file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
//solium-disable linebreak-style pragma solidity ^0.4.24; library ExtendedMath { function limitLessThan(uint a, uint b) internal pure returns(uint c) { if (a > b) return b; return a; } } 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 &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } 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&#39;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; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract ERC20Basic { function totalSupply() public view returns(uint256); function balanceOf(address _who) public view returns(uint256); function transfer(address _to, uint256 _value) public returns(bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns(uint256); function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function approve(address _spender, uint256 _value) public returns(bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal 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(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev 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]; } } 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(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns(bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns(uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _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, uint256 _subtractedValue ) public returns(bool) { uint256 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; } } interface IcaelumVoting { function getTokenProposalDetails() external view returns(address, uint, uint, uint); function getExpiry() external view returns (uint); function getContractType () external view returns (uint); } contract abstractCaelum { function isMasternodeOwner(address _candidate) public view returns(bool); function addToWhitelist(address _ad, uint _amount, uint daysAllowed) internal; function addMasternode(address _candidate) internal returns(uint); function deleteMasternode(uint entityAddress) internal returns(bool success); function getLastPerUser(address _candidate) public view returns (uint); function getMiningReward() public view returns(uint); } contract NewTokenProposal is IcaelumVoting { enum VOTE_TYPE {TOKEN, TEAM} VOTE_TYPE public contractType = VOTE_TYPE.TOKEN; address contractAddress; uint requiredAmount; uint validUntil; uint votingDurationInDays; /** * @dev Create a new vote proposal for an ERC20 token. * @param _contract ERC20 contract * @param _amount How many tokens are required as collateral * @param _valid How long do we accept these tokens on the contract (UNIX timestamp) * @param _voteDuration How many days is this vote available */ constructor(address _contract, uint _amount, uint _valid, uint _voteDuration) public { require(_voteDuration >= 14 && _voteDuration <= 50, "Proposed voting duration does not meet requirements"); contractAddress = _contract; requiredAmount = _amount; validUntil = _valid; votingDurationInDays = _voteDuration; } /** * @dev Returns all details about this proposal */ function getTokenProposalDetails() public view returns(address, uint, uint, uint) { return (contractAddress, requiredAmount, validUntil, uint(contractType)); } /** * @dev Displays the expiry date of contract * @return uint Days valid */ function getExpiry() external view returns (uint) { return votingDurationInDays; } /** * @dev Displays the type of contract * @return uint Enum value {TOKEN, TEAM} */ function getContractType () external view returns (uint){ return uint(contractType); } } contract NewMemberProposal is IcaelumVoting { enum VOTE_TYPE {TOKEN, TEAM} VOTE_TYPE public contractType = VOTE_TYPE.TEAM; address memberAddress; uint totalMasternodes; uint votingDurationInDays; /** * @dev Create a new vote proposal for a team member. * @param _contract Future team member&#39;s address * @param _total How many masternodes do we want to give * @param _voteDuration How many days is this vote available */ constructor(address _contract, uint _total, uint _voteDuration) public { require(_voteDuration >= 14 && _voteDuration <= 50, "Proposed voting duration does not meet requirements"); memberAddress = _contract; totalMasternodes = _total; votingDurationInDays = _voteDuration; } /** * @dev Returns all details about this proposal */ function getTokenProposalDetails() public view returns(address, uint, uint, uint) { return (memberAddress, totalMasternodes, 0, uint(contractType)); } /** * @dev Displays the expiry date of contract * @return uint Days valid */ function getExpiry() external view returns (uint) { return votingDurationInDays; } /** * @dev Displays the type of contract * @return uint Enum value {TOKEN, TEAM} */ function getContractType () external view returns (uint){ return uint(contractType); } } contract CaelumVotings is Ownable { using SafeMath for uint; enum VOTE_TYPE {TOKEN, TEAM} struct Proposals { address tokenContract; uint totalVotes; uint proposedOn; uint acceptedOn; VOTE_TYPE proposalType; } struct Voters { bool isVoter; address owner; uint[] votedFor; } uint MAJORITY_PERCENTAGE_NEEDED = 60; uint MINIMUM_VOTERS_NEEDED = 10; bool public proposalPending; mapping(uint => Proposals) public proposalList; mapping (address => Voters) public voterMap; mapping(uint => address) public voterProposals; uint public proposalCounter; uint public votersCount; uint public votersCountTeam; /** * @notice Define abstract functions for later user */ function isMasternodeOwner(address _candidate) public view returns(bool); function addToWhitelist(address _ad, uint _amount, uint daysAllowed) internal; function addMasternode(address _candidate) internal returns(uint); function updateMasternodeAsTeamMember(address _member) internal returns (bool); function isTeamMember (address _candidate) public view returns (bool); event NewProposal(uint ProposalID); event ProposalAccepted(uint ProposalID); /** * @dev Create a new proposal. * @param _contract Proposal contract address * @return uint ProposalID */ function pushProposal(address _contract) onlyOwner public returns (uint) { if(proposalCounter != 0) require (pastProposalTimeRules (), "You need to wait 90 days before submitting a new proposal."); require (!proposalPending, "Another proposal is pending."); uint _contractType = IcaelumVoting(_contract).getContractType(); proposalList[proposalCounter] = Proposals(_contract, 0, now, 0, VOTE_TYPE(_contractType)); emit NewProposal(proposalCounter); proposalCounter++; proposalPending = true; return proposalCounter.sub(1); } /** * @dev Internal function that handles the proposal after it got accepted. * This function determines if the proposal is a token or team member proposal and executes the corresponding functions. * @return uint Returns the proposal ID. */ function handleLastProposal () internal returns (uint) { uint _ID = proposalCounter.sub(1); proposalList[_ID].acceptedOn = now; proposalPending = false; address _address; uint _required; uint _valid; uint _type; (_address, _required, _valid, _type) = getTokenProposalDetails(_ID); if(_type == uint(VOTE_TYPE.TOKEN)) { addToWhitelist(_address,_required,_valid); } if(_type == uint(VOTE_TYPE.TEAM)) { if(_required != 0) { for (uint i = 0; i < _required; i++) { addMasternode(_address); } } else { addMasternode(_address); } updateMasternodeAsTeamMember(_address); } emit ProposalAccepted(_ID); return _ID; } /** * @dev Rejects the last proposal after the allowed voting time has expired and it&#39;s not accepted. */ function discardRejectedProposal() onlyOwner public returns (bool) { require(proposalPending); require (LastProposalCanDiscard()); proposalPending = false; return (true); } /** * @dev Checks if the last proposal allowed voting time has expired and it&#39;s not accepted. * @return bool */ function LastProposalCanDiscard () public view returns (bool) { uint daysBeforeDiscard = IcaelumVoting(proposalList[proposalCounter - 1].tokenContract).getExpiry(); uint entryDate = proposalList[proposalCounter - 1].proposedOn; uint expiryDate = entryDate + (daysBeforeDiscard * 1 days); if (now >= expiryDate) return true; } /** * @dev Returns all details about a proposal */ function getTokenProposalDetails(uint proposalID) public view returns(address, uint, uint, uint) { return IcaelumVoting(proposalList[proposalID].tokenContract).getTokenProposalDetails(); } /** * @dev Returns if our 90 day cooldown has passed * @return bool */ function pastProposalTimeRules() public view returns (bool) { uint lastProposal = proposalList[proposalCounter - 1].proposedOn; if (now >= lastProposal + 90 days) return true; } /** * @dev Allow any masternode user to become a voter. */ function becomeVoter() public { require (isMasternodeOwner(msg.sender), "User has no masternodes"); require (!voterMap[msg.sender].isVoter, "User Already voted for this proposal"); voterMap[msg.sender].owner = msg.sender; voterMap[msg.sender].isVoter = true; votersCount = votersCount + 1; if (isTeamMember(msg.sender)) votersCountTeam = votersCountTeam + 1; } /** * @dev Allow voters to submit their vote on a proposal. Voters can only cast 1 vote per proposal. * If the proposed vote is about adding Team members, only Team members are able to vote. * A proposal can only be published if the total of votes is greater then MINIMUM_VOTERS_NEEDED. * @param proposalID proposalID */ function voteProposal(uint proposalID) public returns (bool success) { require(voterMap[msg.sender].isVoter, "Sender not listed as voter"); require(proposalID >= 0, "No proposal was selected."); require(proposalID <= proposalCounter, "Proposal out of limits."); require(voterProposals[proposalID] != msg.sender, "Already voted."); if(proposalList[proposalID].proposalType == VOTE_TYPE.TEAM) { require (isTeamMember(msg.sender), "Restricted for team members"); voterProposals[proposalID] = msg.sender; proposalList[proposalID].totalVotes++; if(reachedMajorityForTeam(proposalID)) { // This is the prefered way of handling vote results. It costs more gas but prevents tampering. // If gas is an issue, you can comment handleLastProposal out and call it manually as onlyOwner. handleLastProposal(); return true; } } else { require(votersCount >= MINIMUM_VOTERS_NEEDED, "Not enough voters in existence to push a proposal"); voterProposals[proposalID] = msg.sender; proposalList[proposalID].totalVotes++; if(reachedMajority(proposalID)) { // This is the prefered way of handling vote results. It costs more gas but prevents tampering. // If gas is an issue, you can comment handleLastProposal out and call it manually as onlyOwner. handleLastProposal(); return true; } } } /** * @dev Check if a proposal has reached the majority vote * @param proposalID Token ID * @return bool */ function reachedMajority (uint proposalID) public view returns (bool) { uint getProposalVotes = proposalList[proposalID].totalVotes; if (getProposalVotes >= majority()) return true; } /** * @dev Internal function that calculates the majority * @return uint Total of votes needed for majority */ function majority () internal view returns (uint) { uint a = (votersCount * MAJORITY_PERCENTAGE_NEEDED ); return a / 100; } /** * @dev Check if a proposal has reached the majority vote for a team member * @param proposalID Token ID * @return bool */ function reachedMajorityForTeam (uint proposalID) public view returns (bool) { uint getProposalVotes = proposalList[proposalID].totalVotes; if (getProposalVotes >= majorityForTeam()) return true; } /** * @dev Internal function that calculates the majority * @return uint Total of votes needed for majority */ function majorityForTeam () internal view returns (uint) { uint a = (votersCountTeam * MAJORITY_PERCENTAGE_NEEDED ); return a / 100; } } contract CaelumFundraise is Ownable, BasicToken, abstractCaelum { /** * In no way is Caelum intended to raise funds. We leave this code to demonstrate the potential and functionality. * Should you decide to buy a masternode instead of mining, you can by using this function. Feel free to consider this a tipping jar for our dev team. * We strongly advice to use the `buyMasternode`function, but simply sending Ether to the contract should work as well. */ uint AMOUNT_FOR_MASTERNODE = 50 ether; uint SPOTS_RESERVED = 10; uint COUNTER; bool fundraiseClosed = false; /** * @dev Not recommended way to accept Ether. Can be safely used if no storage operations are called * The contract may revert all the gas because of the gas limitions on the fallback operator. * We leave it in as template for other projects, however, for Caelum the function deposit should be adviced. */ function() payable public { require(msg.value == AMOUNT_FOR_MASTERNODE && msg.value != 0); receivedFunds(); } /** @dev This is the recommended way for users to deposit Ether in return of a masternode. * Users should be encouraged to use this approach as there is not gas risk involved. */ function buyMasternode () payable public { require(msg.value == AMOUNT_FOR_MASTERNODE && msg.value != 0); receivedFunds(); } /** * @dev Forward funds to owner before making any action. owner.transfer will revert if fail. */ function receivedFunds() internal { require(!fundraiseClosed); require (COUNTER <= SPOTS_RESERVED); owner.transfer(msg.value); addMasternode(msg.sender); } } contract CaelumAcceptERC20 is Ownable, CaelumVotings, abstractCaelum { using SafeMath for uint; address[] public tokensList; bool setOwnContract = true; struct _whitelistTokens { address tokenAddress; bool active; uint requiredAmount; uint validUntil; uint timestamp; } mapping(address => mapping(address => uint)) public tokens; mapping(address => _whitelistTokens) acceptedTokens; event Deposit(address token, address user, uint amount, uint balance); event Withdraw(address token, address user, uint amount, uint balance); /** * @dev Return the base rewards. This should be overrided by the miner contract. * Return a base value for standalone usage ONLY. */ function getMiningReward() public view returns(uint) { return 50 * 1e8; } /** * @notice Allow the dev to set it&#39;s own token as accepted payment. * @dev Can be hardcoded in the constructor. Given the contract size, we decided to separate it. * @return bool */ function addOwnToken() onlyOwner public returns (bool) { require(setOwnContract); addToWhitelist(this, 5000 * 1e8, 36500); setOwnContract = false; return true; } // TODO: Set visibility /** * @notice Add a new token as accepted payment method. * @param _token Token contract address. * @param _amount Required amount of this Token as collateral * @param daysAllowed How many days will we accept this token? */ function addToWhitelist(address _token, uint _amount, uint daysAllowed) internal { _whitelistTokens storage newToken = acceptedTokens[_token]; newToken.tokenAddress = _token; newToken.requiredAmount = _amount; newToken.timestamp = now; newToken.validUntil = now + (daysAllowed * 1 days); newToken.active = true; tokensList.push(_token); } /** * @dev internal function to determine if we accept this token. * @param _ad Token contract address * @return bool */ function isAcceptedToken(address _ad) internal view returns(bool) { return acceptedTokens[_ad].active; } /** * @dev internal function to determine the requiredAmount for a specific token. * @param _ad Token contract address * @return bool */ function getAcceptedTokenAmount(address _ad) internal view returns(uint) { return acceptedTokens[_ad].requiredAmount; } /** * @dev internal function to determine if the token is still accepted timewise. * @param _ad Token contract address * @return bool */ function isValid(address _ad) internal view returns(bool) { uint endTime = acceptedTokens[_ad].validUntil; if (block.timestamp < endTime) return true; return false; } /** * @notice Returns an array of all accepted token. You can get more details by calling getTokenDetails function with this address. * @return array Address */ function listAcceptedTokens() public view returns(address[]) { return tokensList; } /** * @notice Returns a full list of the token details * @param token Token contract address */ function getTokenDetails(address token) public view returns(address ad,uint required, bool active, uint valid) { return (acceptedTokens[token].tokenAddress, acceptedTokens[token].requiredAmount,acceptedTokens[token].active, acceptedTokens[token].validUntil); } /** * @notice Public function that allows any user to deposit accepted tokens as collateral to become a masternode. * @param token Token contract address * @param amount Amount to deposit */ function depositCollateral(address token, uint amount) public { require(isAcceptedToken(token), "ERC20 not authorised"); // Should be a token from our list require(amount == getAcceptedTokenAmount(token)); // The amount needs to match our set amount require(isValid(token)); // It should be called within the setup timeframe tokens[token][msg.sender] = tokens[token][msg.sender].add(amount); require(StandardToken(token).transferFrom(msg.sender, this, amount), "error with token"); emit Deposit(token, msg.sender, amount, tokens[token][msg.sender]); addMasternode(msg.sender); } /** * @notice Public function that allows any user to withdraw deposited tokens and stop as masternode * @param token Token contract address * @param amount Amount to withdraw */ function withdrawCollateral(address token, uint amount) public { require(token != 0); // token should be an actual address require(isAcceptedToken(token), "ERC20 not authorised"); // Should be a token from our list require(isMasternodeOwner(msg.sender)); // The sender must be a masternode prior to withdraw require(tokens[token][msg.sender] == amount); // The amount must be exactly whatever is deposited uint amountToWithdraw = tokens[token][msg.sender]; tokens[token][msg.sender] = 0; deleteMasternode(getLastPerUser(msg.sender)); if (!StandardToken(token).transfer(msg.sender, amountToWithdraw)) revert(); emit Withdraw(token, msg.sender, amountToWithdraw, amountToWithdraw); } } contract CaelumMasternode is CaelumFundraise, CaelumAcceptERC20{ using SafeMath for uint; bool onTestnet = false; bool genesisAdded = false; uint masternodeRound; uint masternodeCandidate; uint masternodeCounter; uint masternodeEpoch; uint miningEpoch; uint rewardsProofOfWork; uint rewardsMasternode; uint rewardsGlobal = 50 * 1e8; uint MINING_PHASE_DURATION_BLOCKS = 4500; struct MasterNode { address accountOwner; bool isActive; bool isTeamMember; uint storedIndex; uint startingRound; uint[] indexcounter; } uint[] userArray; address[] userAddressArray; mapping(uint => MasterNode) userByIndex; // UINT masterMapping mapping(address => MasterNode) userByAddress; //masterMapping mapping(address => uint) userAddressIndex; event Deposit(address token, address user, uint amount, uint balance); event Withdraw(address token, address user, uint amount, uint balance); event NewMasternode(address candidateAddress, uint timeStamp); event RemovedMasternode(address candidateAddress, uint timeStamp); /** * @dev Add the genesis accounts */ function addGenesis(address _genesis, bool _team) onlyOwner public { require(!genesisAdded); addMasternode(_genesis); if (_team) { updateMasternodeAsTeamMember(msg.sender); } } /** * @dev Close the genesis accounts */ function closeGenesis() onlyOwner public { genesisAdded = true; // Forever lock this. } /** * @dev Add a user as masternode. Called as internal since we only add masternodes by depositing collateral or by voting. * @param _candidate Candidate address * @return uint Masternode index */ function addMasternode(address _candidate) internal returns(uint) { userByIndex[masternodeCounter].accountOwner = _candidate; userByIndex[masternodeCounter].isActive = true; userByIndex[masternodeCounter].startingRound = masternodeRound + 1; userByIndex[masternodeCounter].storedIndex = masternodeCounter; userByAddress[_candidate].accountOwner = _candidate; userByAddress[_candidate].indexcounter.push(masternodeCounter); userArray.push(userArray.length); masternodeCounter++; emit NewMasternode(_candidate, now); return masternodeCounter - 1; // } /** * @dev Allow us to update a masternode&#39;s round to keep progress * @param _candidate ID of masternode */ function updateMasternode(uint _candidate) internal returns(bool) { userByIndex[_candidate].startingRound++; return true; } /** * @dev Allow us to update a masternode to team member status * @param _member address */ function updateMasternodeAsTeamMember(address _member) internal returns (bool) { userByAddress[_member].isTeamMember = true; return (true); } /** * @dev Let us know if an address is part of the team. * @param _member address */ function isTeamMember (address _member) public view returns (bool) { if (userByAddress[_member].isTeamMember) return true; } /** * @dev Remove a specific masternode * @param _masternodeID ID of the masternode to remove */ function deleteMasternode(uint _masternodeID) internal returns(bool success) { uint rowToDelete = userByIndex[_masternodeID].storedIndex; uint keyToMove = userArray[userArray.length - 1]; userByIndex[_masternodeID].isActive = userByIndex[_masternodeID].isActive = (false); userArray[rowToDelete] = keyToMove; userByIndex[keyToMove].storedIndex = rowToDelete; userArray.length = userArray.length - 1; removeFromUserCounter(_masternodeID); emit RemovedMasternode(userByIndex[_masternodeID].accountOwner, now); return true; } /** * @dev returns what account belongs to a masternode */ function isPartOf(uint mnid) public view returns (address) { return userByIndex[mnid].accountOwner; } /** * @dev Internal function to remove a masternode from a user address if this address holds multpile masternodes * @param index MasternodeID */ function removeFromUserCounter(uint index) internal returns(uint[]) { address belong = isPartOf(index); if (index >= userByAddress[belong].indexcounter.length) return; for (uint i = index; i<userByAddress[belong].indexcounter.length-1; i++){ userByAddress[belong].indexcounter[i] = userByAddress[belong].indexcounter[i+1]; } delete userByAddress[belong].indexcounter[userByAddress[belong].indexcounter.length-1]; userByAddress[belong].indexcounter.length--; return userByAddress[belong].indexcounter; } /** * @dev Primary contract function to update the current user and prepare the next one. * A number of steps have been token to ensure the contract can never run out of gas when looping over our masternodes. */ function setMasternodeCandidate() internal returns(address) { uint hardlimitCounter = 0; while (getFollowingCandidate() == 0x0) { // We must return a value not to break the contract. Require is a secondary killswitch now. require(hardlimitCounter < 6, "Failsafe switched on"); // Choose if loop over revert/require to terminate the loop and return a 0 address. if (hardlimitCounter == 5) return (0); masternodeRound = masternodeRound + 1; masternodeCandidate = 0; hardlimitCounter++; } if (masternodeCandidate == masternodeCounter - 1) { masternodeRound = masternodeRound + 1; masternodeCandidate = 0; } for (uint i = masternodeCandidate; i < masternodeCounter; i++) { if (userByIndex[i].isActive) { if (userByIndex[i].startingRound == masternodeRound) { updateMasternode(i); masternodeCandidate = i; return (userByIndex[i].accountOwner); } } } masternodeRound = masternodeRound + 1; return (0); } /** * @dev Helper function to loop through our masternodes at start and return the correct round */ function getFollowingCandidate() internal view returns(address _address) { uint tmpRound = masternodeRound; uint tmpCandidate = masternodeCandidate; if (tmpCandidate == masternodeCounter - 1) { tmpRound = tmpRound + 1; tmpCandidate = 0; } for (uint i = masternodeCandidate; i < masternodeCounter; i++) { if (userByIndex[i].isActive) { if (userByIndex[i].startingRound == tmpRound) { tmpCandidate = i; return (userByIndex[i].accountOwner); } } } tmpRound = tmpRound + 1; return (0); } /** * @dev Displays all masternodes belonging to a user address. */ function belongsToUser(address userAddress) public view returns(uint[]) { return (userByAddress[userAddress].indexcounter); } /** * @dev Helper function to know if an address owns masternodes */ function isMasternodeOwner(address _candidate) public view returns(bool) { if(userByAddress[_candidate].indexcounter.length <= 0) return false; if (userByAddress[_candidate].accountOwner == _candidate) return true; } /** * @dev Helper function to get the last masternode belonging to a user */ function getLastPerUser(address _candidate) public view returns (uint) { return userByAddress[_candidate].indexcounter[userByAddress[_candidate].indexcounter.length - 1]; } /** * @dev Calculate and set the reward schema for Caelum. * Each mining phase is decided by multiplying the MINING_PHASE_DURATION_BLOCKS with factor 10. * Depending on the outcome (solidity always rounds), we can detect the current stage of mining. * First stage we cut the rewards to 5% to prevent instamining. * Last stage we leave 2% for miners to incentivize keeping miners running. */ function calculateRewardStructures() internal { //ToDo: Set uint _global_reward_amount = getMiningReward(); uint getStageOfMining = miningEpoch / MINING_PHASE_DURATION_BLOCKS * 10; if (getStageOfMining < 10) { rewardsProofOfWork = _global_reward_amount / 100 * 5; rewardsMasternode = 0; return; } if (getStageOfMining > 90) { rewardsProofOfWork = _global_reward_amount / 100 * 2; rewardsMasternode = _global_reward_amount / 100 * 98; return; } uint _mnreward = (_global_reward_amount / 100) * getStageOfMining; uint _powreward = (_global_reward_amount - _mnreward); setBaseRewards(_powreward, _mnreward); } function setBaseRewards(uint _pow, uint _mn) internal { rewardsMasternode = _mn; rewardsProofOfWork = _pow; } /** * @dev Executes the masternode flow. Should be called after mining a block. */ function _arrangeMasternodeFlow() internal { calculateRewardStructures(); setMasternodeCandidate(); miningEpoch++; } /** * @dev Executes the masternode flow. Should be called after mining a block. * This is an emergency manual loop method. */ function _emergencyLoop() onlyOwner public { calculateRewardStructures(); setMasternodeCandidate(); miningEpoch++; } function masternodeInfo(uint index) public view returns ( address, bool, uint, uint ) { return ( userByIndex[index].accountOwner, userByIndex[index].isActive, userByIndex[index].storedIndex, userByIndex[index].startingRound ); } function contractProgress() public view returns ( uint epoch, uint candidate, uint round, uint miningepoch, uint globalreward, uint powreward, uint masternodereward, uint usercounter ) { return ( masternodeEpoch, masternodeCandidate, masternodeRound, miningEpoch, getMiningReward(), rewardsProofOfWork, rewardsMasternode, masternodeCounter ); } } contract CaelumMiner is StandardToken, CaelumMasternode { using SafeMath for uint; using ExtendedMath for uint; string public symbol = "CLM"; string public name = "Caelum Token"; uint8 public decimals = 8; uint256 public totalSupply = 2100000000000000; uint public latestDifficultyPeriodStarted; uint public epochCount; uint public baseMiningReward = 50; uint public blocksPerReadjustment = 512; uint public _MINIMUM_TARGET = 2 ** 16; uint public _MAXIMUM_TARGET = 2 ** 234; uint public rewardEra = 0; uint public maxSupplyForEra; uint public MAX_REWARD_ERA = 39; uint public MINING_RATE_FACTOR = 60; //mint the token 60 times less often than ether //difficulty adjustment parameters- be careful modifying these uint public MAX_ADJUSTMENT_PERCENT = 100; uint public TARGET_DIVISOR = 2000; uint public QUOTIENT_LIMIT = TARGET_DIVISOR.div(2); mapping(bytes32 => bytes32) solutionForChallenge; mapping(address => mapping(address => uint)) allowed; bytes32 public challengeNumber; uint public difficulty; uint public tokensMinted; struct Statistics { address lastRewardTo; uint lastRewardAmount; uint lastRewardEthBlockNumber; uint lastRewardTimestamp; } Statistics public statistics; event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); event RewardMasternode(address candidate, uint amount); constructor() public { tokensMinted = 0; maxSupplyForEra = totalSupply.div(2); difficulty = _MAXIMUM_TARGET; latestDifficultyPeriodStarted = block.number; _newEpoch(0); balances[msg.sender] = balances[msg.sender].add(420000 * 1e8); // 2% Premine as determined by the community meeting. emit Transfer(this, msg.sender, 420000 * 1e8); } function mint(uint256 nonce, bytes32 challenge_digest) public returns(bool success) { // perform the hash function validation _hash(nonce, challenge_digest); _arrangeMasternodeFlow(); uint rewardAmount = _reward(); uint rewardMasternode = _reward_masternode(); tokensMinted += rewardAmount.add(rewardMasternode); uint epochCounter = _newEpoch(nonce); _adjustDifficulty(); statistics = Statistics(msg.sender, rewardAmount, block.number, now); emit Mint(msg.sender, rewardAmount, epochCounter, challengeNumber); return true; } function _newEpoch(uint256 nonce) internal returns(uint) { if (tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < MAX_REWARD_ERA) { rewardEra = rewardEra + 1; } maxSupplyForEra = totalSupply - totalSupply.div(2 ** (rewardEra + 1)); epochCount = epochCount.add(1); challengeNumber = blockhash(block.number - 1); return (epochCount); } function _hash(uint256 nonce, bytes32 challenge_digest) internal returns(bytes32 digest) { digest = keccak256(challengeNumber, msg.sender, nonce); if (digest != challenge_digest) revert(); if (uint256(digest) > difficulty) revert(); bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if (solution != 0x0) revert(); //prevent the same answer from awarding twice } function _reward() internal returns(uint) { uint _pow = rewardsProofOfWork; balances[msg.sender] = balances[msg.sender].add(_pow); emit Transfer(this, msg.sender, _pow); return _pow; } function _reward_masternode() internal returns(uint) { uint _mnReward = rewardsMasternode; if (masternodeCounter == 0) return 0; address _mnCandidate = userByIndex[masternodeCandidate].accountOwner; if (_mnCandidate == 0x0) return 0; balances[_mnCandidate] = balances[_mnCandidate].add(_mnReward); emit Transfer(this, _mnCandidate, _mnReward); emit RewardMasternode(_mnCandidate, _mnReward); return _mnReward; } //DO NOT manually edit this method unless you know EXACTLY what you are doing function _adjustDifficulty() internal returns(uint) { //every so often, readjust difficulty. Dont readjust when deploying if (epochCount % blocksPerReadjustment != 0) { return difficulty; } uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted; //assume 360 ethereum blocks per hour //we want miners to spend 10 minutes to mine each &#39;block&#39;, about 60 ethereum blocks = one 0xbitcoin epoch uint epochsMined = blocksPerReadjustment; uint targetEthBlocksPerDiffPeriod = epochsMined * MINING_RATE_FACTOR; //if there were less eth blocks passed in time than expected if (ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod) { uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div(ethBlocksSinceLastDifficultyPeriod); uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT); // If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100. //make it harder difficulty = difficulty.sub(difficulty.div(TARGET_DIVISOR).mul(excess_block_pct_extra)); //by up to 50 % } else { uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div(targetEthBlocksPerDiffPeriod); uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT); //always between 0 and 1000 //make it easier difficulty = difficulty.add(difficulty.div(TARGET_DIVISOR).mul(shortage_block_pct_extra)); //by up to 50 % } latestDifficultyPeriodStarted = block.number; if (difficulty < _MINIMUM_TARGET) //very difficult { difficulty = _MINIMUM_TARGET; } if (difficulty > _MAXIMUM_TARGET) //very easy { difficulty = _MAXIMUM_TARGET; } } //this is a recent ethereum block hash, used to prevent pre-mining future blocks function getChallengeNumber() public view returns(bytes32) { return challengeNumber; } //the number of zeroes the digest of the PoW solution requires. Auto adjusts function getMiningDifficulty() public view returns(uint) { return _MAXIMUM_TARGET.div(difficulty); } function getMiningTarget() public view returns(uint) { return difficulty; } function getMiningReward() public view returns(uint) { return (baseMiningReward * 1e8).div(2 ** rewardEra); } //help debug mining software function getMintDigest( uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number ) public view returns(bytes32 digesttest) { bytes32 digest = keccak256(challenge_number, msg.sender, nonce); return digest; } //help debug mining software function checkMintSolution( uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget ) public view returns(bool success) { bytes32 digest = keccak256(challenge_number, msg.sender, nonce); if (uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } }
Close the genesis accounts/
function closeGenesis() onlyOwner public { }
6,632,814
./full_match/1/0x87AAdE1067Ed0276ec9BEf6db8E17Abe27A6B454/sources/contracts/TruthPost.sol
@inheritdoc ITruthPost This can happen if arbitration fee gets lowered in between contributions.
function fundAppeal(uint256 _disputeID, RulingOptions _supportedRuling) external payable override returns (bool fullyFunded) { DisputeData storage dispute = disputes[_disputeID]; RulingOptions currentRuling = RulingOptions(ARBITRATOR.currentRuling(_disputeID)); uint256 basicCost; uint256 totalCost; { (uint256 appealWindowStart, uint256 appealWindowEnd) = ARBITRATOR.appealPeriod(_disputeID); uint256 multiplier; if (_supportedRuling == currentRuling) { require(block.timestamp < appealWindowEnd, "Funding must be made within the appeal period."); multiplier = WINNER_STAKE_MULTIPLIER; require( block.timestamp < (appealWindowStart + (((appealWindowEnd - appealWindowStart) * LOSER_APPEAL_PERIOD_MULTIPLIER) / MULTIPLIER_DENOMINATOR)), "Funding must be made within the first half appeal period." ); multiplier = LOSER_STAKE_MULTIPLIER; } basicCost = ARBITRATOR.appealCost(_disputeID, categoryToArbitratorExtraData[dispute.articleCategory]); totalCost = basicCost + ((basicCost * (multiplier)) / MULTIPLIER_DENOMINATOR); } RulingOptions supportedRulingOutcome = RulingOptions(_supportedRuling); uint256 lastRoundIndex = dispute.rounds.length - 1; Round storage lastRound = dispute.rounds[lastRoundIndex]; require(!lastRound.hasPaid[uint256(supportedRulingOutcome)], "Appeal fee has already been paid."); uint256 contribution; { uint256 paidSoFar = lastRound.totalPerRuling[uint256(supportedRulingOutcome)]; if (paidSoFar >= totalCost) { contribution = 0; contribution = totalCost - paidSoFar > msg.value ? msg.value : totalCost - paidSoFar; } } emit Contribution(_disputeID, lastRoundIndex, _supportedRuling, msg.sender, contribution); lastRound.contributions[msg.sender][uint256(supportedRulingOutcome)] += contribution; lastRound.totalPerRuling[uint256(supportedRulingOutcome)] += contribution; if (lastRound.totalPerRuling[uint256(supportedRulingOutcome)] >= totalCost) { lastRound.totalClaimableAfterExpenses += lastRound.totalPerRuling[uint256(supportedRulingOutcome)]; lastRound.hasPaid[uint256(supportedRulingOutcome)] = true; emit RulingFunded(_disputeID, lastRoundIndex, _supportedRuling); } if ( lastRound.hasPaid[uint256(RulingOptions.ChallengeFailed)] && lastRound.hasPaid[uint256(RulingOptions.Debunked)] ) { dispute.rounds.push(); lastRound.totalClaimableAfterExpenses -= basicCost; } return lastRound.hasPaid[uint256(supportedRulingOutcome)]; }
4,921,982
pragma solidity 0.4.15; /* Crypto Market Prices via Ethereum Smart Contract A community driven smart contract that lets your contracts use fiat amounts in USD, EURO, and GBP. Need to charge $10.50 for a contract call? With this contract, you can convert ETH and other crypto&#39;s. Repo: https://github.com/hunterlong/fiatcontract Website: https://fiatcontract.com Examples: FiatContract price = FiatContract(CONTRACT_ADDRESS); uint256 ethCent = price.USD(0); // returns $0.01 worth of ETH in USD. uint256 weiAmount = ethCent * 2500 // returns $25.00 worth of ETH in USD require(msg.value == weiAmount); // require $25.00 worth of ETH as a payment Please look at Repo or Website to get Currency ID values. @author Hunter Long */ contract FiatContract { mapping(uint => Token) public tokens; address public sender; address public creator; event NewPrice(uint id, string token); event DeletePrice(uint id); event UpdatedPrice(uint id); event RequestUpdate(uint id); event Donation(address from); struct Token { string name; uint256 eth; uint256 usd; uint256 eur; uint256 gbp; uint block; } // initialize function function FiatContract() { creator = msg.sender; sender = msg.sender; } // returns the Token struct function getToken(uint _id) internal constant returns (Token) { return tokens[_id]; } // returns rate price of coin related to ETH. function ETH(uint _id) constant returns (uint256) { return tokens[_id].eth; } // returns 0.01 value in United States Dollar function USD(uint _id) constant returns (uint256) { return tokens[_id].usd; } // returns 0.01 value in Euro function EUR(uint _id) constant returns (uint256) { return tokens[_id].eur; } // returns 0.01 value in British Pound function GBP(uint _id) constant returns (uint256) { return tokens[_id].gbp; } // returns block when price was updated last function updatedAt(uint _id) constant returns (uint) { return tokens[_id].block; } // update market rates in USD, EURO, and GBP for a specific coin function update(uint id, string _token, uint256 eth, uint256 usd, uint256 eur, uint256 gbp) external { require(msg.sender==sender); tokens[id] = Token(_token, eth, usd, eur, gbp, block.number); NewPrice(id, _token); } // delete a token from the contract function deleteToken(uint id) { require(msg.sender==creator); DeletePrice(id); delete tokens[id]; } // change creator address function changeCreator(address _creator){ require(msg.sender==creator); creator = _creator; } // change sender address function changeSender(address _sender){ require(msg.sender==creator); sender = _sender; } // execute function for creator if ERC20&#39;s get stuck in this wallet function execute(address _to, uint _value, bytes _data) external returns (bytes32 _r) { require(msg.sender==creator); require(_to.call.value(_value)(_data)); return 0; } // default function so this contract can accept ETH with low gas limits. function() payable { } // public function for requesting an updated price from server // using this function requires a payment of $0.35 USD function requestUpdate(uint id) external payable { uint256 weiAmount = tokens[0].usd * 35; require(msg.value >= weiAmount); sender.transfer(msg.value); RequestUpdate(id); } // donation function that get forwarded to the contract updater function donate() external payable { require(msg.value >= 0); sender.transfer(msg.value); Donation(msg.sender); } }
returns block when price was updated last
function updatedAt(uint _id) constant returns (uint) { return tokens[_id].block; }
6,818,301
// SPDX-License-Identifier: Unlicensed /* Join our socials, Telegram : https://t.me/cthulhuerc Website : https://cthulhu.site/ */ pragma solidity ^0.8.4; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(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; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Address { function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; 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; } } // 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 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 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.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract Cthulhu is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; event TokenBurn(address indexed from, uint256 value); event SetLiquidityFee(uint256 amount); event SetMarketingFee(uint256 amount); event SetBurnFee(uint256 amount); string private _name = "Cthulhu"; string private _symbol = "CTHULHU"; uint8 private _decimals = 18; uint256 private _totalSupply = 100000 * 10**9 * 10**_decimals; address payable public marketingAddress = payable(0xddbe42ed35582a6457d712cc6e4D408537A301c1); address public devandmarketingWalletToken = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public constant deadAddress = 0x000000000000000000000000000000000000dEaD; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) private _isExcludedFromMaxBalance; uint256 private constant _maxFees = 25; uint256 private _totalFees; uint256 private _totalFeesToContract; uint256 private _liquidityFee; uint256 private _burnFee; uint256 private _devmarketingFee; uint256 private _maxBalance; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; uint256 private _liquifyThreshhold; bool inSwapAndLiquify; modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFees[owner()] = true; _isExcludedFromFees[address(this)] = true; _isExcludedFromMaxBalance[owner()] = true; _isExcludedFromMaxBalance[address(this)] = true; _isExcludedFromMaxBalance[uniswapV2Pair] = true; _liquidityFee = 2; _devmarketingFee = 14; _burnFee = 2; _totalFees = _liquidityFee.add(_devmarketingFee).add(_burnFee); _totalFeesToContract = _liquidityFee.add(_devmarketingFee); _liquifyThreshhold = 10 * 10**9 * 10**_decimals; _maxBalance = 2000 * 10**9 * 10**_decimals; _balances[_msgSender()] = _totalSupply; emit Transfer(address(0), _msgSender(), _totalSupply); } receive() external payable {} 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 _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _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 _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 setMarketingAddress(address payable newMarketingAddress) external onlyOwner() { marketingAddress = newMarketingAddress; } function setLiquidityFeePercent(uint256 newLiquidityFee) external onlyOwner() { require(!inSwapAndLiquify, "inSwapAndLiquify"); require(newLiquidityFee.add(_burnFee).add(_devmarketingFee) <= _maxFees, "Fees are too high."); _liquidityFee = newLiquidityFee; _totalFees = _liquidityFee.add(_devmarketingFee).add(_burnFee); _totalFeesToContract = _liquidityFee.add(_devmarketingFee); emit SetLiquidityFee(_liquidityFee); } function setMarketingFeePercent(uint256 newMarketingFee) external onlyOwner() { require(!inSwapAndLiquify, "inSwapAndLiquify"); require(_liquidityFee.add(_burnFee).add(newMarketingFee) <= _maxFees, "Fees are too high."); _devmarketingFee = newMarketingFee; _totalFees = _liquidityFee.add(_devmarketingFee).add(_burnFee); _totalFeesToContract = _liquidityFee.add(_devmarketingFee); emit SetMarketingFee(_devmarketingFee); } function setBurnFeePercent(uint256 newBurnFee) external onlyOwner() { require(_liquidityFee.add(newBurnFee).add(_devmarketingFee) <= _maxFees, "Fees are too high."); _burnFee = newBurnFee; _totalFees = _liquidityFee.add(_devmarketingFee).add(_burnFee); emit SetBurnFee(_burnFee); } function setLiquifyThreshhold(uint256 newLiquifyThreshhold) external onlyOwner() { _liquifyThreshhold = newLiquifyThreshhold; } function setdevandMarketingWalletToken(address _devandmarketingWalletToken) external onlyOwner(){ devandmarketingWalletToken = _devandmarketingWalletToken; } function setMaxBalance(uint256 newMaxBalance) external onlyOwner(){ // Minimum _maxBalance is 0.5% of _totalSupply require(newMaxBalance >= _totalSupply.mul(5).div(1000)); _maxBalance = newMaxBalance; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function excludeFromFees(address account) public onlyOwner { _isExcludedFromFees[account] = true; } function includeInFees(address account) public onlyOwner { _isExcludedFromFees[account] = false; } function isExcludedFromMaxBalance(address account) public view returns(bool) { return _isExcludedFromMaxBalance[account]; } function excludeFromMaxBalance(address account) public onlyOwner { _isExcludedFromMaxBalance[account] = true; } function includeInMaxBalance(address account) public onlyOwner { _isExcludedFromMaxBalance[account] = false; } function totalFees() public view returns (uint256) { return _totalFees; } function liquidityFee() public view returns (uint256) { return _liquidityFee; } function marketingFee() public view returns (uint256) { return _devmarketingFee; } function burnFee() public view returns (uint256) { return _burnFee; } function maxFees() public pure returns (uint256) { return _maxFees; } function liquifyThreshhold() public view returns(uint256){ return _liquifyThreshhold; } function maxBalance() public view returns (uint256) { return _maxBalance; } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); // Make sure that: Balance + Buy Amount <= _maxBalance if( from != owner() && // Not from Owner to != owner() && // Not to Owner !_isExcludedFromMaxBalance[to] // is excludedFromMaxBalance ){ require( balanceOf(to).add(amount) <= _maxBalance, "Max Balance is reached." ); } // Swap Fees if( to == uniswapV2Pair && // Sell !inSwapAndLiquify && // Swap is not locked balanceOf(address(this)) >= _liquifyThreshhold && // liquifyThreshhold is reached _totalFeesToContract > 0 && // LiquidityFee + MarketingFee > 0 from != owner() && // Not from Owner to != owner() // Not to Owner ) { collectFees(); } // Take Fees if( !(_isExcludedFromFees[from] || _isExcludedFromFees[to]) && _totalFees > 0 ) { uint256 feesToContract = amount.mul(_totalFeesToContract).div(100); uint256 toBurnAmount = amount.mul(_burnFee).div(100); amount = amount.sub(feesToContract.add(toBurnAmount)); transferToken(from, address(this), feesToContract); transferToken(from, deadAddress, toBurnAmount); emit TokenBurn(from, toBurnAmount); } transferToken(from, to, amount); } function collectFees() private lockTheSwap { uint256 liquidityTokensToSell = balanceOf(address(this)).mul(_liquidityFee).div(_totalFeesToContract); uint256 marketingTokensToSell = balanceOf(address(this)).mul(_devmarketingFee).div(_totalFeesToContract); // Get collected Liquidity Fees swapAndLiquify(liquidityTokensToSell); // Get collected Marketing Fees swapAndSendToFee(marketingTokensToSell); } function swapAndLiquify(uint256 tokens) private { uint256 half = tokens.div(2); uint256 otherHalf = tokens.sub(half); // current ETH balance uint256 initialBalance = address(this).balance; swapTokensForEth(half); // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); addLiquidity(otherHalf, newBalance); } function swapAndSendToFee(uint256 tokens) private { swapTokensForMarketingToken(tokens); // Transfer sold Token to marketingWallet IERC20(devandmarketingWalletToken).transfer(marketingAddress, IERC20(devandmarketingWalletToken).balanceOf(address(this))); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function swapTokensForMarketingToken(uint256 tokenAmount) private { address[] memory path = new address[](3); path[0] = address(this); path[1] = uniswapV2Router.WETH(); path[2] = devandmarketingWalletToken; _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, 0, address(0), block.timestamp ); } function transferToken(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"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } }
Transfer sold Token to marketingWallet
function swapAndSendToFee(uint256 tokens) private { swapTokensForMarketingToken(tokens); IERC20(devandmarketingWalletToken).transfer(marketingAddress, IERC20(devandmarketingWalletToken).balanceOf(address(this))); }
631,132
// Contracts by dYdX Foundation. Individual files are released under different licenses. // // https://dydx.community // https://github.com/dydxfoundation/governance-contracts // // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../dependencies/open-zeppelin/SafeERC20.sol'; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SM1Admin } from '../v1_1/impl/SM1Admin.sol'; import { SM1Getters } from '../v1_1/impl/SM1Getters.sol'; import { SM1Operators } from '../v1_1/impl/SM1Operators.sol'; import { SM1Slashing } from '../v1_1/impl/SM1Slashing.sol'; import { SM1Staking } from '../v1_1/impl/SM1Staking.sol'; /** * @title SafetyModuleV2 * @author dYdX * * @notice Contract for staking tokens, which may be slashed by the permissioned slasher. * * NOTE: Most functions will revert if epoch zero has not started. */ contract SafetyModuleV2 is SM1Slashing, SM1Operators, SM1Admin, SM1Getters { using SafeERC20 for IERC20; // ============ Constants ============ string public constant EIP712_DOMAIN_NAME = 'dYdX Safety Module'; string public constant EIP712_DOMAIN_VERSION = '1'; bytes32 public constant EIP712_DOMAIN_SCHEMA_HASH = keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ); // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) SM1Staking(stakedToken, rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ External Functions ============ /** * @notice Initializer for v2, intended to fix the deployment bug that affected v1. * * Responsible for the following: * * 1. Funds recovery and staker compensation: * - Transfer all Safety Module DYDX to the recovery contract. * - Transfer compensation amount from the rewards treasury to the recovery contract. * * 2. Storage recovery and cleanup: * - Set the _EXCHANGE_RATE_ to EXCHANGE_RATE_BASE. * - Clean up invalid storage values at slots 115 and 125. * * @param recoveryContract The address of the contract which will distribute * recovered funds to stakers. * @param recoveryCompensationAmount Amount to transfer out of the rewards treasury, for staker * compensation, on top of the return of staked funds. */ function initialize( address recoveryContract, uint256 recoveryCompensationAmount ) external initializer { // Funds recovery and staker compensation. uint256 balance = STAKED_TOKEN.balanceOf(address(this)); STAKED_TOKEN.safeTransfer(recoveryContract, balance); REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recoveryContract, recoveryCompensationAmount); // Storage recovery and cleanup. __SM1ExchangeRate_init(); // solhint-disable-next-line no-inline-assembly assembly { sstore(115, 0) sstore(125, 0) } } // ============ Internal Functions ============ /** * @dev Returns the revision of the implementation contract. * * @return The revision number. */ function getRevision() internal pure override returns (uint256) { return 2; } } // 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; /** * @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: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Roles } from './SM1Roles.sol'; import { SM1StakedBalances } from './SM1StakedBalances.sol'; /** * @title SM1Admin * @author dYdX * * @dev Admin-only functions. */ abstract contract SM1Admin is SM1StakedBalances, SM1Roles { 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. * * @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, 'SM1Admin: Started epoch zero' ); _setEpochParameters(interval, offset); return; } // 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, 'SM1Admin: Changed epochs' ); } /** * @notice Set the blackout window, during which one cannot request withdrawals of staked funds. */ function setBlackoutWindow( uint256 blackoutWindow ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { _setBlackoutWindow(blackoutWindow); } /** * @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); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { Math } from '../../../utils/Math.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1Getters * @author dYdX * * @dev Some external getter functions. */ abstract contract SM1Getters is SM1Storage { using SafeMath for uint256; // ============ External Functions ============ /** * @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 (SM1Types.EpochParameters memory) { return _EPOCH_PARAMETERS_; } /** * @notice The period of time at the end of each epoch in which withdrawals cannot be requested. * * @return The blackout window duration, in seconds. */ function getBlackoutWindow() external view returns (uint256) { return _BLACKOUT_WINDOW_; } /** * @notice Get the domain separator used for EIP-712 signatures. * * @return The EIP-712 domain separator. */ function getDomainSeparator() external view returns (bytes32) { return _DOMAIN_SEPARATOR_; } /** * @notice The value of one underlying token, in the units used for staked balances, denominated * as a mutiple of EXCHANGE_RATE_BASE for additional precision. * * To convert from an underlying amount to a staked amount, multiply by the exchange rate. * * @return The exchange rate. */ function getExchangeRate() external view returns (uint256) { return _EXCHANGE_RATE_; } /** * @notice Get an exchange rate snapshot. * * @param index The index number of the exchange rate snapshot. * * @return The snapshot struct with `blockNumber` and `value` fields. */ function getExchangeRateSnapshot( uint256 index ) external view returns (SM1Types.Snapshot memory) { return _EXCHANGE_RATE_SNAPSHOTS_[index]; } /** * @notice Get the number of exchange rate snapshots. * * @return The number of snapshots that have been taken of the exchange rate. */ function getExchangeRateSnapshotCount() external view returns (uint256) { return _EXCHANGE_RATE_SNAPSHOT_COUNT_; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SM1Roles } from './SM1Roles.sol'; import { SM1Staking } from './SM1Staking.sol'; /** * @title SM1Operators * @author dYdX * * @dev Actions which may be called by authorized operators, nominated by the contract owner. * * There are two 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. */ abstract contract SM1Operators is SM1Staking, SM1Roles { 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 ); // ============ 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 stakeAmount The amount of stake to move from the active to the inactive balance. */ function requestWithdrawalFor( address staker, uint256 stakeAmount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _requestWithdrawal(staker, stakeAmount); emit OperatorWithdrawalRequestedFor(staker, stakeAmount, 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 stakeAmount The amount of stake to withdraw from the staker's inactive balance. */ function withdrawStakeFor( address staker, address recipient, uint256 stakeAmount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _withdrawStake(staker, recipient, stakeAmount); emit OperatorWithdrewStakeFor(staker, recipient, stakeAmount, 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; } } // SPDX-License-Identifier: AGPL-3.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 { SM1Types } from '../lib/SM1Types.sol'; import { SM1Roles } from './SM1Roles.sol'; import { SM1Staking } from './SM1Staking.sol'; /** * @title SM1Slashing * @author dYdX * * @dev Provides the slashing function for removing funds from the contract. * * SLASHING: * * All funds in the contract, active or inactive, are slashable. Slashes are recorded by updating * the exchange rate, and to simplify the technical implementation, we disallow full slashes. * To reduce the possibility of overflow in the exchange rate, we place an upper bound on the * fraction of funds that may be slashed in a single slash. * * Warning: Slashing is not possible if the slash would cause the exchange rate to overflow. * * REWARDS AND GOVERNANCE POWER ACCOUNTING: * * Since all slashes are accounted for by a global exchange rate, slashes do not require any * update to staked balances. The earning of rewards is unaffected by slashes. * * Governance power takes slashes into account by using snapshots of the exchange rate inside * the getPowerAtBlock() function. Note that getPowerAtBlock() returns the governance power as of * the end of the specified block. */ abstract contract SM1Slashing is SM1Staking, SM1Roles { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @notice The maximum fraction of funds that may be slashed in a single slash (numerator). uint256 public constant MAX_SLASH_NUMERATOR = 95; /// @notice The maximum fraction of funds that may be slashed in a single slash (denominator). uint256 public constant MAX_SLASH_DENOMINATOR = 100; // ============ Events ============ event Slashed( uint256 amount, address recipient, uint256 newExchangeRate ); // ============ External Functions ============ /** * @notice Slash staked token balances and withdraw those funds to the specified address. * * @param requestedSlashAmount The request slash amount, denominated in the underlying token. * @param recipient The address to receive the slashed tokens. * * @return The amount slashed, denominated in the underlying token. */ function slash( uint256 requestedSlashAmount, address recipient ) external onlyRole(SLASHER_ROLE) nonReentrant returns (uint256) { uint256 underlyingBalance = STAKED_TOKEN.balanceOf(address(this)); if (underlyingBalance == 0) { return 0; } // Get the slash amount and remaining amount. Note that remainingAfterSlash is nonzero. uint256 maxSlashAmount = underlyingBalance.mul(MAX_SLASH_NUMERATOR).div(MAX_SLASH_DENOMINATOR); uint256 slashAmount = Math.min(requestedSlashAmount, maxSlashAmount); uint256 remainingAfterSlash = underlyingBalance.sub(slashAmount); if (slashAmount == 0) { return 0; } // Update the exchange rate. // // Warning: Can revert if the max exchange rate is exceeded. uint256 newExchangeRate = updateExchangeRate(underlyingBalance, remainingAfterSlash); // Transfer the slashed token. STAKED_TOKEN.safeTransfer(recipient, slashAmount); emit Slashed(slashAmount, recipient, newExchangeRate); return slashAmount; } } // SPDX-License-Identifier: AGPL-3.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 { SM1Types } from '../lib/SM1Types.sol'; import { SM1ERC20 } from './SM1ERC20.sol'; import { SM1StakedBalances } from './SM1StakedBalances.sol'; /** * @title SM1Staking * @author dYdX * * @dev External functions for stakers. See SM1StakedBalances for details on staker accounting. * * UNDERLYING AND STAKED AMOUNTS: * * We distinguish between underlying amounts and stake amounts. An underlying amount is denoted * in the original units of the token being staked. A stake amount is adjusted by the exchange * rate, which can increase due to slashing. Before any slashes have occurred, the exchange rate * is equal to one. */ abstract contract SM1Staking is SM1StakedBalances, SM1ERC20 { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Events ============ event Staked( address indexed staker, address spender, uint256 underlyingAmount, uint256 stakeAmount ); event WithdrawalRequested( address indexed staker, uint256 stakeAmount ); event WithdrewStake( address indexed staker, address recipient, uint256 underlyingAmount, uint256 stakeAmount ); // ============ Constants ============ IERC20 public immutable STAKED_TOKEN; // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) SM1StakedBalances(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) { STAKED_TOKEN = stakedToken; } // ============ External Functions ============ /** * @notice Deposit and stake funds. These funds are active and start earning rewards immediately. * * @param underlyingAmount The amount of underlying token to stake. */ function stake( uint256 underlyingAmount ) external nonReentrant { _stake(msg.sender, underlyingAmount); } /** * @notice Deposit and stake on behalf of another address. * * @param staker The staker who will receive the stake. * @param underlyingAmount The amount of underlying token to stake. */ function stakeFor( address staker, uint256 underlyingAmount ) external nonReentrant { _stake(staker, underlyingAmount); } /** * @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 stakeAmount The amount of stake to move from the active to the inactive balance. */ function requestWithdrawal( uint256 stakeAmount ) external nonReentrant { _requestWithdrawal(msg.sender, stakeAmount); } /** * @notice Withdraw the sender's inactive funds, and send to the specified recipient. * * @param recipient The address that should receive the funds. * @param stakeAmount The amount of stake to withdraw from the sender's inactive balance. */ function withdrawStake( address recipient, uint256 stakeAmount ) external nonReentrant { _withdrawStake(msg.sender, recipient, stakeAmount); } /** * @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 stakeAmount = getStakeAvailableToWithdraw(msg.sender); _withdrawStake(msg.sender, recipient, stakeAmount); return stakeAmount; } /** * @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 for a given staker to withdraw. * * @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. return getInactiveBalanceCurrentEpoch(staker); } // ============ Internal Functions ============ function _stake( address staker, uint256 underlyingAmount ) internal { // Convert using the exchange rate. uint256 stakeAmount = stakeAmountFromUnderlyingAmount(underlyingAmount); // Update staked balances and delegate snapshots. _increaseCurrentAndNextActiveBalance(staker, stakeAmount); _moveDelegatesForTransfer(address(0), staker, stakeAmount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), underlyingAmount); emit Staked(staker, msg.sender, underlyingAmount, stakeAmount); emit Transfer(address(0), msg.sender, stakeAmount); } function _requestWithdrawal( address staker, uint256 stakeAmount ) internal { require( !inBlackoutWindow(), 'SM1Staking: 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( stakeAmount <= requestableBalance, 'SM1Staking: Withdraw request exceeds next active balance' ); // Move amount from active to inactive in the next epoch. _moveNextBalanceActiveToInactive(staker, stakeAmount); emit WithdrawalRequested(staker, stakeAmount); } function _withdrawStake( address staker, address recipient, uint256 stakeAmount ) internal { // Get staker withdrawable balance and revert if there is not enough to withdraw. uint256 withdrawableBalance = getInactiveBalanceCurrentEpoch(staker); require( stakeAmount <= withdrawableBalance, 'SM1Staking: Withdraw amount exceeds staker inactive balance' ); // Update staked balances and delegate snapshots. _decreaseCurrentAndNextInactiveBalance(staker, stakeAmount); _moveDelegatesForTransfer(staker, address(0), stakeAmount); // Convert using the exchange rate. uint256 underlyingAmount = underlyingAmountFromStakeAmount(stakeAmount); // Transfer token to the recipient. STAKED_TOKEN.safeTransfer(recipient, underlyingAmount); emit Transfer(msg.sender, address(0), stakeAmount); emit WithdrewStake(staker, recipient, underlyingAmount, stakeAmount); } } // 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: 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; library SM1Types { /** * @dev The parameters used to convert a timestamp to an epoch number. */ struct EpochParameters { uint128 interval; uint128 offset; } /** * @dev Snapshot of a value at a specific block, used to track historical governance power. */ struct Snapshot { uint256 blockNumber; uint256 value; } /** * @dev A balance, possibly with a change scheduled for the next epoch. * * @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`. */ struct StoredBalance { uint16 currentEpoch; uint240 currentEpochBalance; uint240 nextEpochBalance; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1Roles * @author dYdX * * @dev Defines roles used in the SafetyModuleV1 contract. The hierarchy of roles and powers * of each role are described below. * * Roles: * * OWNER_ROLE * | -> May add or remove addresses from any of the roles below. * | * +-- SLASHER_ROLE * | -> Can slash staked token balances and withdraw those funds. * | * +-- 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. * | * +-- 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). */ abstract contract SM1Roles is SM1Storage { bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE'); bytes32 public constant SLASHER_ROLE = keccak256('SLASHER_ROLE'); bytes32 public constant EPOCH_PARAMETERS_ROLE = keccak256('EPOCH_PARAMETERS_ROLE'); bytes32 public constant REWARDS_RATE_ROLE = keccak256('REWARDS_RATE_ROLE'); bytes32 public constant CLAIM_OPERATOR_ROLE = keccak256('CLAIM_OPERATOR_ROLE'); bytes32 public constant STAKE_OPERATOR_ROLE = keccak256('STAKE_OPERATOR_ROLE'); function __SM1Roles_init() internal { // Assign roles to the sender. // // The 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(SLASHER_ROLE, msg.sender); _setupRole(EPOCH_PARAMETERS_ROLE, msg.sender); _setupRole(REWARDS_RATE_ROLE, msg.sender); // Set OWNER_ROLE as the admin of all roles. _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); _setRoleAdmin(SLASHER_ROLE, OWNER_ROLE); _setRoleAdmin(EPOCH_PARAMETERS_ROLE, OWNER_ROLE); _setRoleAdmin(REWARDS_RATE_ROLE, OWNER_ROLE); _setRoleAdmin(CLAIM_OPERATOR_ROLE, OWNER_ROLE); _setRoleAdmin(STAKE_OPERATOR_ROLE, OWNER_ROLE); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Rewards } from './SM1Rewards.sol'; /** * @title SM1StakedBalances * @author dYdX * * @dev Accounting of staked balances. * * NOTE: Functions may revert if epoch zero has not started. * * NOTE: All amounts dealt with in this file are denominated in staked units, which because of the * exchange rate, may not correspond one-to-one with the underlying token. See SM1Staking.sol. * * STAKED BALANCE ACCOUNTING: * * A staked balance is in one of two states: * - active: Earning staking rewards; cannot be withdrawn by staker; may be slashed. * - inactive: Not earning rewards; can be withdrawn by the staker; may be slashed. * * 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. * * 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 SM1Rewards 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 accounting. * 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 SM1StakedBalances is SM1Rewards { using SafeCast for uint256; using SafeMath for uint256; // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) SM1Rewards(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; } (SM1Types.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; } (SM1Types.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; } (SM1Types.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; } (SM1Types.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; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_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; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total inactive balance. */ function getTotalInactiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_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; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.nextEpochBalance); } /** * @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 _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); } // ============ Private Functions ============ /** * @dev Load a balance for update and then store it. */ function _settleBalance( address maybeStaker, bool isActiveBalance ) private returns (uint256) { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.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) { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.add(amount).toUint240(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint240(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying a decrease. */ function _decreaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.sub(amount).toUint240(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint240(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint240(); _storeBalance(balancePtr, balance); } /** * @dev Settle a balance while applying a decrease. */ function _decreaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint240(); _storeBalance(balancePtr, balance); } function _getBalancePtr( address maybeStaker, bool isActiveBalance ) private view returns (SM1Types.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 may modify state, and so the balance MUST be stored afterwards. * - For active balances: * - If a rollover occurs, rewards are settled up to the epoch boundary. * * @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( SM1Types.StoredBalance storage balancePtr, address maybeStaker, bool isActiveBalance ) private returns (SM1Types.StoredBalance memory) { // Active balance. if (isActiveBalance) { ( SM1Types.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; } // Inactive balance. return _loadInactiveBalance(balancePtr); } function _loadActiveBalance( SM1Types.StoredBalance storage balancePtr ) private view returns ( SM1Types.StoredBalance memory, uint256, uint256, bool ) { SM1Types.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 _loadInactiveBalance( SM1Types.StoredBalance storage balancePtr ) private view returns (SM1Types.StoredBalance memory) { SM1Types.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; } /** * @dev Store a balance. */ function _storeBalance( SM1Types.StoredBalance storage balancePtr, SM1Types.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; } } // SPDX-License-Identifier: AGPL-3.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 { SM1Types } from '../lib/SM1Types.sol'; /** * @title SM1Storage * @author dYdX * * @dev Storage contract. Contains or inherits from all contract with storage. */ abstract contract SM1Storage is AccessControlUpgradeable, ReentrancyGuard, VersionedInitializable { // ============ Epoch Schedule ============ /// @dev The parameters specifying the function from timestamp to epoch number. SM1Types.EpochParameters internal _EPOCH_PARAMETERS_; /// @dev The period of time at the end of each epoch in which withdrawals cannot be requested. uint256 internal _BLACKOUT_WINDOW_; // ============ Staked Token ERC20 ============ /// @dev Allowances for ERC-20 transfers. mapping(address => mapping(address => uint256)) internal _ALLOWANCES_; // ============ Governance Power Delegation ============ /// @dev Domain separator for EIP-712 signatures. bytes32 internal _DOMAIN_SEPARATOR_; /// @dev Mapping from (owner) => (next valid nonce) for EIP-712 signatures. mapping(address => uint256) internal _NONCES_; /// @dev Snapshots and delegates for governance voting power. mapping(address => mapping(uint256 => SM1Types.Snapshot)) internal _VOTING_SNAPSHOTS_; mapping(address => uint256) internal _VOTING_SNAPSHOT_COUNTS_; mapping(address => address) internal _VOTING_DELEGATES_; /// @dev Snapshots and delegates for governance proposition power. mapping(address => mapping(uint256 => SM1Types.Snapshot)) internal _PROPOSITION_SNAPSHOTS_; mapping(address => uint256) internal _PROPOSITION_SNAPSHOT_COUNTS_; mapping(address => address) internal _PROPOSITION_DELEGATES_; // ============ 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 => SM1Types.StoredBalance) internal _ACTIVE_BALANCES_; /// @dev The total active balance of stakers. SM1Types.StoredBalance internal _TOTAL_ACTIVE_BALANCE_; /// @dev The inactive balance by staker. mapping(address => SM1Types.StoredBalance) internal _INACTIVE_BALANCES_; /// @dev The total inactive balance of stakers. SM1Types.StoredBalance internal _TOTAL_INACTIVE_BALANCE_; // ============ Exchange Rate ============ /// @dev The value of one underlying token, in the units used for staked balances, denominated /// as a mutiple of EXCHANGE_RATE_BASE for additional precision. uint256 internal _EXCHANGE_RATE_; /// @dev Historical snapshots of the exchange rate, in each block that it has changed. mapping(uint256 => SM1Types.Snapshot) internal _EXCHANGE_RATE_SNAPSHOTS_; /// @dev Number of snapshots of the exchange rate. uint256 internal _EXCHANGE_RATE_SNAPSHOT_COUNT_; } // 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: 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: 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; /** * @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 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; } /** * @dev Downcast to a uint240, reverting on overflow. */ function toUint240( uint256 a ) internal pure returns (uint240) { uint240 b = uint240(a); require( uint256(b) == a, 'SafeCast: toUint240 overflow' ); return b; } } // SPDX-License-Identifier: AGPL-3.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 { SM1EpochSchedule } from './SM1EpochSchedule.sol'; /** * @title SM1Rewards * @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 SM1Rewards is SM1EpochSchedule { using SafeCast for uint256; using SafeERC20 for IERC20; 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, 'SM1Rewards: 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 __SM1Rewards_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 ============ /** * @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 * since the last update to the global index. * * @return The new global index. */ 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. MUST NOT be less * than the user's index. * * @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'; /** * @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: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1EpochSchedule * @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 SM1EpochSchedule is SM1Storage { using SafeCast for uint256; using SafeMath for uint256; // ============ Events ============ event EpochParametersChanged( SM1Types.EpochParameters epochParameters ); event BlackoutWindowChanged( uint256 blackoutWindow ); // ============ Initializer ============ function __SM1EpochSchedule_init( uint256 interval, uint256 offset, uint256 blackoutWindow ) internal { require( block.timestamp < offset, 'SM1EpochSchedule: Epoch zero must start after initialization' ); _setBlackoutWindow(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) { SM1Types.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) { SM1Types.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 { SM1Types.EpochParameters memory epochParameters = SM1Types.EpochParameters({interval: interval.toUint128(), offset: offset.toUint128()}); _EPOCH_PARAMETERS_ = epochParameters; emit EpochParametersChanged(epochParameters); } function _setBlackoutWindow( uint256 blackoutWindow ) internal { _BLACKOUT_WINDOW_ = blackoutWindow; emit BlackoutWindowChanged(blackoutWindow); } // ============ Private Functions ============ /** * @dev Helper function to read params from storage and apply offset to the given timestamp. * Recall that the formula for epoch number is `n = (t - b) / a`. * * NOTE: Reverts if epoch zero has not started. * * @return The values `a` and `(t - b)`. */ function _getIntervalAndOffsetTimestamp() private view returns (uint256, uint256) { SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); require( block.timestamp >= offset, 'SM1EpochSchedule: Epoch zero has not started' ); uint256 offsetTimestamp = block.timestamp.sub(offset); return (interval, offsetTimestamp); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { IERC20Detailed } from '../../../interfaces/IERC20Detailed.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1GovernancePowerDelegation } from './SM1GovernancePowerDelegation.sol'; import { SM1StakedBalances } from './SM1StakedBalances.sol'; /** * @title SM1ERC20 * @author dYdX * * @dev ERC20 interface for staked tokens. Implements governance functionality for the tokens. * * Also 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 SM1ERC20 is SM1StakedBalances, SM1GovernancePowerDelegation, IERC20Detailed { using SafeMath for uint256; // ============ Constants ============ /// @notice EIP-712 typehash for token approval via EIP-2612 permit. bytes32 public constant PERMIT_TYPEHASH = keccak256( 'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)' ); // ============ External Functions ============ function name() external pure override returns (string memory) { return 'Staked DYDX'; } function symbol() external pure override returns (string memory) { return 'stkDYDX'; } function decimals() external pure override returns (uint8) { return 18; } /** * @notice Get the total supply of staked balances. * * Note that due to the exchange rate, this is different than querying the total balance of * underyling token staked to this contract. * * @return The sum of all staked balances. */ function totalSupply() external view override returns (uint256) { return getTotalActiveBalanceCurrentEpoch() + getTotalInactiveBalanceCurrentEpoch(); } /** * @notice Get a user's staked balance. * * Note that due to the exchange rate, one unit of staked balance may not be equivalent to one * unit of the underlying token. Also note that a user's staked balance is different from a * user's transferable balance. * * @param account The account to get the balance of. * * @return The user's staked balance. */ function balanceOf( address account ) public view override(SM1GovernancePowerDelegation, IERC20) 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, 'SM1ERC20: 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, 'SM1ERC20: Decreased allowance below zero' ) ); return true; } /** * @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), 'SM1ERC20: INVALID_OWNER' ); require( block.timestamp <= deadline, 'SM1ERC20: 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), 'SM1ERC20: INVALID_SIGNATURE' ); _NONCES_[owner] = currentValidNonce.add(1); _approve(owner, spender, value); } // ============ Internal Functions ============ function _transfer( address sender, address recipient, uint256 amount ) internal { require( sender != address(0), 'SM1ERC20: Transfer from address(0)' ); require( recipient != address(0), 'SM1ERC20: Transfer to address(0)' ); require( getTransferableBalance(sender) >= amount, 'SM1ERC20: Transfer exceeds next epoch active balance' ); // Update staked balances and delegate snapshots. _transferCurrentAndNextActiveBalance(sender, recipient, amount); _moveDelegatesForTransfer(sender, recipient, amount); emit Transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 amount ) internal { require( owner != address(0), 'SM1ERC20: Approve from address(0)' ); require( spender != address(0), 'SM1ERC20: Approve to address(0)' ); _ALLOWANCES_[owner][spender] = amount; emit Approval(owner, spender, amount); } } // 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); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IGovernancePowerDelegationERC20 } from '../../../interfaces/IGovernancePowerDelegationERC20.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1ExchangeRate } from './SM1ExchangeRate.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1GovernancePowerDelegation * @author dYdX * * @dev Provides support for two types of governance powers which are separately delegatable. * Provides functions for delegation and for querying a user's power at a certain block number. * * Internally, makes use of staked balances denoted in staked units, but returns underlying token * units from the getPowerAtBlock() and getPowerCurrent() functions. * * This is based on, and is designed to match, Aave's implementation, which is used in their * governance token and staked token contracts. */ abstract contract SM1GovernancePowerDelegation is SM1ExchangeRate, 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)' ); // ============ External Functions ============ /** * @notice Delegates a specific governance power of the sender 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 of the sender 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); } /** * @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 ) external { 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), 'SM1GovernancePowerDelegation: INVALID_SIGNATURE' ); require( nonce == _NONCES_[signer]++, 'SM1GovernancePowerDelegation: INVALID_NONCE' ); require( block.timestamp <= expiry, 'SM1GovernancePowerDelegation: 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 ) external { 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), 'SM1GovernancePowerDelegation: INVALID_SIGNATURE' ); require( nonce == _NONCES_[signer]++, 'SM1GovernancePowerDelegation: INVALID_NONCE' ); require( block.timestamp <= expiry, 'SM1GovernancePowerDelegation: INVALID_EXPIRATION' ); _delegateByType(signer, delegatee, DelegationType.VOTING_POWER); _delegateByType(signer, 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) { return getPowerAtBlock(user, block.number, delegationType); } /** * @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]; } // ============ Public Functions ============ function balanceOf( address account ) public view virtual returns (uint256); /** * @notice Returns the power of a user at a certain block, denominated in underlying token units. * * @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). * * @return The user's governance power of the specified type, in underlying token units. */ function getPowerAtBlock( address user, uint256 blockNumber, DelegationType delegationType ) public override view returns (uint256) { ( mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotCounts, // unused: delegates ) = _getDelegationDataByType(delegationType); uint256 stakeAmount = _findValueAtBlock( snapshots[user], snapshotCounts[user], blockNumber, 0 ); uint256 exchangeRate = _findValueAtBlock( _EXCHANGE_RATE_SNAPSHOTS_, _EXCHANGE_RATE_SNAPSHOT_COUNT_, blockNumber, EXCHANGE_RATE_BASE ); return underlyingAmountFromStakeAmountWithExchangeRate(stakeAmount, exchangeRate); } // ============ 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), 'SM1GovernancePowerDelegation: 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 Update delegate snapshots whenever staked tokens are transfered, minted, or burned. * * @param from The sender. * @param to The recipient. * @param stakedAmount The amount being transfered, denominated in staked units. */ function _moveDelegatesForTransfer( address from, address to, uint256 stakedAmount ) internal { address votingPowerFromDelegatee = _getDelegatee(from, _VOTING_DELEGATES_); address votingPowerToDelegatee = _getDelegatee(to, _VOTING_DELEGATES_); _moveDelegatesByType( votingPowerFromDelegatee, votingPowerToDelegatee, stakedAmount, DelegationType.VOTING_POWER ); address propositionPowerFromDelegatee = _getDelegatee(from, _PROPOSITION_DELEGATES_); address propositionPowerToDelegatee = _getDelegatee(to, _PROPOSITION_DELEGATES_); _moveDelegatesByType( propositionPowerFromDelegatee, propositionPowerToDelegatee, stakedAmount, DelegationType.PROPOSITION_POWER ); } /** * @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 => SM1Types.Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotCounts, // unused: delegates ) = _getDelegationDataByType(delegationType); if (from != address(0)) { mapping(uint256 => SM1Types.Snapshot) storage fromSnapshots = snapshots[from]; uint256 fromSnapshotCount = snapshotCounts[from]; uint256 previousBalance = 0; if (fromSnapshotCount != 0) { previousBalance = fromSnapshots[fromSnapshotCount - 1].value; } uint256 newBalance = previousBalance.sub(amount); snapshotCounts[from] = _writeSnapshot( fromSnapshots, fromSnapshotCount, newBalance ); emit DelegatedPowerChanged(from, newBalance, delegationType); } if (to != address(0)) { mapping(uint256 => SM1Types.Snapshot) storage toSnapshots = snapshots[to]; uint256 toSnapshotCount = snapshotCounts[to]; uint256 previousBalance = 0; if (toSnapshotCount != 0) { previousBalance = toSnapshots[toSnapshotCount - 1].value; } uint256 newBalance = previousBalance.add(amount); snapshotCounts[to] = _writeSnapshot( toSnapshots, toSnapshotCount, newBalance ); emit DelegatedPowerChanged(to, newBalance, delegationType); } } /** * @dev Returns delegation data (snapshot, snapshotCount, delegates) by delegation type. * * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). * * @return The mapping of each user to a mapping of snapshots. * @return The mapping of each user to the total number of snapshots for that user. * @return The mapping of each user to the user's delegate. */ function _getDelegationDataByType( DelegationType delegationType ) internal view returns ( mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage, mapping(address => uint256) storage, mapping(address => address) storage ) { if (delegationType == DelegationType.VOTING_POWER) { return ( _VOTING_SNAPSHOTS_, _VOTING_SNAPSHOT_COUNTS_, _VOTING_DELEGATES_ ); } else { return ( _PROPOSITION_SNAPSHOTS_, _PROPOSITION_SNAPSHOT_COUNTS_, _PROPOSITION_DELEGATES_ ); } } /** * @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; } } // SPDX-License-Identifier: AGPL-3.0 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); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SM1Snapshots } from './SM1Snapshots.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1ExchangeRate * @author dYdX * * @dev Performs math using the exchange rate, which converts between underlying units of the token * that was staked (e.g. STAKED_TOKEN.balanceOf(account)), and staked units, used by this contract * for all staked balances (e.g. this.balanceOf(account)). * * OVERVIEW: * * The exchange rate is stored as a multiple of EXCHANGE_RATE_BASE, and represents the number of * staked balance units that each unit of underlying token is worth. Before any slashes have * occurred, the exchange rate is equal to one. The exchange rate can increase with each slash, * indicating that staked balances are becoming less and less valuable, per unit, relative to the * underlying token. * * AVOIDING OVERFLOW AND UNDERFLOW: * * Staked balances are represented internally as uint240, so the result of an operation returning * a staked balances must return a value less than 2^240. Intermediate values in calcuations are * represented as uint256, so all operations within a calculation must return values under 2^256. * * In the functions below operating on the exchange rate, we are strategic in our choice of the * order of multiplication and division operations, in order to avoid both overflow and underflow. * * We use the following assumptions and principles to implement this module: * - (ASSUMPTION) An amount denoted in underlying token units is never greater than 10^28. * - If the exchange rate is greater than 10^46, then we may perform division on the exchange * rate before performing multiplication, provided that the denominator is not greater * than 10^28 (to ensure a result with at least 18 decimals of precision). Specifically, * we use EXCHANGE_RATE_MAY_OVERFLOW as the cutoff, which is a number greater than 10^46. * - Since staked balances are stored as uint240, we cap the exchange rate to ensure that a * staked balance can never overflow (using the assumption above). */ abstract contract SM1ExchangeRate is SM1Snapshots, SM1Storage { using SafeMath for uint256; // ============ Constants ============ /// @notice The assumed upper bound on the total supply of the staked token. uint256 public constant MAX_UNDERLYING_BALANCE = 1e28; /// @notice Base unit used to represent the exchange rate, for additional precision. uint256 public constant EXCHANGE_RATE_BASE = 1e18; /// @notice Cutoff where an exchange rate may overflow after multiplying by an underlying balance. /// @dev Approximately 1.2e49 uint256 public constant EXCHANGE_RATE_MAY_OVERFLOW = (2 ** 256 - 1) / MAX_UNDERLYING_BALANCE; /// @notice Cutoff where a stake amount may overflow after multiplying by EXCHANGE_RATE_BASE. /// @dev Approximately 1.2e59 uint256 public constant STAKE_AMOUNT_MAY_OVERFLOW = (2 ** 256 - 1) / EXCHANGE_RATE_BASE; /// @notice Max exchange rate. /// @dev Approximately 1.8e62 uint256 public constant MAX_EXCHANGE_RATE = ( ((2 ** 240 - 1) / MAX_UNDERLYING_BALANCE) * EXCHANGE_RATE_BASE ); // ============ Initializer ============ function __SM1ExchangeRate_init() internal { _EXCHANGE_RATE_ = EXCHANGE_RATE_BASE; } function stakeAmountFromUnderlyingAmount( uint256 underlyingAmount ) internal view returns (uint256) { uint256 exchangeRate = _EXCHANGE_RATE_; if (exchangeRate > EXCHANGE_RATE_MAY_OVERFLOW) { uint256 exchangeRateUnbased = exchangeRate.div(EXCHANGE_RATE_BASE); return underlyingAmount.mul(exchangeRateUnbased); } else { return underlyingAmount.mul(exchangeRate).div(EXCHANGE_RATE_BASE); } } function underlyingAmountFromStakeAmount( uint256 stakeAmount ) internal view returns (uint256) { return underlyingAmountFromStakeAmountWithExchangeRate(stakeAmount, _EXCHANGE_RATE_); } function underlyingAmountFromStakeAmountWithExchangeRate( uint256 stakeAmount, uint256 exchangeRate ) internal pure returns (uint256) { if (stakeAmount > STAKE_AMOUNT_MAY_OVERFLOW) { // Note that this case implies that exchangeRate > EXCHANGE_RATE_MAY_OVERFLOW. uint256 exchangeRateUnbased = exchangeRate.div(EXCHANGE_RATE_BASE); return stakeAmount.div(exchangeRateUnbased); } else { return stakeAmount.mul(EXCHANGE_RATE_BASE).div(exchangeRate); } } function updateExchangeRate( uint256 numerator, uint256 denominator ) internal returns (uint256) { uint256 oldExchangeRate = _EXCHANGE_RATE_; // Avoid overflow. // Note that the numerator and denominator are both denominated in underlying token units. uint256 newExchangeRate; if (oldExchangeRate > EXCHANGE_RATE_MAY_OVERFLOW) { newExchangeRate = oldExchangeRate.div(denominator).mul(numerator); } else { newExchangeRate = oldExchangeRate.mul(numerator).div(denominator); } require( newExchangeRate <= MAX_EXCHANGE_RATE, 'SM1ExchangeRate: Max exchange rate exceeded' ); _EXCHANGE_RATE_SNAPSHOT_COUNT_ = _writeSnapshot( _EXCHANGE_RATE_SNAPSHOTS_, _EXCHANGE_RATE_SNAPSHOT_COUNT_, newExchangeRate ); _EXCHANGE_RATE_ = newExchangeRate; return newExchangeRate; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1Snapshots * @author dYdX * * @dev Handles storage and retrieval of historical values by block number. * * Note that the snapshot stored at a given block number represents the value as of the end of * that block. */ abstract contract SM1Snapshots { /** * @dev Writes a snapshot of a value at the current block. * * @param snapshots Storage mapping from snapshot index to snapshot struct. * @param snapshotCount The total number of snapshots in the provided mapping. * @param newValue The new value to snapshot at the current block. * * @return The new snapshot count. */ function _writeSnapshot( mapping(uint256 => SM1Types.Snapshot) storage snapshots, uint256 snapshotCount, uint256 newValue ) internal returns (uint256) { uint256 currentBlock = block.number; if ( snapshotCount != 0 && snapshots[snapshotCount - 1].blockNumber == currentBlock ) { // If there was a previous snapshot for this block, overwrite it. snapshots[snapshotCount - 1].value = newValue; return snapshotCount; } else { snapshots[snapshotCount] = SM1Types.Snapshot(currentBlock, newValue); return snapshotCount + 1; } } /** * @dev Search for the snapshot value at a given block. Uses binary search. * * Reverts if `blockNumber` is greater than the current block number. * * @param snapshots Storage mapping from snapshot index to snapshot struct. * @param snapshotCount The total number of snapshots in the provided mapping. * @param blockNumber The block number to search for. * @param initialValue The value to return if `blockNumber` is before the earliest snapshot. * * @return The snapshot value at the specified block number. */ function _findValueAtBlock( mapping(uint256 => SM1Types.Snapshot) storage snapshots, uint256 snapshotCount, uint256 blockNumber, uint256 initialValue ) internal view returns (uint256) { require( blockNumber <= block.number, 'SM1Snapshots: INVALID_BLOCK_NUMBER' ); if (snapshotCount == 0) { return initialValue; } // Check earliest snapshot. if (blockNumber < snapshots[0].blockNumber) { return initialValue; } // Check latest snapshot. if (blockNumber >= snapshots[snapshotCount - 1].blockNumber) { return snapshots[snapshotCount - 1].value; } uint256 lower = 0; uint256 upper = snapshotCount - 1; while (upper > lower) { uint256 center = upper - (upper - lower) / 2; // Ceil, avoiding overflow. SM1Types.Snapshot memory snapshot = snapshots[center]; if (snapshot.blockNumber == blockNumber) { return snapshot.value; } else if (snapshot.blockNumber < blockNumber) { lower = center; } else { upper = center - 1; } } return snapshots[lower].value; } }
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. user The user's address. userStaked Tokens staked by the user during the period since the last user index update. newGlobalIndex The new index value to bring the user index up to. MUST NOT be less than the user's index. return The user's accrued rewards, including past unclaimed rewards./ Note: Even if the user's staked balance is zero, we still need to update the user index. Calculate newly accrued rewards since the last update to the user's index. Update the user's 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) { newAccruedRewards = oldAccruedRewards; uint256 indexDelta = newGlobalIndex.sub(oldUserIndex); uint256 accruedRewardsDelta = userStaked.mul(indexDelta).div(INDEX_BASE); newAccruedRewards = oldAccruedRewards.add(accruedRewardsDelta); _USER_REWARDS_BALANCES_[user] = newAccruedRewards; } emit UserIndexUpdated(user, newGlobalIndex, newAccruedRewards); return newAccruedRewards; }
203,999
pragma solidity ^0.5.7; /** * @title DecentralizedHealth * @dev see https://github.com/marxMT/decentralizedHealth */ contract DecentralizedHealth{ // hospital que crea el contrato address owner; mapping (address => bool) patientPermition; //Mapping de paciente address a IPFS hash mapping (address => string) hashPatient; //Mapping de doctor address a su permiso mapping (address => bool) doctorPermition; modifier isOwner () { require(msg.sender == owner); _; } constructor() public { owner = msg.sender; } /** *@dev sudo agrega a mapping paciente con su hash determinado *@param _addresPatient direccion del paciente *@param hashIPFS apunta a data en IPFS */ function addPatient(address _addresPatient, string memory hashIPFS) public isOwner(){ require(!patientPermition[_addresPatient], "Pasciente Existente"); hashPatient[_addresPatient]=hashIPFS; } /** *@dev se agrega doctor y se otorga permiso para modificar HR *@param _addressDoctor */ function addDoctor(address _addressDoctor) public isOwner(){ require(!(doctorPermition[_addressDoctor])); doctorPermition[_addressDoctor] = true; } /** *@dev sudo agrega a mapping paciente con su hash determinado *@param _addresPatient direccion del paciente *@param hashIPFS apunta a data en IPFS */ function addToHR(address _addresPatient, string memory _hashIPFS ) public { // el doctor agrega un documento a la historia clinica require(doctorPermition[msg.sender]); hashPatient[_addresPatient] = _hashIPFS; // Como crear el hash ipfs? } /** *@dev Returns IPFS hash */ function viewHR() public view returns(string memory result){ require(patientPermition[msg.sender] || doctorPermition[msg.sender], "El paciente ingresado no existe"); result= hashPatient[msg.sender]; } }
Returns IPFS hash/
function viewHR() public view returns(string memory result){ require(patientPermition[msg.sender] || doctorPermition[msg.sender], "El paciente ingresado no existe"); result= hashPatient[msg.sender]; }
15,825,397
pragma solidity ^0.8.7; contract MappingStructExample { // struct to keep payment info struct Payment { uint amount; uint timestamps; } // struct to keep balance info struct Balance { uint totalBalance; uint numPayments; mapping(uint => Payment) payments; } // like an array but with all possible keys already init with their default value // is like an array which keeps the balance of every address // deprecated // mapping(address => uint) public balanceReceived; // new version with a mapping of address => Balance mapping(address => Balance) public balanceReceived; // function to return the balance of this address function getBalance() public view returns(uint) { return address(this).balance; } function sendMoney() public payable { // update totalBalance of sender's balanceReceived balanceReceived[msg.sender].totalBalance += msg.value; // create a new payment with the value that was sent and with the current timestamp Payment memory payment = Payment(msg.value, block.timestamp); // add the payment to the balanceReceived value (to Balance.payments) balanceReceived[msg.sender].payments[balanceReceived[msg.sender].numPayments] = payment; // increase the number of payments balanceReceived[msg.sender].numPayments++; } // partial withdraw, put money into the smart contract i.e five ether // and then start slowly withdrawing to other different addresses function withdrawMoney(address payable _to, uint _amount) public { // first check if the person has enough money to send require(balanceReceived[msg.sender].totalBalance >= _amount, "Not enough funds"); // deduct from sender's balance balanceReceived[msg.sender].totalBalance -= _amount; // send them to the recipient _to.transfer(_amount); } // withdraw all the money from this address and send them to _to address function withdrawAllMoney(address payable _to) public { // the code below follows the checks effects interactions pattern // this is the amount that this person has in his balance uint balanceToSend = balanceReceived[msg.sender].totalBalance; // set this person's balance to zero balanceReceived[msg.sender].totalBalance = 0; // transfer it to the account that was specified by the person who owns this balance _to.transfer(balanceToSend); } }
update totalBalance of sender's balanceReceived create a new payment with the value that was sent and with the current timestamp add the payment to the balanceReceived value (to Balance.payments) increase the number of payments
function sendMoney() public payable { balanceReceived[msg.sender].totalBalance += msg.value; Payment memory payment = Payment(msg.value, block.timestamp); balanceReceived[msg.sender].payments[balanceReceived[msg.sender].numPayments] = payment; balanceReceived[msg.sender].numPayments++; }
14,019,865
./full_match/5/0x079BC05ebF765c3678Bec03A598561f0414f6227/sources/project:/contracts/PropertyNFT.sol
Approves another address to manage the specified token. Overrides ERC721's approve function. to - The address to be approved. tokenId - The ID of the token to be approved for management./
function approve(address to, uint256 tokenId) public virtual override(ERC721, IERC721) { super.approve(to, tokenId); }
1,864,641
./full_match/80001/0xc2db37573a582bA35861DD890Ba8A0ec8CB77843/sources/contracts/StakingContract_flattened.sol
Internal Function to unstake tokens _poolId pool id to unstake from account address of the user _amount amount of tokens to unstake/ Check if the pool is active require(pool.isActive, "This pool is not active"); adding this check will prevent users from unstaking after the pool is set inactive Check if the user has enough staked tokens Check if the staking period is valid Calculate unstaking fee Calculate penalty for early unstaking update vault
function _unstakeToken( uint256 _poolId, address account, uint256 _amount ) internal { StakingPool memory pool = stakingPools[_poolId]; require( stakedBalances[account][_poolId] >= _amount, "Insufficient staked balance" ); require( block.timestamp >= pool.startDate, "Unstaking is not allowed before the staking period starts" ); uint256 unstakingFee = (_amount * unstakingFeePercentageNumerator) / unstakingFeePercentageDenominator; uint256 penalty = 0; if (block.timestamp < pool.endDate) { penalty = (_amount * pool.penaltyPercentageNumerator) / pool.penaltyPercentageDenominator; } stakingPools[_poolId].totalStaked -= _amount; vaults[account][_poolId] = Stake({ poolId: _poolId, tokenId: stakedBalances[account][_poolId], owner: account }); emit Unstaked(account, _poolId, _amount, penalty); }
5,607,109
pragma solidity ^0.4.11; contract Token is StandardToken, Ownable, HasNoEther, Contactable, Addressed { string public constant name = "Concurrence"; string public constant symbol = "CCCE"; uint8 public constant decimals = 9; uint256 public constant INITIAL_SUPPLY = 10**18; function Token(address _mainAddress) Addressed(_mainAddress) { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } //event debug(address sender, uint256 balance, bytes32 request, uint256 amount); event Reserve(address sender, bytes32 request, uint256 value, uint256 total); mapping (bytes32 => uint256) public reserved; //reservations are one directional; once they go in, the only way //to get them out is through mining and consensus function reserve(bytes32 _request, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); reserved[_request] = reserved[_request].add(_value); Reserve(msg.sender,_request,_value,reserved[_request]); return true; } function reward(bytes32 _request, address _miner, uint256 _value) public returns (bool) { Main mainContract = Main(mainAddress); Requests requestsContract = Requests(mainContract.getContract('Requests')); //the only account that can move the reserved token around //is the combiner defined in the request require(msg.sender == requestsContract.getCombiner(_request)); require(_value <= reserved[_request]); reserved[_request] = reserved[_request].sub(_value); balances[_miner] = balances[_miner].add(_value); return true; } event Stake(address indexed sender, bytes32 indexed request, bytes32 indexed response, uint256 value, uint256 total); //event Unstake(address indexed sender, bytes32 indexed response, uint256 value, uint256 total); mapping (address => mapping (bytes32 => mapping (bytes32 => uint256))) public staked; function stake(bytes32 _request,bytes32 _response, uint256 _value) public returns (bool) { //TODO for now set it up so only the response sender can stake token behind it // this is because if another account stakes on a response they wont ever // get their token back require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); staked[msg.sender][_request][_response] = staked[msg.sender][_request][_response].add(_value); Stake(msg.sender,_request,_response,_value,staked[msg.sender][_request][_response]); return true; } function release(bytes32 _request, bytes32 _response, address _miner, uint256 _value) public returns (bool) { Main mainContract = Main(mainAddress); Requests requestsContract = Requests(mainContract.getContract('Requests')); //the only account that can move the staked token around //is the combiner defined in the request require(msg.sender == requestsContract.getCombiner(_request)); require(_value <= staked[_miner][_request][_response]); staked[_miner][_request][_response] = staked[_miner][_request][_response].sub(_value); balances[_miner] = balances[_miner].add(_value); return true; } function punish(bytes32 _request, bytes32 _response, address _miner, uint256 _value, address _to) public returns (bool) { Main mainContract = Main(mainAddress); Requests requestsContract = Requests(mainContract.getContract('Requests')); //the only account that can move the staked token around //is the combiner defined in the request require(msg.sender == requestsContract.getCombiner(_request)); require(_value <= staked[_miner][_request][_response]); staked[_miner][_request][_response] = staked[_miner][_request][_response].sub(_value); balances[_to] = balances[_to].add(_value); return true; } } contract Requests {function getCombiner(bytes32 _id) public constant returns (address) {}} import 'zeppelin-solidity/contracts/ownership/Ownable.sol'; import 'zeppelin-solidity/contracts/ownership/HasNoEther.sol'; import 'zeppelin-solidity/contracts/ownership/Contactable.sol'; import 'zeppelin-solidity/contracts/token/StandardToken.sol'; import 'Addressed.sol';
the only account that can move the staked token aroundis the combiner defined in the request
function punish(bytes32 _request, bytes32 _response, address _miner, uint256 _value, address _to) public returns (bool) { Main mainContract = Main(mainAddress); Requests requestsContract = Requests(mainContract.getContract('Requests')); require(msg.sender == requestsContract.getCombiner(_request)); require(_value <= staked[_miner][_request][_response]); staked[_miner][_request][_response] = staked[_miner][_request][_response].sub(_value); balances[_to] = balances[_to].add(_value); return true; }
15,835,028
./partial_match/1/0xcACAbb068D1bC1CC75Fdefa9940991B389bA1fda/sources/XDSeaTrade.sol
ids[0] - tokenId, ids[1] - amount, ids[2] - nooftoken, ids[3] - nftType
function saleWithToken( string memory bidtoken, address payable from, uint256[] memory ids, address _conAddr ) public { require( ids[1] == order_place[from][ids[0]].price.mul(ids[2]) && order_place[from][ids[0]].price.mul(ids[2]) > 0, "Order is Mismatch" ); _saleToken(from, ids, bidtoken, _conAddr); if (ids[3] == 721) { IERC721Upgradeable(_conAddr).safeTransferFrom( from, msg.sender, ids[0] ); if (order_place[from][ids[0]].price > 0) { delete order_place[from][ids[0]]; } if ( IERC1155Upgradeable(_conAddr).balanceOf(from, ids[0]).sub( ids[2] ) == 0 ) { if (order_place[from][ids[0]].price > 0) { delete order_place[from][ids[0]]; } } IERC1155Upgradeable(_conAddr).safeTransferFrom( from, msg.sender, ids[0], ids[2], "" ); } }
4,020,845
// 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/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.0; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they not should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, with should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(_msgSender(), spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(value, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } // 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: @openzeppelin/contracts/access/roles/WhitelistAdminRole.sol pragma solidity ^0.5.0; /** * @title WhitelistAdminRole * @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts. */ contract WhitelistAdminRole is Context { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; constructor () internal { _addWhitelistAdmin(_msgSender()); } modifier onlyWhitelistAdmin() { require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role"); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { _addWhitelistAdmin(account); } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(_msgSender()); } function _addWhitelistAdmin(address account) internal { _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } } // File: contracts/roles/AdminRole.sol pragma solidity ^0.5.6; contract AdminRole is WhitelistAdminRole { address[] private _adminList; function _addWhitelistAdmin(address account) internal { super._addWhitelistAdmin(account); _adminList.push(account); } function _removeWhitelistAdmin(address account) internal { require(_adminList.length > 1, "At lease 1 Admin"); super._removeWhitelistAdmin(account); uint256 s = getIndexOfAdmin(account); _adminList[s] = _adminList[_adminList.length - 1]; _adminList.pop(); } function getIndexOfAdmin(address account) public view returns(uint256) { uint256 s = 0; for (s; s < _adminList.length; s += 1) { if (account == _adminList[s]) return s; } return 0; } function getAdminList() public view onlyWhitelistAdmin returns(address[] memory) { return _adminList; } } // File: contracts/token/PausableToken.sol pragma solidity ^0.5.6; /** * @title Pausable token * @dev ERC20 with pausable transfers and allowances. * * Useful if you want to stop trades until the end of a crowdsale, or have * an emergency switch for freezing all token transfers in the event of a large * bug. */ contract PausableToken is ERC20, AdminRole { /** * @dev Emitted when the pause is triggered by a whitelistAdmin (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a whitelistAdmin (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the whitelistAdmin role * to the deployer. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a whitelistAdmin to pause, triggers stopped state. */ function pause() public onlyWhitelistAdmin whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a whitelistAdmin to unpause, returns to normal state. */ function unpause() public onlyWhitelistAdmin whenPaused { _paused = false; emit Unpaused(_msgSender()); } /** * @dev set modifier is paused to transfer function * @param to address * @param value uint256 */ function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } /** * @dev set modifier is paused to transferFrom function * @param from address * @param to address * @param value uint256 */ function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } /** * @dev set modifier is paused to approve function * @param spender address * @param value uint256 */ function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } /** * @dev set modifier is paused to increaseAllowance function * @param spender address * @param addedValue uint256 */ function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } /** * @dev set modifier is paused to decreaseAllowance function * @param spender address * @param subtractedValue uint256 */ function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } // File: contracts/erc/ERC1132.sol pragma solidity ^0.5.6; /** * @title ERC1132 interface * @dev see https://github.com/ethereum/EIPs/issues/1132 */ contract ERC1132 { /** * @dev Reasons why a user's tokens have been locked */ mapping(address => bytes32[]) public lockReason; /** * @dev locked token structure */ struct LockToken { uint256 amount; uint256 validity; bool claimed; } /** * @dev Holds number & validity of tokens locked for a given reason for * a specified address */ mapping(address => mapping(bytes32 => LockToken)) public locked; /** * @dev Records data of all the tokens Locked */ event Locked( address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity ); /** * @dev Records data of all the tokens unlocked */ event Unlocked( address indexed _of, bytes32 indexed _reason, uint256 _amount ); // /** // * @dev Locks a specified amount of tokens against an address, // * for a specified reason and time // * @param _reason The reason to lock tokens // * @param _amount Number of tokens to be locked // * @param _time Lock time in seconds // */ // function lock(bytes32 _reason, uint256 _amount, uint256 _time) // internal returns (bool); /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount); /** * @dev Returns tokens validity for a specified address for a specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensValidity(address _of, bytes32 _reason) public view returns (uint256 validity); /** * @dev Returns total tokens held by an address (locked + transferable) * @param _of The address to query the total balance of */ function lockBalanceOf(address _of) public view returns (uint256 amount); /** * @dev Extends lock for a specified reason and time * @param _to adress to which tokens are to be extended lock * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLock(address _to, bytes32 _reason, uint256 _time) public returns (bool); /** * @dev Increase number of tokens locked for a specified reason * @param _to adress to which tokens are to be increased * @param _reason The reason to lock tokens * @param _amount Number of tokens to be increased */ function increaseLockAmount(address _to, bytes32 _reason, uint256 _amount) public returns (bool); /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Unlocks the unlockable tokens of a specified address * @param _of Address of user, claiming back unlockable tokens */ function unlock(address _of) public returns (uint256 unlockableTokens); /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens); } // File: contracts/token/LockableToken.sol pragma solidity ^0.5.6; contract LockableToken is PausableToken, ERC1132 { /** * @dev Error messages for require statements */ string internal constant ALREADY_LOCKED = "Tokens already locked"; string internal constant NOT_LOCKED = "No tokens locked"; string internal constant AMOUNT_ZERO = "Amount can not be 0"; /** * @dev is msg.sender or shitelistadmin * @param _address address */ modifier isAdminOrSelf(address _address) { require(_address == msg.sender || isWhitelistAdmin(msg.sender), "tokens are unlockable by owner or admin"); _; } /** * @dev Returns tokens locked for a specified address for a specified reason * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount) { if (!locked[_of][_reason].claimed) amount = locked[_of][_reason].amount; } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount) { if (locked[_of][_reason].validity > _time) amount = locked[_of][_reason].amount; } /** * @dev Returns tokens validity for a specified address for a specified reason * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensValidity(address _of, bytes32 _reason) public view returns (uint256 validity) { validity = locked[_of][_reason].validity; } /** * @dev Returns total tokens held by an address (locked + transferable) * @param _of The address to query the total balance of */ function lockBalanceOf(address _of) public view returns (uint256 amount) { amount = 0; uint256 i = 0; for ( i ; i < lockReason[_of].length; i++) { amount = amount.add(tokensLocked(_of, lockReason[_of][i])); } } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount) { if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) //solium-disable-line amount = locked[_of][_reason].amount; } /** * @dev Unlocks the unlockable tokens of a specified address * @param _of Address of user, claiming back unlockable tokens */ function unlock(address _of) public isAdminOrSelf(_of) returns (uint256 unlockableTokens) { uint256 lockedTokens; uint256 i = 0; for ( i ; i < lockReason[_of].length; i++) { lockedTokens = tokensUnlockable(_of, lockReason[_of][i]); if (lockedTokens > 0) { unlockableTokens = unlockableTokens.add(lockedTokens); locked[_of][lockReason[_of][i]].claimed = true; emit Unlocked(_of, lockReason[_of][i], lockedTokens); } } if (unlockableTokens > 0) { _transfer(address(this), _of, unlockableTokens); } } /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens) { uint256 i = 0; for ( i ; i < lockReason[_of].length; i++) { unlockableTokens = unlockableTokens.add(tokensUnlockable(_of, lockReason[_of][i])); } } /** * @dev Transfers and Locks a specified amount of tokens, * for a specified reason and time * @param _to adress to which tokens are to be transfered * @param _reason The reason to lock tokens * @param _amount Number of tokens to be transfered and locked * @param _time Lock time in seconds */ function transferWithLock(address _to, bytes32 _reason, uint256 _amount, uint256 _time) public onlyWhitelistAdmin returns (bool) { require(_to != address(0), "Zero address not allowed"); require(_amount != 0, AMOUNT_ZERO); require(tokensLocked(_to, _reason) == 0, ALREADY_LOCKED); require(balanceOf(msg.sender) > _amount); uint256 validUntil = now.add(_time); //solium-disable-line // not allowed duplicate reason for address if (locked[_to][_reason].amount == 0) lockReason[_to].push(_reason); _transfer(msg.sender, address(this), _amount); locked[_to][_reason] = LockToken(_amount, validUntil, false); emit Locked(_to, _reason, _amount, validUntil); return true; } /** * @dev Extends lock for a specified reason and time * @param _to adress to which tokens are to be extended lock * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLock(address _to, bytes32 _reason, uint256 _time) public onlyWhitelistAdmin returns (bool) { require(_to != address(0), "Zero address not allowed"); require(tokensLocked(_to, _reason) > 0, NOT_LOCKED); locked[_to][_reason].validity = locked[_to][_reason].validity.add(_time); emit Locked(_to, _reason, locked[_to][_reason].amount, locked[_to][_reason].validity); return true; } /** * @dev Increase number of tokens locked for a specified reason * @param _to adress to which tokens are to be increased * @param _reason The reason to lock tokens * @param _amount Number of tokens to be increased */ function increaseLockAmount(address _to, bytes32 _reason, uint256 _amount) public onlyWhitelistAdmin returns (bool) { require(_to != address(0), "Zero address not allowed"); require(tokensLocked(_to, _reason) > 0, NOT_LOCKED); _transfer(msg.sender, address(this), _amount); locked[_to][_reason].amount = locked[_to][_reason].amount.add(_amount); emit Locked(_to, _reason, locked[_to][_reason].amount, locked[_to][_reason].validity); return true; } /** * @dev get length of lockReason array * @param _of address */ function getSizeOfLockReason(address _of) public view returns (uint256) { return lockReason[_of].length; } } // File: contracts/token/StakingToken.sol pragma solidity ^0.5.6; /** * @title Staking Token (STK) * @author Alberto Cuesta Canada * @dev Implements a basic ERC20 staking token with incentive distribution. */ contract StakingToken is LockableToken { /** * @dev Emitted when user staked token. */ event Staked(address account, uint256 amount); /** * @dev Emitted when user unstaked token. */ event Unstaked(address account, uint256 amount); /** * @dev Emitted when user unstaked token. */ event validStakePeriod(uint256 _startTime, uint256 _duration, bool stakeFlag); /** * @dev We usually require to know who are all the stakeholders. */ address[] internal stakeholders; /** * @dev The stakes for each stakeholder. */ mapping(address => uint256) internal stakes; uint256 private secondsInterval; uint256 private validStakeDuration; uint256 private validStakeStartTime; bool private stakeFlag; /** * @dev Initializes the contract in stake state. * to the deployer. */ constructor () internal { secondsInterval = 60*60*24*7; // default : interval 7 days validStakeDuration = 32400; // default : 60*60*9 ( 9hours ) validStakeStartTime = now - validStakeDuration; //solium-disable-line stakeFlag = false; } // ---------- SET TIME ---------- modifier isvalidStakePeriod() { require(stakeFlag, "stake is disabled"); require(isAbleToStake(), "It's not valid time to stake"); //solium-disable-line _; } /** * @dev Set period of able to stake. (It is automatically set to the same day each week.) * @param _startTime uint256 available start time to set stake/unstake * @param _duration uint256 duration second to set stake/unstake */ function setvalidStakePeriod(uint256 _startTime, uint256 _duration) public onlyWhitelistAdmin returns (uint256, uint256){ validStakeStartTime = _startTime; validStakeDuration = _duration; stakeFlag = true; emit validStakePeriod(_startTime, _duration, stakeFlag); return stakePeriod(); } /** * @dev change the stakeFlag state. * @param _stakeFlag bool stakeFlag state */ function setStakeFlag(bool _stakeFlag) public onlyWhitelistAdmin returns (bool) { stakeFlag = _stakeFlag; return stakeFlag; } /** * @dev A method for check is able to stake */ function isAbleToStake() public view returns (bool){ if(!stakeFlag || now < validStakeStartTime) { //solium-disable-line return false; } uint256 validTime = now.sub(validStakeStartTime).mod(secondsInterval); //solium-disable-line return (validTime >= 0 && validTime < validStakeDuration); } /** * @dev A method for check period for stake */ function stakePeriod() public view returns (uint256 validStakePeriodStart, uint256 validStakePeriodEnd){ if(now < validStakeStartTime) { //solium-disable-line validStakePeriodStart = validStakeStartTime; validStakePeriodEnd = validStakePeriodStart.add(validStakeDuration); }else{ uint256 week = now.sub(validStakeStartTime).div(secondsInterval); //solium-disable-line if(isAbleToStake()){ validStakePeriodStart = validStakeStartTime.add(secondsInterval.mul(week)); }else{ validStakePeriodStart = validStakeStartTime.add(secondsInterval.mul(week.add(1))); } validStakePeriodEnd = validStakePeriodStart.add(validStakeDuration); } } // ---------- STAKES ---------- /** * @dev A method for a stakeholder to create a stake. * @param _stake The size of the stake to be created. */ function createStake(uint256 _stake) external isvalidStakePeriod { require(transfer(address(this), _stake), "Token transfer failed"); if(stakes[msg.sender] == 0) _addStakeholder(msg.sender); stakes[msg.sender] = stakes[msg.sender].add(_stake); emit Staked(msg.sender,_stake); } /** * @dev A method for a stakeholder to remove a stake. * @param _stake The size of the stake to be removed. */ function removeStake(uint256 _stake) external isvalidStakePeriod { require(_stake <= stakes[msg.sender], "insufficient stake balance"); stakes[msg.sender] = stakes[msg.sender].sub(_stake); if(stakes[msg.sender] == 0) _removeStakeholder(msg.sender); _transfer(address(this), msg.sender, _stake); emit Unstaked(msg.sender,_stake); } /** * @dev A method to retrieve the stake for a stakeholder. * @param _stakeholder The stakeholder to retrieve the stake for. * @return uint256 The amount of wei staked. */ function stakeOf(address _stakeholder) public view returns(uint256) { return stakes[_stakeholder]; } /** * @dev A method to the aggregated stakes from all stakeholders. * @return uint256 The aggregated stakes from all stakeholders. */ function totalStakes() public view returns(uint256) { uint256 _totalStakes = 0; uint256 s = 0; for ( s ; s < stakeholders.length; s += 1){ _totalStakes = _totalStakes.add(stakes[stakeholders[s]]); } return _totalStakes; } // ---------- STAKEHOLDERS ---------- /** * @dev A method to check if an address is a stakeholder. * @param _address The address to verify. * @return bool, uint256 Whether the address is a stakeholder, * and if so its position in the stakeholders array. */ function isStakeholder(address _address) public view returns(bool, uint256) { uint256 s = 0; for ( s ; s < stakeholders.length; s += 1){ if (_address == stakeholders[s]) return (true, s); } return (false, 0); } /** * @dev A method to add a stakeholder. * @param _stakeholder The stakeholder to add. */ function _addStakeholder(address _stakeholder) internal { (bool _isStakeholder, ) = isStakeholder(_stakeholder); if(!_isStakeholder) stakeholders.push(_stakeholder); } /** * @dev A method to remove a stakeholder. * @param _stakeholder The stakeholder to remove. */ function _removeStakeholder(address _stakeholder) internal { (bool _isStakeholder, uint256 s) = isStakeholder(_stakeholder); if(_isStakeholder){ stakeholders[s] = stakeholders[stakeholders.length - 1]; stakeholders.pop(); } } /** * @dev A method to get stake holders */ function stakeholderList() external view returns (address[] memory) { return stakeholders; } } // File: contracts/HiblocksToken.sol pragma solidity ^0.5.6; contract HiblocksToken is ERC20Detailed, StakingToken { mapping(address => mapping(uint => bytes)) public memos; /** * @dev constructor to mint initial tokens * @param name string * @param symbol string * @param decimals uint8 * @param initialSupply uint256 */ constructor(string memory name, string memory symbol, uint8 decimals, uint256 initialSupply) public ERC20Detailed(name, symbol, decimals) { // Mint the initial supply require(initialSupply > 0, "initialSupply must be greater than zero."); _mint(_msgSender(), initialSupply * (10 ** uint256(decimals))); } /** * @dev Transfer token for a specified address with memo * @param to The address to transfer to. * @param value The amount to be transferred. * @param memo The memo to be saved. */ function transferWithMemo(address to, uint256 value, bytes memory memo) public returns (bool) { require(transfer(to, value), "Token transfer failed"); memos[to][block.number] = memo; return true; } /** * @dev Gets the memo of the specified address and block number. * @param addr The address to query the memo of. * @param blockNumber The block number to query the memo of. * @return An bytes representing the memo writed by the passed address. */ function memoOf(address addr, uint blockNumber) external view returns (bytes memory) { return(memos[addr][blockNumber]); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public onlyWhitelistAdmin { super._burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from the address. * * See {ERC20-_burnFrom}. */ function burnFrom(address addr, uint256 amount) public onlyWhitelistAdmin { super._burnFrom(addr, amount); } /** * @dev Returns total tokens held by an address (transferable + locked) * @param _addr The address to query the total balance of */ function totalBalanceOf(address _addr) external view returns (uint256 amount, uint256 token, uint256 locked, uint256 staked) { token = balanceOf(_addr); locked = lockBalanceOf(_addr); staked = stakeOf(_addr); amount = token.add(locked).add(staked); } }
A method for a stakeholder to remove a stake. _stake The size of the stake to be removed./
function removeStake(uint256 _stake) external isvalidStakePeriod { require(_stake <= stakes[msg.sender], "insufficient stake balance"); stakes[msg.sender] = stakes[msg.sender].sub(_stake); if(stakes[msg.sender] == 0) _removeStakeholder(msg.sender); _transfer(address(this), msg.sender, _stake); emit Unstaked(msg.sender,_stake); }
5,500,716
pragma solidity 0.4.18; import './zeppelin/token/BurnableToken.sol'; contract SofinToken is BurnableToken { string public constant name = 'SOFIN'; string public constant symbol = 'SOFIN'; uint256 public constant decimals = 18; uint256 public constant tokenCreationCap = 45000000 * 10 ** decimals; address public multiSigWallet; address public owner; bool public active = true; uint256 public oneTokenInWei = 65000000000000000; modifier onlyOwner { if (owner != msg.sender) { revert(); } _; } modifier onlyActive { if (!active) { revert(); } _; } /** * @dev add an address to the list of frozen accounts * @param account address to freeze * @return true if the address was added to the list of frozen accounts, false if the address was already in the list */ function freezeAccount(address account) public onlyOwner returns (bool success) { if (!frozenAccounts[account]) { frozenAccounts[account] = true; Frozen(account); success = true; } } /** * @dev remove an address from the list of frozen accounts * @param account address to unfreeze * @return true if the address was removed from the list of frozen accounts, * false if the address wasn't in the list in the first place */ function unfreezeAccount(address account) public onlyOwner returns (bool success) { if (frozenAccounts[account]) { frozenAccounts[account] = false; Unfrozen(account); success = true; } } event Mint(address indexed to, uint256 amount); event MintFinished(); /** * 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 SofinToken(address _multiSigWallet) public { multiSigWallet = _multiSigWallet; owner = msg.sender; } function() payable public { createTokens(); } /** * @param _to Target address. * @param _amount Amount of SOFIN tokens, _NOT_ multiplied to decimals. */ function mintTokens(address _to, uint256 _amount) external onlyOwner { uint256 decimalsMultipliedAmount = _amount.mul(10 ** decimals); uint256 checkedSupply = totalSupply.add(decimalsMultipliedAmount); if (tokenCreationCap < checkedSupply) { revert(); } balances[_to] += decimalsMultipliedAmount; totalSupply = checkedSupply; Mint(_to, decimalsMultipliedAmount); Transfer(address(0), _to, decimalsMultipliedAmount); } function withdraw() external onlyOwner { multiSigWallet.transfer(this.balance); } function finalize() external onlyOwner { active = false; MintFinished(); } /** * Sets price in wei per 1 SOFIN token. */ function setTokenPriceInWei(uint256 _oneTokenInWei) external onlyOwner { oneTokenInWei = _oneTokenInWei; } function createTokens() internal onlyActive { if (msg.value <= 0) { revert(); } uint256 multiplier = 10 ** decimals; uint256 tokens = msg.value.mul(multiplier) / oneTokenInWei; uint256 checkedSupply = totalSupply.add(tokens); if (tokenCreationCap < checkedSupply) { revert(); } balances[msg.sender] += tokens; totalSupply = checkedSupply; Mint(msg.sender, tokens); Transfer(address(0), msg.sender, tokens); TokenPurchase( msg.sender, msg.sender, msg.value, tokens ); } }
add an address to the list of frozen accounts account address to freeze return true if the address was added to the list of frozen accounts, false if the address was already in the list/
function freezeAccount(address account) public onlyOwner returns (bool success) { if (!frozenAccounts[account]) { frozenAccounts[account] = true; Frozen(account); success = true; } }
1,784,668
./full_match/1/0xe63C777dCaab7Db2F6667fCA5f323D47fEE565B2/sources/MyContract.sol
Hook that is called before any token transfer. This includes minting and burning. Calling conditions: - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be transferred to `to`. - When `from` is zero, `tokenId` will be minted for `to`. - When `to` is zero, ``from``'s `tokenId` will be burned. - `from` cannot be the zero address. - `to` cannot be the zero address. To learn more about hooks, head to xref:ROOT:extending-contracts.adocusing-hooks[Using Hooks]./
function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } }
8,463,252
./partial_match/97/0x815fA0A6f75F8EdA9e73D110d719082101757757/sources/IKOMP.sol
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "IKOMP::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
11,390,390
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../interfaces/IControllable.sol"; abstract contract Controllable is IControllable { mapping(address => bool) _controllers; /** * @dev Throws if called by any account not in authorized list */ modifier onlyController() { require( _controllers[msg.sender] == true || address(this) == msg.sender, "Controllable: caller is not a controller" ); _; } /** * @dev Add an address allowed to control this contract */ function _addController(address _controller) internal { _controllers[_controller] = true; } /** * @dev Add an address allowed to control this contract */ function addController(address _controller) external override onlyController { _controllers[_controller] = true; } /** * @dev Check if this address is a controller */ function isController(address _address) external view override returns (bool allowed) { allowed = _controllers[_address]; } /** * @dev Check if this address is a controller */ function relinquishControl() external view override onlyController { _controllers[msg.sender]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../access/Controllable.sol"; import "../pool/NFTGemPool.sol"; import "../libs/Create2.sol"; import "../interfaces/INFTGemPoolFactory.sol"; contract NFTGemPoolFactory is Controllable, INFTGemPoolFactory { address private operator; mapping(uint256 => address) private _getNFTGemPool; address[] private _allNFTGemPools; constructor() { _addController(msg.sender); } /** * @dev get the quantized token for this */ function getNFTGemPool(uint256 _symbolHash) external view override returns (address gemPool) { gemPool = _getNFTGemPool[_symbolHash]; } /** * @dev get the quantized token for this */ function allNFTGemPools(uint256 idx) external view override returns (address gemPool) { gemPool = _allNFTGemPools[idx]; } /** * @dev number of quantized addresses */ function allNFTGemPoolsLength() external view override returns (uint256) { return _allNFTGemPools.length; } /** * @dev deploy a new erc20 token using create2 */ function createNFTGemPool( string memory gemSymbol, string memory gemName, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffstep, uint256 maxMint, address allowedToken ) external override onlyController returns (address payable gemPool) { bytes32 salt = keccak256(abi.encodePacked(gemSymbol)); require(_getNFTGemPool[uint256(salt)] == address(0), "GEMPOOL_EXISTS"); // single check is sufficient // validation checks to make sure values are sane require(ethPrice != 0, "INVALID_PRICE"); require(minTime != 0, "INVALID_MIN_TIME"); require(diffstep != 0, "INVALID_DIFFICULTY_STEP"); // create the quantized erc20 token using create2, which lets us determine the // quantized erc20 address of a token without interacting with the contract itself bytes memory bytecode = type(NFTGemPool).creationCode; // use create2 to deploy the quantized erc20 contract gemPool = payable(Create2.deploy(0, salt, bytecode)); // initialize the erc20 contract with the relevant addresses which it proxies NFTGemPool(gemPool).initialize(gemSymbol, gemName, ethPrice, minTime, maxTime, diffstep, maxMint, allowedToken); // insert the erc20 contract address into lists - one that maps source to quantized, _getNFTGemPool[uint256(salt)] = gemPool; _allNFTGemPools.push(gemPool); // emit an event about the new pool being created emit NFTGemPoolCreated(gemSymbol, gemName, ethPrice, minTime, maxTime, diffstep, maxMint, allowedToken); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; interface IControllable { event ControllerAdded(address indexed contractAddress, address indexed controllerAddress); event ControllerRemoved(address indexed contractAddress, address indexed controllerAddress); function addController(address controller) external; function isController(address controller) external view returns (bool); function relinquishControl() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "./IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; interface INFTGemFeeManager { event DefaultFeeDivisorChanged(address indexed operator, uint256 oldValue, uint256 value); event FeeDivisorChanged(address indexed operator, address indexed token, uint256 oldValue, uint256 value); event ETHReceived(address indexed manager, address sender, uint256 value); event LiquidityChanged(address indexed manager, uint256 oldValue, uint256 value); function liquidity(address token) external view returns (uint256); function defaultLiquidity() external view returns (uint256); function setDefaultLiquidity(uint256 _liquidityMult) external returns (uint256); function feeDivisor(address token) external view returns (uint256); function defaultFeeDivisor() external view returns (uint256); function setFeeDivisor(address token, uint256 _feeDivisor) external returns (uint256); function setDefaultFeeDivisor(uint256 _feeDivisor) external returns (uint256); function ethBalanceOf() external view returns (uint256); function balanceOF(address token) external view returns (uint256); function transferEth(address payable recipient, uint256 amount) external; function transferToken( address token, address recipient, uint256 amount ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface INFTGemGovernor { event GovernanceTokenIssued(address indexed receiver, uint256 amount); event FeeUpdated(address indexed proposal, address indexed token, uint256 newFee); event AllowList(address indexed proposal, address indexed token, bool isBanned); event ProjectFunded(address indexed proposal, address indexed receiver, uint256 received); event StakingPoolCreated( address indexed proposal, address indexed pool, string symbol, string name, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffStep, uint256 maxClaims, address alllowedToken ); function initialize( address _multitoken, address _factory, address _feeTracker, address _proposalFactory, address _swapHelper ) external; function createProposalVoteTokens(uint256 proposalHash) external; function destroyProposalVoteTokens(uint256 proposalHash) external; function executeProposal(address propAddress) external; function issueInitialGovernanceTokens(address receiver) external returns (uint256); function maybeIssueGovernanceToken(address receiver) external returns (uint256); function issueFuelToken(address receiver, uint256 amount) external returns (uint256); function createPool( string memory symbol, string memory name, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffstep, uint256 maxClaims, address allowedToken ) external returns (address); function createSystemPool( string memory symbol, string memory name, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffstep, uint256 maxClaims, address allowedToken ) external returns (address); function createNewPoolProposal( address, string memory, string memory, string memory, uint256, uint256, uint256, uint256, uint256, address ) external returns (address); function createChangeFeeProposal( address, string memory, address, address, uint256 ) external returns (address); function createFundProjectProposal( address, string memory, address, string memory, uint256 ) external returns (address); function createUpdateAllowlistProposal( address, string memory, address, address, bool ) external returns (address); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface INFTGemMultiToken { // called by controller to mint a claim or a gem function mint( address account, uint256 tokenHash, uint256 amount ) external; // called by controller to burn a claim function burn( address account, uint256 tokenHash, uint256 amount ) external; function allHeldTokens(address holder, uint256 _idx) external view returns (uint256); function allHeldTokensLength(address holder) external view returns (uint256); function allTokenHolders(uint256 _token, uint256 _idx) external view returns (address); function allTokenHoldersLength(uint256 _token) external view returns (uint256); function totalBalances(uint256 _id) external view returns (uint256); function allProxyRegistries(uint256 _idx) external view returns (address); function allProxyRegistriesLength() external view returns (uint256); function addProxyRegistry(address registry) external; function removeProxyRegistryAt(uint256 index) external; function getRegistryManager() external view returns (address); function setRegistryManager(address newManager) external; function lock(uint256 token, uint256 timeframe) external; function unlockTime(address account, uint256 token) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface for a Bitgem staking pool */ interface INFTGemPool { /** * @dev Event generated when an NFT claim is created using ETH */ event NFTGemClaimCreated(address account, address pool, uint256 claimHash, uint256 length, uint256 quantity, uint256 amountPaid); /** * @dev Event generated when an NFT claim is created using ERC20 tokens */ event NFTGemERC20ClaimCreated( address account, address pool, uint256 claimHash, uint256 length, address token, uint256 quantity, uint256 conversionRate ); /** * @dev Event generated when an NFT claim is redeemed */ event NFTGemClaimRedeemed( address account, address pool, uint256 claimHash, uint256 amountPaid, uint256 feeAssessed ); /** * @dev Event generated when an NFT claim is redeemed */ event NFTGemERC20ClaimRedeemed( address account, address pool, uint256 claimHash, address token, uint256 ethPrice, uint256 tokenAmount, uint256 feeAssessed ); /** * @dev Event generated when a gem is created */ event NFTGemCreated(address account, address pool, uint256 claimHash, uint256 gemHash, uint256 quantity); function setMultiToken(address token) external; function setGovernor(address addr) external; function setFeeTracker(address addr) external; function setSwapHelper(address addr) external; function mintGenesisGems(address creator, address funder) external; function createClaim(uint256 timeframe) external payable; function createClaims(uint256 timeframe, uint256 count) external payable; function createERC20Claim(address erc20token, uint256 tokenAmount) external; function createERC20Claims(address erc20token, uint256 tokenAmount, uint256 count) external; function collectClaim(uint256 claimHash) external; function initialize( string memory, string memory, uint256, uint256, uint256, uint256, uint256, address ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; interface INFTGemPoolData { // pool is inited with these parameters. Once inited, all // but ethPrice are immutable. ethPrice only increases. ONLY UP function symbol() external view returns (string memory); function name() external view returns (string memory); function ethPrice() external view returns (uint256); function minTime() external view returns (uint256); function maxTime() external view returns (uint256); function difficultyStep() external view returns (uint256); function maxClaims() external view returns (uint256); // these describe the pools created contents over time. This is where // you query to get information about a token that a pool created function claimedCount() external view returns (uint256); function claimAmount(uint256 claimId) external view returns (uint256); function claimQuantity(uint256 claimId) external view returns (uint256); function mintedCount() external view returns (uint256); function totalStakedEth() external view returns (uint256); function tokenId(uint256 tokenHash) external view returns (uint256); function tokenType(uint256 tokenHash) external view returns (uint8); function allTokenHashesLength() external view returns (uint256); function allTokenHashes(uint256 ndx) external view returns (uint256); function nextClaimHash() external view returns (uint256); function nextGemHash() external view returns (uint256); function nextGemId() external view returns (uint256); function nextClaimId() external view returns (uint256); function claimUnlockTime(uint256 claimId) external view returns (uint256); function claimTokenAmount(uint256 claimId) external view returns (uint256); function stakedToken(uint256 claimId) external view returns (address); function allowedTokensLength() external view returns (uint256); function allowedTokens(uint256 idx) external view returns (address); function isTokenAllowed(address token) external view returns (bool); function addAllowedToken(address token) external; function removeAllowedToken(address token) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface for a Bitgem staking pool */ interface INFTGemPoolFactory { /** * @dev emitted when a new gem pool has been added to the system */ event NFTGemPoolCreated( string gemSymbol, string gemName, uint256 ethPrice, uint256 mintTime, uint256 maxTime, uint256 diffstep, uint256 maxMint, address allowedToken ); function getNFTGemPool(uint256 _symbolHash) external view returns (address); function allNFTGemPools(uint256 idx) external view returns (address); function allNFTGemPoolsLength() external view returns (uint256); function createNFTGemPool( string memory gemSymbol, string memory gemName, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffstep, uint256 maxMint, address allowedToken ) external returns (address payable); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; interface ISwapQueryHelper { function coinQuote(address token, uint256 tokenAmount) external view returns ( uint256, uint256, uint256 ); function factory() external pure returns (address); function COIN() external pure returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function hasPool(address token) external view returns (bool); function getReserves( address pair ) external view returns (uint256, uint256); function pairFor( address tokenA, address tokenB ) external pure returns (address); function getPathForCoinToToken(address token) external pure returns (address[] memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /** * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer. * `CREATE2` can be used to compute in advance the address where a smart * contract will be deployed, which allows for interesting new mechanisms known * as 'counterfactual interactions'. * * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more * information. */ library Create2 { /** * @dev Deploys a contract using `CREATE2`. The address where the contract * will be deployed can be known in advance via {computeAddress}. * * The bytecode for a contract can be obtained from Solidity with * `type(contractName).creationCode`. * * Requirements: * * - `bytecode` must not be empty. * - `salt` must have not been used for `bytecode` already. * - the factory must have a balance of at least `amount`. * - if `amount` is non-zero, `bytecode` must have a `payable` constructor. */ function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address) { address addr; require(address(this).balance >= amount, "Create2: insufficient balance"); require(bytecode.length != 0, "Create2: bytecode length is zero"); // solhint-disable-next-line no-inline-assembly assembly { addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt) } require(addr != address(0), "Create2: Failed on deploy"); return addr; } /** * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the * `bytecodeHash` or `salt` will result in a new destination address. */ function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) { return computeAddress(salt, bytecodeHash, address(this)); } /** * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}. */ function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address) { bytes32 _data = keccak256( abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash) ); return address(uint160(uint256(_data))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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.0; import "../utils/Initializable.sol"; import "../interfaces/INFTGemMultiToken.sol"; import "../interfaces/INFTGemFeeManager.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/IERC1155.sol"; import "../interfaces/INFTGemPool.sol"; import "../interfaces/INFTGemGovernor.sol"; import "../interfaces/ISwapQueryHelper.sol"; import "../libs/SafeMath.sol"; import "./NFTGemPoolData.sol"; contract NFTGemPool is Initializable, NFTGemPoolData, INFTGemPool { using SafeMath for uint256; // governor and multitoken target address private _multitoken; address private _governor; address private _feeTracker; address private _swapHelper; /** * @dev initializer called when contract is deployed */ function initialize ( string memory __symbol, string memory __name, uint256 __ethPrice, uint256 __minTime, uint256 __maxTime, uint256 __diffstep, uint256 __maxClaims, address __allowedToken ) external override initializer { _symbol = __symbol; _name = __name; _ethPrice = __ethPrice; _minTime = __minTime; _maxTime = __maxTime; _diffstep = __diffstep; _maxClaims = __maxClaims; if(__allowedToken != address(0)) { _allowedTokens.push(__allowedToken); _isAllowedMap[__allowedToken] = true; } } /** * @dev set the governor. pool uses the governor to issue gov token issuance requests */ function setGovernor(address addr) external override { require(_governor == address(0), "IMMUTABLE"); _governor = addr; } /** * @dev set the governor. pool uses the governor to issue gov token issuance requests */ function setFeeTracker(address addr) external override { require(_feeTracker == address(0), "IMMUTABLE"); _feeTracker = addr; } /** * @dev set the multitoken that this pool will mint new tokens on. Must be a controller of the multitoken */ function setMultiToken(address token) external override { require(_multitoken == address(0), "IMMUTABLE"); _multitoken = token; } /** * @dev set the multitoken that this pool will mint new tokens on. Must be a controller of the multitoken */ function setSwapHelper(address helper) external override { require(_swapHelper == address(0), "IMMUTABLE"); _swapHelper = helper; } /** * @dev mint the genesis gems earned by the pools creator and funder */ function mintGenesisGems(address creator, address funder) external override { require(_multitoken != address(0), "NO_MULTITOKEN"); require(creator != address(0) && funder != address(0), "ZERO_DESTINATION"); require(_nextGemId == 0, "ALREADY_MINTED"); uint256 gemHash = _nextGemHash(); INFTGemMultiToken(_multitoken).mint(creator, gemHash, 1); _addToken(gemHash, 2); gemHash = _nextGemHash(); INFTGemMultiToken(_multitoken).mint(creator, gemHash, 1); _addToken(gemHash, 2); } /** * @dev the external version of the above */ function createClaim(uint256 timeframe) external payable override { _createClaim(timeframe); } /** * @dev the external version of the above */ function createClaims(uint256 timeframe, uint256 count) external payable override { _createClaims(timeframe, count); } /** * @dev create a claim using a erc20 token */ function createERC20Claim(address erc20token, uint256 tokenAmount) external override { _createERC20Claim(erc20token, tokenAmount); } /** * @dev create a claim using a erc20 token */ function createERC20Claims(address erc20token, uint256 tokenAmount, uint256 count) external override { _createERC20Claims(erc20token, tokenAmount, count); } /** * @dev default receive. tries to issue a claim given the received ETH or */ receive() external payable { uint256 incomingEth = msg.value; // compute the mimimum cost of a claim and revert if not enough sent uint256 minClaimCost = _ethPrice.div(_maxTime).mul(_minTime); require(incomingEth >= minClaimCost, "INSUFFICIENT_ETH"); // compute the minimum actual claim time uint256 actualClaimTime = _minTime; // refund ETH above max claim cost if (incomingEth <= _ethPrice) { actualClaimTime = _ethPrice.div(incomingEth).mul(_minTime); } // create the claim using minimum possible claim time _createClaim(actualClaimTime); } /** * @dev attempt to create a claim using the given timeframe */ function _createClaim(uint256 timeframe) internal { // minimum timeframe require(timeframe >= _minTime, "TIMEFRAME_TOO_SHORT"); // maximum timeframe require((_maxTime != 0 && timeframe <= _maxTime) || _maxTime == 0, "TIMEFRAME_TOO_LONG"); // cost given this timeframe uint256 cost = _ethPrice.mul(_minTime).div(timeframe); require(msg.value > cost, "INSUFFICIENT_ETH"); // get the nest claim hash, revert if no more claims uint256 claimHash = _nextClaimHash(); require(claimHash != 0, "NO_MORE_CLAIMABLE"); // mint the new claim to the caller's address INFTGemMultiToken(_multitoken).mint(msg.sender, claimHash, 1); _addToken(claimHash, 1); // record the claim unlock time and cost paid for this claim uint256 _claimUnlockTime = block.timestamp.add(timeframe); claimLockTimestamps[claimHash] = _claimUnlockTime; claimAmountPaid[claimHash] = cost; claimQuant[claimHash] = 1; // increase the staked eth balance _totalStakedEth = _totalStakedEth.add(cost); // maybe mint a governance token for the claimant INFTGemGovernor(_governor).maybeIssueGovernanceToken(msg.sender); INFTGemGovernor(_governor).issueFuelToken(msg.sender, cost); emit NFTGemClaimCreated(msg.sender, address(this), claimHash, timeframe, 1, cost); if (msg.value > cost) { (bool success, ) = payable(msg.sender).call{value: msg.value.sub(cost)}(""); require(success, "REFUND_FAILED"); } } /** * @dev attempt to create a claim using the given timeframe */ function _createClaims(uint256 timeframe, uint256 count) internal { // minimum timeframe require(timeframe >= _minTime, "TIMEFRAME_TOO_SHORT"); // no ETH require(msg.value != 0, "ZERO_BALANCE"); // zero qty require(count != 0, "ZERO_QUANTITY"); // maximum timeframe require((_maxTime != 0 && timeframe <= _maxTime) || _maxTime == 0, "TIMEFRAME_TOO_LONG"); uint256 adjustedBalance = msg.value.div(count); // cost given this timeframe uint256 cost = _ethPrice.mul(_minTime).div(timeframe); require(adjustedBalance >= cost, "INSUFFICIENT_ETH"); // get the nest claim hash, revert if no more claims uint256 claimHash = _nextClaimHash(); require(claimHash != 0, "NO_MORE_CLAIMABLE"); // mint the new claim to the caller's address INFTGemMultiToken(_multitoken).mint(msg.sender, claimHash, 1); _addToken(claimHash, 1); // record the claim unlock time and cost paid for this claim uint256 _claimUnlockTime = block.timestamp.add(timeframe); claimLockTimestamps[claimHash] = _claimUnlockTime; claimAmountPaid[claimHash] = cost.mul(count); claimQuant[claimHash] = count; // maybe mint a governance token for the claimant INFTGemGovernor(_governor).maybeIssueGovernanceToken(msg.sender); INFTGemGovernor(_governor).issueFuelToken(msg.sender, cost); emit NFTGemClaimCreated(msg.sender, address(this), claimHash, timeframe, count, cost); // increase the staked eth balance _totalStakedEth = _totalStakedEth.add(cost.mul(count)); if (msg.value > cost.mul(count)) { (bool success, ) = payable(msg.sender).call{value: msg.value.sub(cost.mul(count))}(""); require(success, "REFUND_FAILED"); } } /** * @dev crate a gem claim using an erc20 token. this token must be tradeable in Uniswap or this call will fail */ function _createERC20Claim(address erc20token, uint256 tokenAmount) internal { // must be a valid address require(erc20token != address(0), "INVALID_ERC20_TOKEN"); // token is allowed require((_allowedTokens.length > 0 && _isAllowedMap[erc20token]) || _allowedTokens.length == 0, "TOKEN_DISALLOWED"); // Uniswap pool must exist require(ISwapQueryHelper(_swapHelper).hasPool(erc20token) == true, "NO_UNISWAP_POOL"); // must have an amount specified require(tokenAmount >= 0, "NO_PAYMENT_INCLUDED"); // get a quote in ETH for the given token. (uint256 ethereum, uint256 tokenReserve, uint256 ethReserve) = ISwapQueryHelper(_swapHelper).coinQuote(erc20token, tokenAmount); // get the min liquidity from fee tracker uint256 liquidity = INFTGemFeeManager(_feeTracker).liquidity(erc20token); // make sure the convertible amount is has reserves > 100x the token require(ethReserve >= ethereum.mul(liquidity), "INSUFFICIENT_ETH_LIQUIDITY"); // make sure the convertible amount is has reserves > 100x the token require(tokenReserve >= tokenAmount.mul(liquidity), "INSUFFICIENT_TOKEN_LIQUIDITY"); // make sure the convertible amount is less than max price require(ethereum <= _ethPrice, "OVERPAYMENT"); // calculate the maturity time given the converted eth uint256 maturityTime = _ethPrice.mul(_minTime).div(ethereum); // make sure the convertible amount is less than max price require(maturityTime >= _minTime, "INSUFFICIENT_TIME"); // get the next claim hash, revert if no more claims uint256 claimHash = _nextClaimHash(); require(claimHash != 0, "NO_MORE_CLAIMABLE"); // transfer the caller's ERC20 tokens into the pool IERC20(erc20token).transferFrom(msg.sender, address(this), tokenAmount); // mint the new claim to the caller's address INFTGemMultiToken(_multitoken).mint(msg.sender, claimHash, 1); _addToken(claimHash, 1); // record the claim unlock time and cost paid for this claim uint256 _claimUnlockTime = block.timestamp.add(maturityTime); claimLockTimestamps[claimHash] = _claimUnlockTime; claimAmountPaid[claimHash] = ethereum; claimLockToken[claimHash] = erc20token; claimTokenAmountPaid[claimHash] = tokenAmount; claimQuant[claimHash] = 1; _totalStakedEth = _totalStakedEth.add(ethereum); // maybe mint a governance token for the claimant INFTGemGovernor(_governor).maybeIssueGovernanceToken(msg.sender); INFTGemGovernor(_governor).issueFuelToken(msg.sender, ethereum); // emit a message indicating that an erc20 claim has been created emit NFTGemERC20ClaimCreated(msg.sender, address(this), claimHash, maturityTime, erc20token, 1, ethereum); } /** * @dev crate multiple gem claim using an erc20 token. this token must be tradeable in Uniswap or this call will fail */ function _createERC20Claims(address erc20token, uint256 tokenAmount, uint256 count) internal { // must be a valid address require(erc20token != address(0), "INVALID_ERC20_TOKEN"); // token is allowed require((_allowedTokens.length > 0 && _isAllowedMap[erc20token]) || _allowedTokens.length == 0, "TOKEN_DISALLOWED"); // zero qty require(count != 0, "ZERO_QUANTITY"); // Uniswap pool must exist require(ISwapQueryHelper(_swapHelper).hasPool(erc20token) == true, "NO_UNISWAP_POOL"); // must have an amount specified require(tokenAmount >= 0, "NO_PAYMENT_INCLUDED"); // get a quote in ETH for the given token. (uint256 ethereum, uint256 tokenReserve, uint256 ethReserve) = ISwapQueryHelper(_swapHelper).coinQuote( erc20token, tokenAmount.div(count) ); // make sure the convertible amount is has reserves > 100x the token require(ethReserve >= ethereum.mul(100).mul(count), "INSUFFICIENT_ETH_LIQUIDITY"); // make sure the convertible amount is has reserves > 100x the token require(tokenReserve >= tokenAmount.mul(100).mul(count), "INSUFFICIENT_TOKEN_LIQUIDITY"); // make sure the convertible amount is less than max price require(ethereum <= _ethPrice, "OVERPAYMENT"); // calculate the maturity time given the converted eth uint256 maturityTime = _ethPrice.mul(_minTime).div(ethereum); // make sure the convertible amount is less than max price require(maturityTime >= _minTime, "INSUFFICIENT_TIME"); // get the next claim hash, revert if no more claims uint256 claimHash = _nextClaimHash(); require(claimHash != 0, "NO_MORE_CLAIMABLE"); // mint the new claim to the caller's address INFTGemMultiToken(_multitoken).mint(msg.sender, claimHash, 1); _addToken(claimHash, 1); // record the claim unlock time and cost paid for this claim uint256 _claimUnlockTime = block.timestamp.add(maturityTime); claimLockTimestamps[claimHash] = _claimUnlockTime; claimAmountPaid[claimHash] = ethereum; claimLockToken[claimHash] = erc20token; claimTokenAmountPaid[claimHash] = tokenAmount; claimQuant[claimHash] = count; // increase staked eth amount _totalStakedEth = _totalStakedEth.add(ethereum); // maybe mint a governance token for the claimant INFTGemGovernor(_governor).maybeIssueGovernanceToken(msg.sender); INFTGemGovernor(_governor).issueFuelToken(msg.sender, ethereum); // emit a message indicating that an erc20 claim has been created emit NFTGemERC20ClaimCreated(msg.sender, address(this), claimHash, maturityTime, erc20token, count, ethereum); // transfer the caller's ERC20 tokens into the pool IERC20(erc20token).transferFrom(msg.sender, address(this), tokenAmount); } /** * @dev collect an open claim (take custody of the funds the claim is redeeemable for and maybe a gem too) */ function collectClaim(uint256 claimHash) external override { // validation checks - disallow if not owner (holds coin with claimHash) // or if the unlockTime amd unlockPaid data is in an invalid state require(IERC1155(_multitoken).balanceOf(msg.sender, claimHash) == 1, "NOT_CLAIM_OWNER"); uint256 unlockTime = claimLockTimestamps[claimHash]; uint256 unlockPaid = claimAmountPaid[claimHash]; require(unlockTime != 0 && unlockPaid > 0, "INVALID_CLAIM"); // grab the erc20 token info if there is any address tokenUsed = claimLockToken[claimHash]; uint256 unlockTokenPaid = claimTokenAmountPaid[claimHash]; // check the maturity of the claim - only issue gem if mature bool isMature = unlockTime < block.timestamp; // burn claim and transfer money back to user INFTGemMultiToken(_multitoken).burn(msg.sender, claimHash, 1); // if they used erc20 tokens stake their claim, return their tokens if (tokenUsed != address(0)) { // calculate fee portion using fee tracker uint256 feePortion = 0; if (isMature == true) { uint256 poolDiv = INFTGemFeeManager(_feeTracker).feeDivisor(address(this)); uint256 divisor = INFTGemFeeManager(_feeTracker).feeDivisor(tokenUsed); uint256 feeNum = poolDiv != divisor ? divisor : poolDiv; feePortion = unlockTokenPaid.div(feeNum); } // assess a fee for minting the NFT. Fee is collectec in fee tracker IERC20(tokenUsed).transferFrom(address(this), _feeTracker, feePortion); // send the principal minus fees to the caller IERC20(tokenUsed).transferFrom(address(this), msg.sender, unlockTokenPaid.sub(feePortion)); // emit an event that the claim was redeemed for ERC20 emit NFTGemERC20ClaimRedeemed( msg.sender, address(this), claimHash, tokenUsed, unlockPaid, unlockTokenPaid, feePortion ); } else { // calculate fee portion using fee tracker uint256 feePortion = 0; if (isMature == true) { uint256 divisor = INFTGemFeeManager(_feeTracker).feeDivisor(address(0)); feePortion = unlockPaid.div(divisor); } // transfer the ETH fee to fee tracker payable(_feeTracker).transfer(feePortion); // transfer the ETH back to user payable(msg.sender).transfer(unlockPaid.sub(feePortion)); // emit an event that the claim was redeemed for ETH emit NFTGemClaimRedeemed(msg.sender, address(this), claimHash, unlockPaid, feePortion); } // deduct the total staked ETH balance of the pool _totalStakedEth = _totalStakedEth.sub(unlockPaid); // if all this is happening before the unlocktime then we exit // without minting a gem because the user is withdrawing early if (!isMature) { return; } // get the next gem hash, increase the staking sifficulty // for the pool, and mint a gem token back to account uint256 nextHash = this.nextGemHash(); // mint the gem INFTGemMultiToken(_multitoken).mint(msg.sender, nextHash, claimQuant[claimHash]); _addToken(nextHash, 2); // maybe mint a governance token INFTGemGovernor(_governor).maybeIssueGovernanceToken(msg.sender); INFTGemGovernor(_governor).issueFuelToken(msg.sender, unlockPaid); // emit an event about a gem getting created emit NFTGemCreated(msg.sender, address(this), claimHash, nextHash, claimQuant[claimHash]); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../libs/SafeMath.sol"; import "../utils/Initializable.sol"; import "../interfaces/INFTGemPoolData.sol"; contract NFTGemPoolData is INFTGemPoolData, Initializable { using SafeMath for uint256; // it all starts with a symbol and a nams string internal _symbol; string internal _name; // magic economy numbers uint256 internal _ethPrice; uint256 internal _minTime; uint256 internal _maxTime; uint256 internal _diffstep; uint256 internal _maxClaims; mapping(uint256 => uint8) internal _tokenTypes; mapping(uint256 => uint256) internal _tokenIds; uint256[] internal _tokenHashes; // next ids of things uint256 internal _nextGemId; uint256 internal _nextClaimId; uint256 internal _totalStakedEth; // records claim timestamp / ETH value / ERC token and amount sent mapping(uint256 => uint256) internal claimLockTimestamps; mapping(uint256 => address) internal claimLockToken; mapping(uint256 => uint256) internal claimAmountPaid; mapping(uint256 => uint256) internal claimQuant; mapping(uint256 => uint256) internal claimTokenAmountPaid; address[] internal _allowedTokens; mapping(address => bool) internal _isAllowedMap; constructor() {} /** * @dev The symbol for this pool / NFT */ function symbol() external view override returns (string memory) { return _symbol; } /** * @dev The name for this pool / NFT */ function name() external view override returns (string memory) { return _name; } /** * @dev The ether price for this pool / NFT */ function ethPrice() external view override returns (uint256) { return _ethPrice; } /** * @dev min time to stake in this pool to earn an NFT */ function minTime() external view override returns (uint256) { return _minTime; } /** * @dev max time to stake in this pool to earn an NFT */ function maxTime() external view override returns (uint256) { return _maxTime; } /** * @dev difficulty step increase for this pool. */ function difficultyStep() external view override returns (uint256) { return _diffstep; } /** * @dev max claims that can be made on this NFT */ function maxClaims() external view override returns (uint256) { return _maxClaims; } /** * @dev number of claims made thus far */ function claimedCount() external view override returns (uint256) { return _nextClaimId; } /** * @dev the number of gems minted in this */ function mintedCount() external view override returns (uint256) { return _nextGemId; } /** * @dev the number of gems minted in this */ function totalStakedEth() external view override returns (uint256) { return _totalStakedEth; } /** * @dev get token type of hash - 1 is for claim, 2 is for gem */ function tokenType(uint256 tokenHash) external view override returns (uint8) { return _tokenTypes[tokenHash]; } /** * @dev get token id (serial #) of the given token hash. 0 if not a token, 1 if claim, 2 if gem */ function tokenId(uint256 tokenHash) external view override returns (uint256) { return _tokenIds[tokenHash]; } /** * @dev get token id (serial #) of the given token hash. 0 if not a token, 1 if claim, 2 if gem */ function allTokenHashesLength() external view override returns (uint256) { return _tokenHashes.length; } /** * @dev get token id (serial #) of the given token hash. 0 if not a token, 1 if claim, 2 if gem */ function allTokenHashes(uint256 ndx) external view override returns (uint256) { return _tokenHashes[ndx]; } /** * @dev the external version of the above */ function nextClaimHash() external view override returns (uint256) { return _nextClaimHash(); } /** * @dev the external version of the above */ function nextGemHash() external view override returns (uint256) { return _nextGemHash(); } /** * @dev the external version of the above */ function nextClaimId() external view override returns (uint256) { return _nextClaimId; } /** * @dev the external version of the above */ function nextGemId() external view override returns (uint256) { return _nextGemId; } /** * @dev the external version of the above */ function allowedTokensLength() external view override returns (uint256) { return _allowedTokens.length; } /** * @dev the external version of the above */ function allowedTokens(uint256 idx) external view override returns (address) { return _allowedTokens[idx]; } /** * @dev the external version of the above */ function isTokenAllowed(address token) external view override returns (bool) { return _isAllowedMap[token]; } /** * @dev the external version of the above */ function addAllowedToken(address token) external override { if(!_isAllowedMap[token]) { _allowedTokens.push(token); _isAllowedMap[token] = true; } } /** * @dev the external version of the above */ function removeAllowedToken(address token) external override { if(_isAllowedMap[token]) { for(uint256 i = 0; i < _allowedTokens.length; i++) { if(_allowedTokens[i] == token) { _allowedTokens[i] = _allowedTokens[_allowedTokens.length - 1]; delete _allowedTokens[_allowedTokens.length - 1]; _isAllowedMap[token] = false; return; } } } } /** * @dev the claim amount for the given claim id */ function claimAmount(uint256 claimHash) external view override returns (uint256) { return claimAmountPaid[claimHash]; } /** * @dev the claim quantity (count of gems staked) for the given claim id */ function claimQuantity(uint256 claimHash) external view override returns (uint256) { return claimQuant[claimHash]; } /** * @dev the lock time for this claim. once past lock time a gema is minted */ function claimUnlockTime(uint256 claimHash) external view override returns (uint256) { return claimLockTimestamps[claimHash]; } /** * @dev claim token amount if paid using erc20 */ function claimTokenAmount(uint256 claimHash) external view override returns (uint256) { return claimTokenAmountPaid[claimHash]; } /** * @dev the staked token if staking with erc20 */ function stakedToken(uint256 claimHash) external view override returns (address) { return claimLockToken[claimHash]; } /** * @dev get token id (serial #) of the given token hash. 0 if not a token, 1 if claim, 2 if gem */ function _addToken(uint256 tokenHash, uint8 tt) internal { require(tt == 1 || tt == 2, "INVALID_TOKENTYPE"); _tokenHashes.push(tokenHash); _tokenTypes[tokenHash] = tt; _tokenIds[tokenHash] = tt == 1 ? __nextClaimId() : __nextGemId(); if(tt == 2) { _increaseDifficulty(); } } /** * @dev get the next claim id */ function __nextClaimId() private returns (uint256) { uint256 ncId = _nextClaimId; _nextClaimId = _nextClaimId.add(1); return ncId; } /** * @dev get the next gem id */ function __nextGemId() private returns (uint256) { uint256 ncId = _nextGemId; _nextGemId = _nextGemId.add(1); return ncId; } /** * @dev increase the pool's difficulty by calculating the step increase portion and adding it to the eth price of the market */ function _increaseDifficulty() private { uint256 diffIncrease = _ethPrice.div(_diffstep); _ethPrice = _ethPrice.add(diffIncrease); } /** * @dev the hash of the next gem to be minted */ function _nextGemHash() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked("gem", address(this), _nextGemId))); } /** * @dev the hash of the next claim to be minted */ function _nextClaimHash() internal view returns (uint256) { return (_maxClaims != 0 && _nextClaimId <= _maxClaims) || _maxClaims == 0 ? uint256(keccak256(abi.encodePacked("claim", address(this), _nextClaimId))) : 0; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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 // solhint-disable-next-line compiler-version pragma solidity >=0.4.24; import "../utils/Address.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 !Address.isContract(address(this)); } }
get token id (serial ) of the given token hash. 0 if not a token, 1 if claim, 2 if gem/
function _addToken(uint256 tokenHash, uint8 tt) internal { require(tt == 1 || tt == 2, "INVALID_TOKENTYPE"); _tokenHashes.push(tokenHash); _tokenTypes[tokenHash] = tt; _tokenIds[tokenHash] = tt == 1 ? __nextClaimId() : __nextGemId(); if(tt == 2) { _increaseDifficulty(); } }
11,794,183
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {ISYNC} from "./interfaces/ISYNC.sol"; /** * @title TokenDistributor * @notice It handles the distribution of SYNC token. * It auto-adjusts block rewards over a set number of periods. */ contract TokenDistributor is ReentrancyGuard { using SafeERC20 for IERC20; using SafeERC20 for ISYNC; struct StakingPeriod { uint256 rewardPerBlockForStaking; uint256 rewardPerBlockForOthers; uint256 periodLengthInBlock; } struct UserInfo { uint256 amount; // Amount of staked tokens provided by user uint256 rewardDebt; // Reward debt } // Precision factor for calculating rewards uint256 public constant PRECISION_FACTOR = 10**12; ISYNC public immutable SYNCToken; address public immutable tokenSplitter; // Number of reward periods uint256 public immutable NUMBER_PERIODS; // Block number when rewards start uint256 public immutable START_BLOCK; // Accumulated tokens per share uint256 public accTokenPerShare; // Current phase for rewards uint256 public currentPhase; // Block number when rewards end uint256 public endBlock; // Block number of the last update uint256 public lastRewardBlock; // Tokens distributed per block for other purposes (team + treasury + trading rewards) uint256 public rewardPerBlockForOthers; // Tokens distributed per block for staking uint256 public rewardPerBlockForStaking; // Total amount staked uint256 public totalAmountStaked; mapping(uint256 => StakingPeriod) public stakingPeriod; mapping(address => UserInfo) public userInfo; event Compound(address indexed user, uint256 harvestedAmount); event Deposit(address indexed user, uint256 amount, uint256 harvestedAmount); event NewRewardsPerBlock( uint256 indexed currentPhase, uint256 startBlock, uint256 rewardPerBlockForStaking, uint256 rewardPerBlockForOthers ); event Withdraw(address indexed user, uint256 amount, uint256 harvestedAmount); /** * @notice Constructor * @param _SYNCToken SYNC token address * @param _tokenSplitter token splitter contract address (for team and trading rewards) * @param _startBlock start block for reward program * @param _rewardsPerBlockForStaking array of rewards per block for staking * @param _rewardsPerBlockForOthers array of rewards per block for other purposes (team + treasury + trading rewards) * @param _periodLengthesInBlocks array of period lengthes * @param _numberPeriods number of periods with different rewards/lengthes (e.g., if 3 changes --> 4 periods) */ constructor( address _SYNCToken, address _tokenSplitter, uint256 _startBlock, uint256[] memory _rewardsPerBlockForStaking, uint256[] memory _rewardsPerBlockForOthers, uint256[] memory _periodLengthesInBlocks, uint256 _numberPeriods ) { require( (_periodLengthesInBlocks.length == _numberPeriods) && (_rewardsPerBlockForStaking.length == _numberPeriods) && (_rewardsPerBlockForStaking.length == _numberPeriods), "Distributor: Lengthes must match numberPeriods" ); // 1. Operational checks for supply uint256 nonCirculatingSupply = ISYNC(_SYNCToken).SUPPLY_CAP() - ISYNC(_SYNCToken).totalSupply(); uint256 amountTokensToBeMinted; for (uint256 i = 0; i < _numberPeriods; i++) { amountTokensToBeMinted += (_rewardsPerBlockForStaking[i] * _periodLengthesInBlocks[i]) + (_rewardsPerBlockForOthers[i] * _periodLengthesInBlocks[i]); stakingPeriod[i] = StakingPeriod({ rewardPerBlockForStaking: _rewardsPerBlockForStaking[i], rewardPerBlockForOthers: _rewardsPerBlockForOthers[i], periodLengthInBlock: _periodLengthesInBlocks[i] }); } require(amountTokensToBeMinted == nonCirculatingSupply, "Distributor: Wrong reward parameters"); // 2. Store values SYNCToken = ISYNC(_SYNCToken); tokenSplitter = _tokenSplitter; rewardPerBlockForStaking = _rewardsPerBlockForStaking[0]; rewardPerBlockForOthers = _rewardsPerBlockForOthers[0]; START_BLOCK = _startBlock; endBlock = _startBlock + _periodLengthesInBlocks[0]; NUMBER_PERIODS = _numberPeriods; // Set the lastRewardBlock as the startBlock lastRewardBlock = _startBlock; } /** * @notice Deposit staked tokens and compounds pending rewards * @param amount amount to deposit (in SYNC) */ function deposit(uint256 amount) external nonReentrant { require(amount > 0, "Deposit: Amount must be > 0"); // Update pool information _updatePool(); // Transfer SYNC tokens to this contract SYNCToken.safeTransferFrom(msg.sender, address(this), amount); uint256 pendingRewards; // If not new deposit, calculate pending rewards (for auto-compounding) if (userInfo[msg.sender].amount > 0) { pendingRewards = ((userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR) - userInfo[msg.sender].rewardDebt; } // Adjust user information userInfo[msg.sender].amount += (amount + pendingRewards); userInfo[msg.sender].rewardDebt = (userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR; // Increase totalAmountStaked totalAmountStaked += (amount + pendingRewards); emit Deposit(msg.sender, amount, pendingRewards); } /** * @notice Compound based on pending rewards */ function harvestAndCompound() external nonReentrant { // Update pool information _updatePool(); // Calculate pending rewards uint256 pendingRewards = ((userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR) - userInfo[msg.sender].rewardDebt; // Return if no pending rewards if (pendingRewards == 0) { // It doesn't throw revertion (to help with the fee-sharing auto-compounding contract) return; } // Adjust user amount for pending rewards userInfo[msg.sender].amount += pendingRewards; // Adjust totalAmountStaked totalAmountStaked += pendingRewards; // Recalculate reward debt based on new user amount userInfo[msg.sender].rewardDebt = (userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR; emit Compound(msg.sender, pendingRewards); } /** * @notice Update pool rewards */ function updatePool() external nonReentrant { _updatePool(); } /** * @notice Withdraw staked tokens and compound pending rewards * @param amount amount to withdraw */ function withdraw(uint256 amount) external nonReentrant { require( (userInfo[msg.sender].amount >= amount) && (amount > 0), "Withdraw: Amount must be > 0 or lower than user balance" ); // Update pool _updatePool(); // Calculate pending rewards uint256 pendingRewards = ((userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR) - userInfo[msg.sender].rewardDebt; // Adjust user information userInfo[msg.sender].amount = userInfo[msg.sender].amount + pendingRewards - amount; userInfo[msg.sender].rewardDebt = (userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR; // Adjust total amount staked totalAmountStaked = totalAmountStaked + pendingRewards - amount; // Transfer SYNC tokens to the sender SYNCToken.safeTransfer(msg.sender, amount); emit Withdraw(msg.sender, amount, pendingRewards); } /** * @notice Withdraw all staked tokens and collect tokens */ function withdrawAll() external nonReentrant { require(userInfo[msg.sender].amount > 0, "Withdraw: Amount must be > 0"); // Update pool _updatePool(); // Calculate pending rewards and amount to transfer (to the sender) uint256 pendingRewards = ((userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR) - userInfo[msg.sender].rewardDebt; uint256 amountToTransfer = userInfo[msg.sender].amount + pendingRewards; // Adjust total amount staked totalAmountStaked = totalAmountStaked - userInfo[msg.sender].amount; // Adjust user information userInfo[msg.sender].amount = 0; userInfo[msg.sender].rewardDebt = 0; // Transfer SYNC tokens to the sender SYNCToken.safeTransfer(msg.sender, amountToTransfer); emit Withdraw(msg.sender, amountToTransfer, pendingRewards); } /** * @notice Calculate pending rewards for a user * @param user address of the user * @return Pending rewards */ function calculatePendingRewards(address user) external view returns (uint256) { if ((block.number > lastRewardBlock) && (totalAmountStaked != 0)) { uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); uint256 tokenRewardForStaking = multiplier * rewardPerBlockForStaking; uint256 adjustedEndBlock = endBlock; uint256 adjustedCurrentPhase = currentPhase; // Check whether to adjust multipliers and reward per block while ((block.number > adjustedEndBlock) && (adjustedCurrentPhase < (NUMBER_PERIODS - 1))) { // Update current phase adjustedCurrentPhase++; // Update rewards per block uint256 adjustedRewardPerBlockForStaking = stakingPeriod[adjustedCurrentPhase].rewardPerBlockForStaking; // Calculate adjusted block number uint256 previousEndBlock = adjustedEndBlock; // Update end block adjustedEndBlock = previousEndBlock + stakingPeriod[adjustedCurrentPhase].periodLengthInBlock; // Calculate new multiplier uint256 newMultiplier = (block.number <= adjustedEndBlock) ? (block.number - previousEndBlock) : stakingPeriod[adjustedCurrentPhase].periodLengthInBlock; // Adjust token rewards for staking tokenRewardForStaking += (newMultiplier * adjustedRewardPerBlockForStaking); } uint256 adjustedTokenPerShare = accTokenPerShare + (tokenRewardForStaking * PRECISION_FACTOR) / totalAmountStaked; return (userInfo[user].amount * adjustedTokenPerShare) / PRECISION_FACTOR - userInfo[user].rewardDebt; } else { return (userInfo[user].amount * accTokenPerShare) / PRECISION_FACTOR - userInfo[user].rewardDebt; } } /** * @notice Update reward variables of the pool */ function _updatePool() internal { if (block.number <= lastRewardBlock) { return; } if (totalAmountStaked == 0) { lastRewardBlock = block.number; return; } // Calculate multiplier uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); // Calculate rewards for staking and others uint256 tokenRewardForStaking = multiplier * rewardPerBlockForStaking; uint256 tokenRewardForOthers = multiplier * rewardPerBlockForOthers; // Check whether to adjust multipliers and reward per block while ((block.number > endBlock) && (currentPhase < (NUMBER_PERIODS - 1))) { // Update rewards per block _updateRewardsPerBlock(endBlock); uint256 previousEndBlock = endBlock; // Adjust the end block endBlock += stakingPeriod[currentPhase].periodLengthInBlock; // Adjust multiplier to cover the missing periods with other lower inflation schedule uint256 newMultiplier = _getMultiplier(previousEndBlock, block.number); // Adjust token rewards tokenRewardForStaking += (newMultiplier * rewardPerBlockForStaking); tokenRewardForOthers += (newMultiplier * rewardPerBlockForOthers); } // Mint tokens only if token rewards for staking are not null if (tokenRewardForStaking > 0) { // It allows protection against potential issues to prevent funds from being locked bool mintStatus = SYNCToken.mint(address(this), tokenRewardForStaking); if (mintStatus) { accTokenPerShare = accTokenPerShare + ((tokenRewardForStaking * PRECISION_FACTOR) / totalAmountStaked); } SYNCToken.mint(tokenSplitter, tokenRewardForOthers); } // Update last reward block only if it wasn't updated after or at the end block if (lastRewardBlock <= endBlock) { lastRewardBlock = block.number; } } /** * @notice Update rewards per block * @dev Rewards are halved by 2 (for staking + others) */ function _updateRewardsPerBlock(uint256 _newStartBlock) internal { // Update current phase currentPhase++; // Update rewards per block rewardPerBlockForStaking = stakingPeriod[currentPhase].rewardPerBlockForStaking; rewardPerBlockForOthers = stakingPeriod[currentPhase].rewardPerBlockForOthers; emit NewRewardsPerBlock(currentPhase, _newStartBlock, rewardPerBlockForStaking, rewardPerBlockForOthers); } /** * @notice Return reward multiplier over the given "from" to "to" block. * @param from block to start calculating reward * @param to block to finish calculating reward * @return the multiplier for the period */ function _getMultiplier(uint256 from, uint256 to) internal view returns (uint256) { if (to <= endBlock) { return to - from; } else if (from >= endBlock) { return 0; } else { return endBlock - from; } } }
Update reward variables of the pool/ Check whether to adjust multipliers and reward per block Update rewards per block Adjust the end block Adjust multiplier to cover the missing periods with other lower inflation schedule Adjust token rewards Mint tokens only if token rewards for staking are not null It allows protection against potential issues to prevent funds from being locked Update last reward block only if it wasn't updated after or at the end block
function _updatePool() internal { if (block.number <= lastRewardBlock) { return; } if (totalAmountStaked == 0) { lastRewardBlock = block.number; return; } uint256 tokenRewardForOthers = multiplier * rewardPerBlockForOthers; while ((block.number > endBlock) && (currentPhase < (NUMBER_PERIODS - 1))) { _updateRewardsPerBlock(endBlock); uint256 previousEndBlock = endBlock; endBlock += stakingPeriod[currentPhase].periodLengthInBlock; uint256 newMultiplier = _getMultiplier(previousEndBlock, block.number); tokenRewardForStaking += (newMultiplier * rewardPerBlockForStaking); tokenRewardForOthers += (newMultiplier * rewardPerBlockForOthers); } if (tokenRewardForStaking > 0) { bool mintStatus = SYNCToken.mint(address(this), tokenRewardForStaking); if (mintStatus) { accTokenPerShare = accTokenPerShare + ((tokenRewardForStaking * PRECISION_FACTOR) / totalAmountStaked); } SYNCToken.mint(tokenSplitter, tokenRewardForOthers); } if (lastRewardBlock <= endBlock) { lastRewardBlock = block.number; } }
883,233
./full_match/1/0x23F8B0B57723bcD99D5Be4Cf4863E49D8092dC14/sources/contracts/LbdToken.sol
Ban the Kucoin hacker
function initialize() public initializer { __ERC20_init("Lbd Protocol", "LBD"); _setupDecimals(uint8(DECIMALS)); __Ownable_init(); _totalShares = INITIAL_SHARES; _totalSupply = INITIAL_SUPPLY; _shareBalances[owner()] = _totalShares; _sharesPerLBD = _totalShares.div(_totalSupply); bannedUsers[0xeB31973E0FeBF3e3D7058234a5eBbAe1aB4B8c23] = true; emit Transfer(address(0x0), owner(), _totalSupply); }
8,354,424
/** *Submitted for verification at Etherscan.io on 2021-02-12 */ pragma solidity 0.8.0; interface ISavingsManager { /** @dev Admin privs */ function distributeUnallocatedInterest(address _mAsset) external; /** @dev Liquidator */ function depositLiquidation(address _mAsset, uint256 _liquidation) external; /** @dev Liquidator */ function collectAndStreamInterest(address _mAsset) external; /** @dev Public privs */ function collectAndDistributeInterest(address _mAsset) external; } interface ISavingsContractV2 { // DEPRECATED but still backwards compatible function redeem(uint256 _amount) external returns (uint256 massetReturned); function creditBalances(address) external view returns (uint256); // V1 & V2 (use balanceOf) // -------------------------------------------- function depositInterest(uint256 _amount) external; // V1 & V2 function depositSavings(uint256 _amount) external returns (uint256 creditsIssued); // V1 & V2 function depositSavings(uint256 _amount, address _beneficiary) external returns (uint256 creditsIssued); // V2 function redeemCredits(uint256 _amount) external returns (uint256 underlyingReturned); // V2 function redeemUnderlying(uint256 _amount) external returns (uint256 creditsBurned); // V2 function exchangeRate() external view returns (uint256); // V1 & V2 function balanceOfUnderlying(address _user) external view returns (uint256 balance); // V2 function underlyingToCredits(uint256 _credits) external view returns (uint256 underlying); // V2 function creditsToUnderlying(uint256 _underlying) external view returns (uint256 credits); // V2 } /* * @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 { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. // constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return payable(msg.sender); } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } 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); } contract ERC205 is Context, IERC20 { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public 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 override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_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 returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] -= 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 { require(account != address(0), "ERC20: mint to the zero address"); _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 { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] -= amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()] - amount); } } abstract contract InitializableERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. * @notice To avoid variable shadowing appended `Arg` after arguments name. */ function _initialize( string memory nameArg, string memory symbolArg, uint8 decimalsArg ) internal { _name = nameArg; _symbol = symbolArg; _decimals = decimalsArg; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } abstract contract InitializableToken is ERC205, InitializableERC20Detailed { /** * @dev Initialization function for implementing contract * @notice To avoid variable shadowing appended `Arg` after arguments name. */ function _initialize(string memory _nameArg, string memory _symbolArg) internal { InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18); } } contract ModuleKeys { // Governance // =========== // keccak256("Governance"); bytes32 internal constant KEY_GOVERNANCE = 0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d; //keccak256("Staking"); bytes32 internal constant KEY_STAKING = 0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034; //keccak256("ProxyAdmin"); bytes32 internal constant KEY_PROXY_ADMIN = 0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1; // mStable // ======= // keccak256("OracleHub"); bytes32 internal constant KEY_ORACLE_HUB = 0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040; // keccak256("Manager"); bytes32 internal constant KEY_MANAGER = 0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f; //keccak256("Recollateraliser"); bytes32 internal constant KEY_RECOLLATERALISER = 0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f; //keccak256("MetaToken"); bytes32 internal constant KEY_META_TOKEN = 0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2; // keccak256("SavingsManager"); bytes32 internal constant KEY_SAVINGS_MANAGER = 0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1; // keccak256("Liquidator"); bytes32 internal constant KEY_LIQUIDATOR = 0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4; } interface INexus { function governor() external view returns (address); function getModule(bytes32 key) external view returns (address); function proposeModule(bytes32 _key, address _addr) external; function cancelProposedModule(bytes32 _key) external; function acceptProposedModule(bytes32 _key) external; function acceptProposedModules(bytes32[] calldata _keys) external; function requestLockModule(bytes32 _key) external; function cancelLockModule(bytes32 _key) external; function lockModule(bytes32 _key) external; } abstract contract ImmutableModule is ModuleKeys { INexus public immutable nexus; /** * @dev Initialization function for upgradable proxy contracts * @param _nexus Nexus contract address */ constructor(address _nexus) { require(_nexus != address(0), "Nexus address is zero"); nexus = INexus(_nexus); } /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyGovernor() { _onlyGovernor(); _; } function _onlyGovernor() internal view { require(msg.sender == _governor(), "Only governor can execute"); } /** * @dev Modifier to allow function calls only from the Governance. * Governance is either Governor address or Governance address. */ modifier onlyGovernance() { require( msg.sender == _governor() || msg.sender == _governance(), "Only governance can execute" ); _; } /** * @dev Modifier to allow function calls only from the ProxyAdmin. */ modifier onlyProxyAdmin() { require(msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute"); _; } /** * @dev Modifier to allow function calls only from the Manager. */ modifier onlyManager() { require(msg.sender == _manager(), "Only manager can execute"); _; } /** * @dev Returns Governor address from the Nexus * @return Address of Governor Contract */ function _governor() internal view returns (address) { return nexus.governor(); } /** * @dev Returns Governance Module address from the Nexus * @return Address of the Governance (Phase 2) */ function _governance() internal view returns (address) { return nexus.getModule(KEY_GOVERNANCE); } /** * @dev Return Staking Module address from the Nexus * @return Address of the Staking Module contract */ function _staking() internal view returns (address) { return nexus.getModule(KEY_STAKING); } /** * @dev Return ProxyAdmin Module address from the Nexus * @return Address of the ProxyAdmin Module contract */ function _proxyAdmin() internal view returns (address) { return nexus.getModule(KEY_PROXY_ADMIN); } /** * @dev Return MetaToken Module address from the Nexus * @return Address of the MetaToken Module contract */ function _metaToken() internal view returns (address) { return nexus.getModule(KEY_META_TOKEN); } /** * @dev Return OracleHub Module address from the Nexus * @return Address of the OracleHub Module contract */ function _oracleHub() internal view returns (address) { return nexus.getModule(KEY_ORACLE_HUB); } /** * @dev Return Manager Module address from the Nexus * @return Address of the Manager Module contract */ function _manager() internal view returns (address) { return nexus.getModule(KEY_MANAGER); } /** * @dev Return SavingsManager Module address from the Nexus * @return Address of the SavingsManager Module contract */ function _savingsManager() internal view returns (address) { return nexus.getModule(KEY_SAVINGS_MANAGER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _recollateraliser() internal view returns (address) { return nexus.getModule(KEY_RECOLLATERALISER); } } interface IConnector { /** * @notice Deposits the mAsset into the connector * @param _amount Units of mAsset to receive and deposit */ function deposit(uint256 _amount) external; /** * @notice Withdraws a specific amount of mAsset from the connector * @param _amount Units of mAsset to withdraw */ function withdraw(uint256 _amount) external; /** * @notice Withdraws all mAsset from the connector */ function withdrawAll() external; /** * @notice Returns the available balance in the connector. In connections * where there is likely to be an initial dip in value due to conservative * exchange rates (e.g. with Curves `get_virtual_price`), it should return * max(deposited, balance) to avoid temporary negative yield. Any negative yield * should be corrected during a withdrawal or over time. * @return Balance of mAsset in the connector */ function checkBalance() external view returns (uint256); } contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } library StableMath { /** * @dev Scaling unit for use in specific calculations, * where 1 * 10**18, or 1e18 represents a unit '1' */ uint256 private constant FULL_SCALE = 1e18; /** * @dev Token Ratios are used when converting between units of bAsset, mAsset and MTA * Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold) * bAsset ratio unit for use in exact calculations, * where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit */ uint256 private constant RATIO_SCALE = 1e8; /** * @dev Provides an interface to the scaling unit * @return Scaling unit (1e18 or 1 * 10**18) */ function getFullScale() internal pure returns (uint256) { return FULL_SCALE; } /** * @dev Provides an interface to the ratio unit * @return Ratio scale unit (1e8 or 1 * 10**8) */ function getRatioScale() internal pure returns (uint256) { return RATIO_SCALE; } /** * @dev Scales a given integer to the power of the full scale. * @param x Simple uint256 to scale * @return Scaled value a to an exact number */ function scaleInteger(uint256 x) internal pure returns (uint256) { return x * FULL_SCALE; } /*************************************** PRECISE ARITHMETIC ****************************************/ /** * @dev Multiplies two precise units, and then truncates by the full scale * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) { return mulTruncateScale(x, y, FULL_SCALE); } /** * @dev Multiplies two precise units, and then truncates by the given scale. For example, * when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18 * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @param scale Scale unit * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncateScale( uint256 x, uint256 y, uint256 scale ) internal pure returns (uint256) { // e.g. assume scale = fullScale // z = 10e18 * 9e17 = 9e36 // return 9e38 / 1e18 = 9e18 return (x * y) / scale; } /** * @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit, rounded up to the closest base unit. */ function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e17 * 17268172638 = 138145381104e17 uint256 scaled = x * y; // e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17 uint256 ceil = scaled + FULL_SCALE - 1; // e.g. 13814538111.399...e18 / 1e18 = 13814538111 return ceil / FULL_SCALE; } /** * @dev Precisely divides two units, by first scaling the left hand operand. Useful * for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) * @param x Left hand input to division * @param y Right hand input to division * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e18 * 1e18 = 8e36 // e.g. 8e36 / 10e18 = 8e17 return (x * FULL_SCALE) / y; } /*************************************** RATIO FUNCS ****************************************/ /** * @dev Multiplies and truncates a token ratio, essentially flooring the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand operand to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return c Result after multiplying the two inputs and then dividing by the ratio scale */ function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) { return mulTruncateScale(x, ratio, RATIO_SCALE); } /** * @dev Multiplies and truncates a token ratio, rounding up the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand input to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return Result after multiplying the two inputs and then dividing by the shared * ratio scale, rounded up to the closest base unit. */ function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) { // e.g. How much mAsset should I burn for this bAsset (x)? // 1e18 * 1e8 = 1e26 uint256 scaled = x * ratio; // 1e26 + 9.99e7 = 100..00.999e8 uint256 ceil = scaled + RATIO_SCALE - 1; // return 100..00.999e8 / 1e8 = 1e18 return ceil / RATIO_SCALE; } /** * @dev Precisely divides two ratioed units, by first scaling the left hand operand * i.e. How much bAsset is this mAsset worth? * @param x Left hand operand in division * @param ratio bAsset ratio * @return c Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) { // e.g. 1e14 * 1e8 = 1e22 // return 1e22 / 1e12 = 1e10 return (x * RATIO_SCALE) / ratio; } /*************************************** HELPERS ****************************************/ /** * @dev Calculates minimum of two numbers * @param x Left hand input * @param y Right hand input * @return Minimum of the two inputs */ function min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } /** * @dev Calculated maximum of two numbers * @param x Left hand input * @param y Right hand input * @return Maximum of the two inputs */ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? x : y; } /** * @dev Clamps a value to an upper bound * @param x Left hand input * @param upperBound Maximum possible value to return * @return Input x clamped to a maximum value, upperBound */ function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) { return x > upperBound ? upperBound : x; } } /** * @title SavingsContract * @author mStable * @notice Savings contract uses the ever increasing "exchangeRate" to increase * the value of the Savers "credits" (ERC20) relative to the amount of additional * underlying collateral that has been deposited into this contract ("interest") * @dev VERSION: 2.0 * DATE: 2020-12-15 */ contract SavingsContract is ISavingsContractV2, Initializable, InitializableToken, ImmutableModule { using StableMath for uint256; // Core events for depositing and withdrawing event ExchangeRateUpdated(uint256 newExchangeRate, uint256 interestCollected); event SavingsDeposited(address indexed saver, uint256 savingsDeposited, uint256 creditsIssued); event CreditsRedeemed( address indexed redeemer, uint256 creditsRedeemed, uint256 savingsCredited ); event AutomaticInterestCollectionSwitched(bool automationEnabled); // Connector poking event PokerUpdated(address poker); event FractionUpdated(uint256 fraction); event ConnectorUpdated(address connector); event EmergencyUpdate(); event Poked(uint256 oldBalance, uint256 newBalance, uint256 interestDetected); event PokedRaw(); // Rate between 'savings credits' and underlying // e.g. 1 credit (1e17) mulTruncate(exchangeRate) = underlying, starts at 10:1 // exchangeRate increases over time uint256 private constant startingRate = 1e17; uint256 public override exchangeRate; // Underlying asset is underlying IERC20 public immutable underlying; bool private automateInterestCollection; // Yield // Poker is responsible for depositing/withdrawing from connector address public poker; // Last time a poke was made uint256 public lastPoke; // Last known balance of the connector uint256 public lastBalance; // Fraction of capital assigned to the connector (100% = 1e18) uint256 public fraction; // Address of the current connector (all IConnectors are mStable validated) IConnector public connector; // How often do we allow pokes uint256 private constant POKE_CADENCE = 4 hours; // Max APY generated on the capital in the connector uint256 private constant MAX_APY = 4e18; uint256 private constant SECONDS_IN_YEAR = 365 days; constructor(address _nexus, address _underlying) ImmutableModule(_nexus) { require(address(_underlying) != address(0), "mAsset address is zero"); underlying = IERC20(_underlying); } // Add these constants to bytecode at deploytime function initialize( address _poker, string calldata _nameArg, string calldata _symbolArg ) external initializer { InitializableToken._initialize(_nameArg, _symbolArg); require(_poker != address(0), "Invalid poker address"); poker = _poker; fraction = 2e17; automateInterestCollection = true; exchangeRate = startingRate; } /** @dev Only the savings managaer (pulled from Nexus) can execute this */ modifier onlySavingsManager() { require(msg.sender == _savingsManager(), "Only savings manager can execute"); _; } /*************************************** VIEW - E ****************************************/ /** * @dev Returns the underlying balance of a given user * @param _user Address of the user to check * @return balance Units of underlying owned by the user */ function balanceOfUnderlying(address _user) external view override returns (uint256 balance) { (balance, ) = _creditsToUnderlying(balanceOf(_user)); } /** * @dev Converts a given underlying amount into credits * @param _underlying Units of underlying * @return credits Credit units (a.k.a imUSD) */ function underlyingToCredits(uint256 _underlying) external view override returns (uint256 credits) { (credits, ) = _underlyingToCredits(_underlying); } /** * @dev Converts a given credit amount into underlying * @param _credits Units of credits * @return amount Corresponding underlying amount */ function creditsToUnderlying(uint256 _credits) external view override returns (uint256 amount) { (amount, ) = _creditsToUnderlying(_credits); } // Deprecated in favour of `balanceOf(address)` // Maintained for backwards compatibility // Returns the credit balance of a given user function creditBalances(address _user) external view override returns (uint256) { return balanceOf(_user); } /*************************************** INTEREST ****************************************/ /** * @dev Deposit interest (add to savings) and update exchange rate of contract. * Exchange rate is calculated as the ratio between new savings q and credits: * exchange rate = savings / credits * * @param _amount Units of underlying to add to the savings vault */ function depositInterest(uint256 _amount) external override onlySavingsManager { require(_amount > 0, "Must deposit something"); // Transfer the interest from sender to here require(underlying.transferFrom(msg.sender, address(this), _amount), "Must receive tokens"); // Calc new exchange rate, protect against initialisation case uint256 totalCredits = totalSupply(); if (totalCredits > 0) { // new exchange rate is relationship between _totalCredits & totalSavings // _totalCredits * exchangeRate = totalSavings // exchangeRate = totalSavings/_totalCredits (uint256 totalCollat, ) = _creditsToUnderlying(totalCredits); uint256 newExchangeRate = _calcExchangeRate(totalCollat + _amount, totalCredits); exchangeRate = newExchangeRate; emit ExchangeRateUpdated(newExchangeRate, _amount); } } /** @dev Enable or disable the automation of fee collection during deposit process */ function automateInterestCollectionFlag(bool _enabled) external onlyGovernor { automateInterestCollection = _enabled; emit AutomaticInterestCollectionSwitched(_enabled); } /*************************************** DEPOSIT ****************************************/ /** * @dev During a migration period, allow savers to deposit underlying here before the interest has been redirected * @param _underlying Units of underlying to deposit into savings vault * @param _beneficiary Immediately transfer the imUSD token to this beneficiary address * @return creditsIssued Units of credits (imUSD) issued */ function preDeposit(uint256 _underlying, address _beneficiary) external returns (uint256 creditsIssued) { require(exchangeRate == startingRate, "Can only use this method before streaming begins"); return _deposit(_underlying, _beneficiary, false); } /** * @dev Deposit the senders savings to the vault, and credit them internally with "credits". * Credit amount is calculated as a ratio of deposit amount and exchange rate: * credits = underlying / exchangeRate * We will first update the internal exchange rate by collecting any interest generated on the underlying. * @param _underlying Units of underlying to deposit into savings vault * @return creditsIssued Units of credits (imUSD) issued */ function depositSavings(uint256 _underlying) external override returns (uint256 creditsIssued) { return _deposit(_underlying, msg.sender, true); } /** * @dev Deposit the senders savings to the vault, and credit them internally with "credits". * Credit amount is calculated as a ratio of deposit amount and exchange rate: * credits = underlying / exchangeRate * We will first update the internal exchange rate by collecting any interest generated on the underlying. * @param _underlying Units of underlying to deposit into savings vault * @param _beneficiary Immediately transfer the imUSD token to this beneficiary address * @return creditsIssued Units of credits (imUSD) issued */ function depositSavings(uint256 _underlying, address _beneficiary) external override returns (uint256 creditsIssued) { return _deposit(_underlying, _beneficiary, true); } /** * @dev Internally deposit the _underlying from the sender and credit the beneficiary with new imUSD */ function _deposit( uint256 _underlying, address _beneficiary, bool _collectInterest ) internal returns (uint256 creditsIssued) { require(_underlying > 0, "Must deposit something"); require(_beneficiary != address(0), "Invalid beneficiary address"); // Collect recent interest generated by basket and update exchange rate IERC20 mAsset = underlying; if (_collectInterest) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(mAsset)); } // Transfer tokens from sender to here require(mAsset.transferFrom(msg.sender, address(this), _underlying), "Must receive tokens"); // Calc how many credits they receive based on currentRatio (creditsIssued, ) = _underlyingToCredits(_underlying); // add credits to ERC20 balances _mint(_beneficiary, creditsIssued); emit SavingsDeposited(_beneficiary, _underlying, creditsIssued); } /*************************************** REDEEM ****************************************/ // Deprecated in favour of redeemCredits // Maintaining backwards compatibility, this fn minimics the old redeem fn, in which // credits are redeemed but the interest from the underlying is not collected. function redeem(uint256 _credits) external override returns (uint256 massetReturned) { require(_credits > 0, "Must withdraw something"); (, uint256 payout) = _redeem(_credits, true); // Collect recent interest generated by basket and update exchange rate if (automateInterestCollection) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying)); } return payout; } /** * @dev Redeem specific number of the senders "credits" in exchange for underlying. * Payout amount is calculated as a ratio of credits and exchange rate: * payout = credits * exchangeRate * @param _credits Amount of credits to redeem * @return massetReturned Units of underlying mAsset paid out */ function redeemCredits(uint256 _credits) external override returns (uint256 massetReturned) { require(_credits > 0, "Must withdraw something"); // Collect recent interest generated by basket and update exchange rate if (automateInterestCollection) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying)); } (, uint256 payout) = _redeem(_credits, true); return payout; } /** * @dev Redeem credits into a specific amount of underlying. * Credits needed to burn is calculated using: * credits = underlying / exchangeRate * @param _underlying Amount of underlying to redeem * @return creditsBurned Units of credits burned from sender */ function redeemUnderlying(uint256 _underlying) external override returns (uint256 creditsBurned) { require(_underlying > 0, "Must withdraw something"); // Collect recent interest generated by basket and update exchange rate if (automateInterestCollection) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying)); } // Ensure that the payout was sufficient (uint256 credits, uint256 massetReturned) = _redeem(_underlying, false); require(massetReturned == _underlying, "Invalid output"); return credits; } /** * @dev Internally burn the credits and send the underlying to msg.sender */ function _redeem(uint256 _amt, bool _isCreditAmt) internal returns (uint256 creditsBurned, uint256 massetReturned) { // Centralise credit <> underlying calcs and minimise SLOAD count uint256 credits_; uint256 underlying_; uint256 exchangeRate_; // If the input is a credit amt, then calculate underlying payout and cache the exchangeRate if (_isCreditAmt) { credits_ = _amt; (underlying_, exchangeRate_) = _creditsToUnderlying(_amt); } // If the input is in underlying, then calculate credits needed to burn else { underlying_ = _amt; (credits_, exchangeRate_) = _underlyingToCredits(_amt); } // Burn required credits from the sender FIRST _burn(msg.sender, credits_); // Transfer tokens from here to sender require(underlying.transfer(msg.sender, underlying_), "Must send tokens"); // If this withdrawal pushes the portion of stored collateral in the `connector` over a certain // threshold (fraction + 20%), then this should trigger a _poke on the connector. This is to avoid // a situation in which there is a rush on withdrawals for some reason, causing the connector // balance to go up and thus having too large an exposure. CachedData memory cachedData = _cacheData(); ConnectorStatus memory status = _getConnectorStatus(cachedData, exchangeRate_); if (status.inConnector > status.limit) { _poke(cachedData, false); } emit CreditsRedeemed(msg.sender, credits_, underlying_); return (credits_, underlying_); } struct ConnectorStatus { // Limit is the max amount of units allowed in the connector uint256 limit; // Derived balance of the connector uint256 inConnector; } /** * @dev Derives the units of collateral held in the connector * @param _data Struct containing data on balances * @param _exchangeRate Current system exchange rate * @return status Contains max amount of assets allowed in connector */ function _getConnectorStatus(CachedData memory _data, uint256 _exchangeRate) internal pure returns (ConnectorStatus memory) { // Total units of underlying collateralised uint256 totalCollat = _data.totalCredits.mulTruncate(_exchangeRate); // Max amount of underlying that can be held in the connector uint256 limit = totalCollat.mulTruncate(_data.fraction + 2e17); // Derives amount of underlying present in the connector uint256 inConnector = _data.rawBalance >= totalCollat ? 0 : totalCollat - _data.rawBalance; return ConnectorStatus(limit, inConnector); } /*************************************** YIELD - E ****************************************/ /** @dev Modifier allowing only the designated poker to execute the fn */ modifier onlyPoker() { require(msg.sender == poker, "Only poker can execute"); _; } /** * @dev External poke function allows for the redistribution of collateral between here and the * current connector, setting the ratio back to the defined optimal. */ function poke() external onlyPoker { CachedData memory cachedData = _cacheData(); _poke(cachedData, false); } /** * @dev Governance action to set the address of a new poker * @param _newPoker Address of the new poker */ function setPoker(address _newPoker) external onlyGovernor { require(_newPoker != address(0) && _newPoker != poker, "Invalid poker"); poker = _newPoker; emit PokerUpdated(_newPoker); } /** * @dev Governance action to set the percentage of assets that should be held * in the connector. * @param _fraction Percentage of assets that should be held there (where 20% == 2e17) */ function setFraction(uint256 _fraction) external onlyGovernor { require(_fraction <= 5e17, "Fraction must be <= 50%"); fraction = _fraction; CachedData memory cachedData = _cacheData(); _poke(cachedData, true); emit FractionUpdated(_fraction); } /** * @dev Governance action to set the address of a new connector, and move funds (if any) across. * @param _newConnector Address of the new connector */ function setConnector(address _newConnector) external onlyGovernor { // Withdraw all from previous by setting target = 0 CachedData memory cachedData = _cacheData(); cachedData.fraction = 0; _poke(cachedData, true); // Set new connector CachedData memory cachedDataNew = _cacheData(); connector = IConnector(_newConnector); _poke(cachedDataNew, true); emit ConnectorUpdated(_newConnector); } /** * @dev Governance action to perform an emergency withdraw of the assets in the connector, * should it be the case that some or all of the liquidity is trapped in. This causes the total * collateral in the system to go down, causing a hard refresh. */ function emergencyWithdraw(uint256 _withdrawAmount) external onlyGovernor { // withdraw _withdrawAmount from connection connector.withdraw(_withdrawAmount); // reset the connector connector = IConnector(address(0)); emit ConnectorUpdated(address(0)); // set fraction to 0 fraction = 0; emit FractionUpdated(0); // check total collateralisation of credits CachedData memory data = _cacheData(); // use rawBalance as the remaining liquidity in the connector is now written off _refreshExchangeRate(data.rawBalance, data.totalCredits, true); emit EmergencyUpdate(); } /*************************************** YIELD - I ****************************************/ /** @dev Internal poke function to keep the balance between connector and raw balance healthy */ function _poke(CachedData memory _data, bool _ignoreCadence) internal { require(_data.totalCredits > 0, "Must have something to poke"); // 1. Verify that poke cadence is valid, unless this is a manual action by governance uint256 currentTime = uint256(block.timestamp); uint256 timeSinceLastPoke = currentTime - lastPoke; require(_ignoreCadence || timeSinceLastPoke > POKE_CADENCE, "Not enough time elapsed"); lastPoke = currentTime; // If there is a connector, check the balance and settle to the specified fraction % IConnector connector_ = connector; if (address(connector_) != address(0)) { // 2. Check and verify new connector balance uint256 lastBalance_ = lastBalance; uint256 connectorBalance = connector_.checkBalance(); // Always expect the collateral in the connector to increase in value require(connectorBalance >= lastBalance_, "Invalid yield"); if (connectorBalance > 0) { // Validate the collection by ensuring that the APY is not ridiculous _validateCollection( connectorBalance, connectorBalance - lastBalance_, timeSinceLastPoke ); } // 3. Level the assets to Fraction (connector) & 100-fraction (raw) uint256 sum = _data.rawBalance + connectorBalance; uint256 ideal = sum.mulTruncate(_data.fraction); // If there is not enough mAsset in the connector, then deposit if (ideal > connectorBalance) { uint256 deposit = ideal - connectorBalance; underlying.approve(address(connector_), deposit); connector_.deposit(deposit); } // Else withdraw, if there is too much mAsset in the connector else if (connectorBalance > ideal) { // If fraction == 0, then withdraw everything if (ideal == 0) { connector_.withdrawAll(); sum = IERC20(underlying).balanceOf(address(this)); } else { connector_.withdraw(connectorBalance - ideal); } } // Else ideal == connectorBalance (e.g. 0), do nothing require(connector_.checkBalance() >= ideal, "Enforce system invariant"); // 4i. Refresh exchange rate and emit event lastBalance = ideal; _refreshExchangeRate(sum, _data.totalCredits, false); emit Poked(lastBalance_, ideal, connectorBalance - lastBalance_); } else { // 4ii. Refresh exchange rate and emit event lastBalance = 0; _refreshExchangeRate(_data.rawBalance, _data.totalCredits, false); emit PokedRaw(); } } /** * @dev Internal fn to refresh the exchange rate, based on the sum of collateral and the number of credits * @param _realSum Sum of collateral held by the contract * @param _totalCredits Total number of credits in the system * @param _ignoreValidation This is for use in the emergency situation, and ignores a decreasing exchangeRate */ function _refreshExchangeRate( uint256 _realSum, uint256 _totalCredits, bool _ignoreValidation ) internal { // Based on the current exchange rate, how much underlying is collateralised? (uint256 totalCredited, ) = _creditsToUnderlying(_totalCredits); // Require the amount of capital held to be greater than the previously credited units require(_ignoreValidation || _realSum >= totalCredited, "ExchangeRate must increase"); // Work out the new exchange rate based on the current capital uint256 newExchangeRate = _calcExchangeRate(_realSum, _totalCredits); exchangeRate = newExchangeRate; emit ExchangeRateUpdated( newExchangeRate, _realSum > totalCredited ? _realSum - totalCredited : 0 ); } /** * FORKED DIRECTLY FROM SAVINGSMANAGER.sol * --------------------------------------- * @dev Validates that an interest collection does not exceed a maximum APY. If last collection * was under 30 mins ago, simply check it does not exceed 10bps * @param _newBalance New balance of the underlying * @param _interest Increase in total supply since last collection * @param _timeSinceLastCollection Seconds since last collection */ function _validateCollection( uint256 _newBalance, uint256 _interest, uint256 _timeSinceLastCollection ) internal pure returns (uint256 extrapolatedAPY) { // Protect against division by 0 uint256 protectedTime = StableMath.max(1, _timeSinceLastCollection); uint256 oldSupply = _newBalance - _interest; uint256 percentageIncrease = _interest.divPrecisely(oldSupply); uint256 yearsSinceLastCollection = protectedTime.divPrecisely(SECONDS_IN_YEAR); extrapolatedAPY = percentageIncrease.divPrecisely(yearsSinceLastCollection); if (protectedTime > 30 minutes) { require(extrapolatedAPY < MAX_APY, "Interest protected from inflating past maxAPY"); } else { require(percentageIncrease < 1e15, "Interest protected from inflating past 10 Bps"); } } /*************************************** VIEW - I ****************************************/ struct CachedData { // SLOAD from 'fraction' uint256 fraction; // ERC20 balance of underlying, held by this contract // underlying.balanceOf(address(this)) uint256 rawBalance; // totalSupply() uint256 totalCredits; } /** * @dev Retrieves generic data to avoid duplicate SLOADs */ function _cacheData() internal view returns (CachedData memory) { uint256 balance = underlying.balanceOf(address(this)); return CachedData(fraction, balance, totalSupply()); } /** * @dev Converts masset amount into credits based on exchange rate * c = (masset / exchangeRate) + 1 */ function _underlyingToCredits(uint256 _underlying) internal view returns (uint256 credits, uint256 exchangeRate_) { // e.g. (1e20 * 1e18) / 1e18 = 1e20 // e.g. (1e20 * 1e18) / 14e17 = 7.1429e19 // e.g. 1 * 1e18 / 1e17 + 1 = 11 => 11 * 1e17 / 1e18 = 1.1e18 / 1e18 = 1 exchangeRate_ = exchangeRate; credits = _underlying.divPrecisely(exchangeRate_) + 1; } /** * @dev Works out a new exchange rate, given an amount of collateral and total credits * e = underlying / (credits-1) */ function _calcExchangeRate(uint256 _totalCollateral, uint256 _totalCredits) internal pure returns (uint256 _exchangeRate) { _exchangeRate = _totalCollateral.divPrecisely(_totalCredits - 1); } /** * @dev Converts credit amount into masset based on exchange rate * m = credits * exchangeRate */ function _creditsToUnderlying(uint256 _credits) internal view returns (uint256 underlyingAmount, uint256 exchangeRate_) { // e.g. (1e20 * 1e18) / 1e18 = 1e20 // e.g. (1e20 * 14e17) / 1e18 = 1.4e20 exchangeRate_ = exchangeRate; underlyingAmount = _credits.mulTruncate(exchangeRate_); } }
Internally deposit the _underlying from the sender and credit the beneficiary with new imUSD/ Collect recent interest generated by basket and update exchange rate
function _deposit( uint256 _underlying, address _beneficiary, bool _collectInterest ) internal returns (uint256 creditsIssued) { require(_underlying > 0, "Must deposit something"); require(_beneficiary != address(0), "Invalid beneficiary address"); IERC20 mAsset = underlying; if (_collectInterest) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(mAsset)); } emit SavingsDeposited(_beneficiary, _underlying, creditsIssued); }
15,005,556
// SPDX-License-Identifier: MIT pragma solidity 0.6.2; import "./access/OwnableUpgradeable.sol"; import "./math/MathUpgradeable.sol"; import "./math/SafeMathUpgradeable.sol"; import "./interfaces/IERC20Upgradeable.sol"; import "./interfaces/IStakingPoolRewarder.sol"; import "./libraries/TransferHelper.sol"; /** * @title StakingPoolRewarder * * @dev An upgradeable rewarder contract for releasing Lithium tokens based on * schedule. */ contract StakingPoolRewarder is OwnableUpgradeable, IStakingPoolRewarder { using SafeMathUpgradeable for uint256; event VestingScheduleAdded(address indexed user, uint256 amount, uint256 startTime, uint256 endTime, uint256 step); event VestingSettingChanged(uint8 percentageToVestingSchedule, uint256 claimStartTime, uint256 claimDuration, uint256 claimStep); event TokenVested(address indexed user, uint256 poolId, uint256 amount); event MoveVestingScheduleEarlier(uint256 poolId, address indexed user, uint32 startTime, uint32 endTime, uint256 duration); event RewardDispatcherUpdated(address indexed dispatcher); /** * @param amount Total amount to be vested over the complete period * @param startTime Unix timestamp in seconds for the period start time * @param endTime Unix timestamp in seconds for the period end time * @param step Interval in seconds at which vestable amounts are accumulated * @param lastClaimTime Unix timestamp in seconds for the last claim time */ struct VestingSchedule { uint128 amount; uint32 startTime; uint32 endTime; uint32 step; uint32 lastClaimTime; } mapping(address => mapping(uint256 => VestingSchedule)) public vestingSchedules; address public stakingPools; address public rewardToken; address public rewardDispatcher; uint8 public percentageToVestingSchedule; uint256 public claimStartTime; uint256 public claimDuration; uint256 public claimStep; bool private locked; modifier blockReentrancy { require(!locked, "Reentrancy is blocked"); locked = true; _; locked = false; } function __StakingPoolRewarder_init( address _stakingPools, address _rewardToken, address _rewardDispatcher, uint8 _percentageToVestingSchedule, uint256 _claimStartTime, uint256 _claimDuration, uint256 _claimStep ) public initializer { __Ownable_init(); require(_stakingPools != address(0), "StakingPoolRewarder: stakingPools zero address"); require(_rewardToken != address(0), "StakingPoolRewarder: rewardToken zero address"); require(_rewardDispatcher != address(0), "StakingPoolRewarder: rewardDispatcher zero address"); require(_percentageToVestingSchedule <= 100, "StakingPoolRewarder: invalid percentageToVestingSchedule value"); require(_claimStep > 0 && _claimDuration % _claimStep == 0, "StakingPoolRewarder: invalid step"); stakingPools = _stakingPools; rewardToken = _rewardToken; rewardDispatcher = _rewardDispatcher; percentageToVestingSchedule = _percentageToVestingSchedule; claimStartTime = _claimStartTime; claimDuration = _claimDuration; claimStep = _claimStep; } modifier onlyStakingPools() { require(stakingPools == msg.sender, "StakingPoolRewarder: only stakingPool can call"); _; } function updateVestingSetting( uint8 _percentageToVestingSchedule, uint256 _claimStartTime, uint256 _claimDuration, uint256 _claimStep ) external onlyOwner { require(_percentageToVestingSchedule <= 100, "StakingPoolRewarder: invalid percentageToVestingSchedule value"); require(_claimStep > 0 && _claimDuration % _claimStep == 0, "StakingPoolRewarder: invalid step"); percentageToVestingSchedule = _percentageToVestingSchedule; claimStartTime = _claimStartTime; claimDuration = _claimDuration; claimStep = _claimStep; emit VestingSettingChanged(_percentageToVestingSchedule, _claimStartTime, _claimDuration, _claimStep); } function moveVestingScheduleEarlier(uint256 poolId, address user, uint256 duration) external onlyOwner { require(user != address(0), "StakingPoolRewarder: zero address"); require(vestingSchedules[user][poolId].amount != 0, "StakingPoolRewarder: Vesting schedule not exist" ); VestingSchedule memory vestingSchedule = vestingSchedules[user][poolId]; vestingSchedules[user][poolId] = VestingSchedule({ amount : vestingSchedule.amount, startTime : uint32(uint256(vestingSchedule.startTime).sub(duration)), endTime : uint32(uint256(vestingSchedule.endTime).sub(duration)), step : vestingSchedule.step, lastClaimTime : uint32(uint256(vestingSchedule.lastClaimTime).sub(duration)) }); emit MoveVestingScheduleEarlier(poolId, user, vestingSchedules[user][poolId].startTime, vestingSchedules[user][poolId].endTime, duration); } function setRewardDispatcher(address _rewardDispatcher) external onlyOwner { require(_rewardDispatcher != address(0), "StakingPoolRewarder: zero address!"); rewardDispatcher = _rewardDispatcher; emit RewardDispatcherUpdated(_rewardDispatcher); } function updateVestingSchedule( address user, uint256 poolId, uint256 amount, uint256 startTime, uint256 endTime, uint256 step ) private { require(user != address(0), "StakingPoolRewarder: zero address"); require(amount > 0, "StakingPoolRewarder: zero amount"); require(startTime < endTime, "StakingPoolRewarder: invalid time range"); require(step > 0 && endTime.sub(startTime) % step == 0, "StakingPoolRewarder: invalid step"); // Overflow checks require(uint256(uint128(amount)) == amount, "StakingPoolRewarder: amount overflow"); require(uint256(uint32(startTime)) == startTime, "StakingPoolRewarder: startTime overflow"); require(uint256(uint32(endTime)) == endTime, "StakingPoolRewarder: endTime overflow"); require(uint256(uint32(step)) == step, "StakingPoolRewarder: step overflow"); vestingSchedules[user][poolId] = VestingSchedule({ amount : uint128(amount), startTime : uint32(startTime), endTime : uint32(endTime), step : uint32(step), lastClaimTime : uint32(startTime) }); emit VestingScheduleAdded(user, amount, startTime, endTime, step); } function calculateWithdrawableFromVesting(address user, uint256 poolId) external view returns (uint256) { (uint256 withdrawable, ,) = _calculateWithdrawableFromVesting(user, poolId); return withdrawable; } function _calculateWithdrawableFromVesting(address user, uint256 poolId) private view returns ( uint256 amount, uint256 newClaimTime, bool allVested ){ VestingSchedule memory vestingSchedule = vestingSchedules[user][poolId]; if (vestingSchedule.amount == 0) return (0, 0, false); if (block.timestamp < uint256(vestingSchedule.startTime)) return (0, 0, false); uint256 currentStepTime = MathUpgradeable.min( block.timestamp .sub(uint256(vestingSchedule.startTime)) .div(uint256(vestingSchedule.step)) .mul(uint256(vestingSchedule.step)) .add(uint256(vestingSchedule.startTime)), uint256(vestingSchedule.endTime) ); if (currentStepTime <= uint256(vestingSchedule.lastClaimTime)) return (0, 0, false); uint256 totalSteps = uint256(vestingSchedule.endTime).sub(uint256(vestingSchedule.startTime)).div(vestingSchedule.step); if (currentStepTime == uint256(vestingSchedule.endTime)) { // All vested uint256 stepsVested = uint256(vestingSchedule.lastClaimTime).sub(uint256(vestingSchedule.startTime)).div(vestingSchedule.step); uint256 amountToVest = uint256(vestingSchedule.amount).sub(uint256(vestingSchedule.amount).div(totalSteps).mul(stepsVested)); return (amountToVest, currentStepTime, true); } else { // Partially vested uint256 stepsToVest = currentStepTime.sub(uint256(vestingSchedule.lastClaimTime)).div(vestingSchedule.step); uint256 amountToVest = uint256(vestingSchedule.amount).div(totalSteps).mul(stepsToVest); return (amountToVest, currentStepTime, false); } } function _calculateUnvestedAmount(address user, uint256 poolId, uint256 stepTime) private view returns (uint256) { if (vestingSchedules[user][poolId].amount == 0) return 0; uint256 totalSteps = uint256(vestingSchedules[user][poolId].endTime) .sub(uint256(vestingSchedules[user][poolId].startTime)) .div(vestingSchedules[user][poolId].step); uint256 stepsVested = stepTime .sub(uint256(vestingSchedules[user][poolId].startTime)) .div(vestingSchedules[user][poolId].step); return uint256(vestingSchedules[user][poolId].amount) .sub(uint256(vestingSchedules[user][poolId].amount) .mul(stepsVested) .div(totalSteps)); } function onReward( uint256 poolId, address user, uint256 amount ) onlyStakingPools external override { _onReward(poolId, user, amount); } function _onReward(uint256 poolId, address user, uint256 amount) private blockReentrancy { require(user != address(0), "StakingPoolRewarder: zero address"); uint256 newUnvestedAmount = 0; uint256 newVestedAmount = 0; if (amount > 0) { newUnvestedAmount = amount.mul(uint256(percentageToVestingSchedule)).div(100); newVestedAmount = amount.sub(newUnvestedAmount); } if (newUnvestedAmount > 0) { require(vestingSchedules[user][poolId].amount == 0, "StakingPoolRewarder: vesting schedule already exists"); updateVestingSchedule(user, poolId, newUnvestedAmount, claimStartTime, claimStartTime.add(claimDuration), claimStep); } (uint256 lastVestedAmount,uint256 newClaimTime, bool allVested) = _calculateWithdrawableFromVesting(user, poolId); if (lastVestedAmount > 0) { if (allVested) { // Remove storage slot to save gas delete vestingSchedules[user][poolId]; } else { vestingSchedules[user][poolId].lastClaimTime = uint32(newClaimTime); } } uint256 totalVested = lastVestedAmount.add(newVestedAmount); require(totalVested > 0, "StakingPoolRewarder: zero totalVested"); TransferHelper.safeTransferFrom( rewardToken, rewardDispatcher, user, totalVested ); emit TokenVested(user, poolId, totalVested); } // Add an external function to enable user claim vested reward when reward amount in staking is 0 function claimVestedReward(uint256 poolId) external { require(poolId > 0, "StakingPoolRewarder: poolId is 0"); _onReward(poolId, msg.sender, 0); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.2; 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.2; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.2; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.2; /** * @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.2; interface IStakingPoolRewarder { function onReward( uint256 poolId, address user, uint256 amount ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.2; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.2; 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.6.2; 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; /** * @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); } } } }
Remove storage slot to save gas
function _onReward(uint256 poolId, address user, uint256 amount) private blockReentrancy { require(user != address(0), "StakingPoolRewarder: zero address"); uint256 newUnvestedAmount = 0; uint256 newVestedAmount = 0; if (amount > 0) { newUnvestedAmount = amount.mul(uint256(percentageToVestingSchedule)).div(100); newVestedAmount = amount.sub(newUnvestedAmount); } if (newUnvestedAmount > 0) { require(vestingSchedules[user][poolId].amount == 0, "StakingPoolRewarder: vesting schedule already exists"); updateVestingSchedule(user, poolId, newUnvestedAmount, claimStartTime, claimStartTime.add(claimDuration), claimStep); } (uint256 lastVestedAmount,uint256 newClaimTime, bool allVested) = _calculateWithdrawableFromVesting(user, poolId); if (lastVestedAmount > 0) { if (allVested) { delete vestingSchedules[user][poolId]; vestingSchedules[user][poolId].lastClaimTime = uint32(newClaimTime); } } uint256 totalVested = lastVestedAmount.add(newVestedAmount); require(totalVested > 0, "StakingPoolRewarder: zero totalVested"); TransferHelper.safeTransferFrom( rewardToken, rewardDispatcher, user, totalVested ); emit TokenVested(user, poolId, totalVested); }
1,675,328
pragma solidity ^0.6.0 <0.7.0; import "./MerkleTreeGenIndex.sol"; /* In this example we are spliting the processing of one tree in many branches. Each leaf is a tree by itself Important point: We can imagine a very large tree of trees, but in the end is the same as a unique tree. This code is just to give an idea. */ contract ExampleForest { bytes32 public root; bytes32[] public subtrees; MerkleTreeGenIndex.Data ram; constructor(bytes32 _root) public { root = _root; } //Call this function for each subtree you want to validate function calculateRootOfSubTree(bytes32[] memory _nodes, uint256[] memory _GIOP) public { subtrees[subtrees.length - 1] = callLibraryToCalculateRoot(_nodes, _GIOP); } //Here we are assuming that the Principal tree is bigger than the subtrees saved in this contract, and the user give the complete GIOP array function calculateRootOfPrincipalTree(bytes32[] memory _nodes, uint256[] memory _GIOP) public returns(bool) { bytes32[] memory _orderNodes; for(uint256 i = 0; i < subtrees.length; i = i + 2) { //each leaf as a sibling _orderNodes[i] = subtrees[i]; _orderNodes[i+1] = subtrees[i+1]; } //lets add a BLANK POINT _orderNodes[_orderNodes.length] = keccak256(abi.encodePacked(uint256(0))); //let skip the leaves GIOP uint256 _skip = (subtrees.length / 2) + 1; // +1 because of BLANK_POINT uint256 j; //lets add to the array the nodes info for(uint256 i = _skip; i < _GIOP.length; i++) { _orderNodes[i] = _nodes[j]; j += 1; } return root == callLibraryToCalculateRoot(_orderNodes, _GIOP); } //Note that we make a call with the library always the same way function callLibraryToCalculateRoot(bytes32[] memory _nodes, uint256[] memory _GIOP) internal returns(bytes32){ return MerkleTreeGenIndex.getRoot(ram, _nodes, _GIOP); } }
Here we are assuming that the Principal tree is bigger than the subtrees saved in this contract, and the user give the complete GIOP arrayeach leaf as a siblinglets add to the array the nodes info
function calculateRootOfPrincipalTree(bytes32[] memory _nodes, uint256[] memory _GIOP) public returns(bool) { bytes32[] memory _orderNodes; for(uint256 i = 0; i < subtrees.length; i = i + 2) { _orderNodes[i] = subtrees[i]; _orderNodes[i+1] = subtrees[i+1]; } for(uint256 i = _skip; i < _GIOP.length; i++) { _orderNodes[i] = _nodes[j]; j += 1; } return root == callLibraryToCalculateRoot(_orderNodes, _GIOP); }
7,221,692
./full_match/43113/0x2BA5B51742125Ca75BcfA22E32456BdE1488977E/sources/apps/avai/src/contracts/PodLeader.sol
Add a new reward token to the pool Can only be called by the owner. DO NOT add the same token more than once. Rewards will be messed up if you do. allocPoint Number of allocation points to allot to this token/pool token The token that will be staked for rewards withUpdate if specified, update all pools before adding new pool _depositFeeBp If true, users get voting power for deposits/
function add( uint256 allocPoint, address token, bool withUpdate, uint16 _depositFeeBp ) external onlyOwner { if (withUpdate) { massUpdatePools(); } uint256 rewardStartTimestamp = block.timestamp > startTimestamp ? block.timestamp : startTimestamp; if (totalAllocPoint == 0) { _setRewardsEndTimestamp(); } totalAllocPoint = totalAllocPoint + allocPoint; poolInfo.push( PoolInfo({ token: IERC20(token), allocPoint: allocPoint, lastRewardTimestamp: rewardStartTimestamp, accRewardsPerShare: 0, totalStaked: 0, depositFeeBP: _depositFeeBp }) ); emit PoolAdded( poolInfo.length - 1, token, allocPoint, totalAllocPoint, rewardStartTimestamp, _depositFeeBp ); }
7,175,466
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ERC20.sol"; import "./SafeMath.sol"; import "./ERC20Burnable.sol"; contract HOPE is ERC20, ERC20Burnable { using SafeMath for uint256; address payable public Fundcontract; //scam alert, read the contract to be sure, could be exit scam uint public bid; uint public ask; uint public volume; uint public totalFeesCollected; uint public feesLeftInContract; uint public claimedFees; bool public canInvest; bool public minFeeActive; uint public fee; uint public fundsCollectedTotal; uint public fundsRepaidTotal; uint public FundsLeftInContract; //there could be other funds in the contract, like fees, this should be discarded for realValue; uint public indexOfOrders; uint public burnedToFund; uint public realBalance =payable(address(this)).balance; address payable public thisContract = payable(address(this)); struct order { uint orderNumber; uint timeStamp; uint amount; bool buy; uint price; address participant; uint eth; uint fundingTokens; } mapping (address => bool) public owners; mapping (address => bool) public openProjects; mapping (uint => order) public orders; order[] public allOrdersArr; constructor(uint256 initsupply) public payable ERC20 ("Hopium", "HOPE") { _mint(msg.sender, initsupply.mul(10**18) ); owners[msg.sender] = true; feesLeftInContract = 0; canInvest = true; FundsLeftInContract = msg.value; fundsCollectedTotal = FundsLeftInContract; } modifier onlyOwner{ require(owners[msg.sender], "Only an owner can call this function." ); _; } modifier onlyFundContract { require( msg.sender == Fundcontract, "Only the Fundcontract can call this function." ); _; } function closeFunding () public onlyOwner { canInvest = false; } function openFunding () public onlyOwner { canInvest = true; } function buy (uint amount, uint price, uint _fee) public payable returns (uint) { //free choice to donate or not require(canInvest, "funding is now closed, try again later"); require(ask <= price, "user not willing to pay the ask price"); if (!minFeeActive) { fee = _fee; } volume += amount; setPrice(); uint priceToPay = ask.mul(amount); priceToPay = priceToPay.div(10**18); require(priceToPay > 1, "less than 1 wei, buy more"); FundsLeftInContract += priceToPay; fundsCollectedTotal += priceToPay; priceToPay = priceToPay.add(fee); require(msg.value >= priceToPay, "not enough money send"); indexOfOrders += 1; _mint(msg.sender, amount); if (priceToPay < msg.value) { require(priceToPay > 0); uint refund = msg.value.sub(priceToPay); msg.sender.transfer(refund); } order memory neworder = orders[indexOfOrders]; neworder.orderNumber = indexOfOrders; neworder.timeStamp = block.number; neworder.amount = amount; //in wei neworder.buy = true; neworder.price = ask; neworder.participant = msg.sender; neworder.eth = priceToPay; neworder.fundingTokens = amount; orders[indexOfOrders] = neworder; allOrdersArr.push(neworder); setPrice(); totalFeesCollected += fee; feesLeftInContract += fee; return indexOfOrders; } function addOwner (address payable newOwner) public onlyOwner { owners[newOwner] = true; } function checkPriceForXcoinsInWeiPerCoin(uint amountOfCoins) public view returns (uint pricePerCoin) { amountOfCoins = amountOfCoins; pricePerCoin = (amountOfCoins.div(10**18).mul(ask)).add(fee); return pricePerCoin; //should be front-end function, not on the smart contract itself } function sell (uint amount, uint minPrice, uint _fee) public returns (uint) { require(bid >= minPrice, "user not willing to pay the bid price"); require(canInvest, "funding is now closed, try again later"); if (!minFeeActive) { fee = _fee; } volume += amount; //to be adjusted when working front-end setPrice(); uint ethToReceive = bid.mul(amount); ethToReceive = ethToReceive.div(10**18); require(ethToReceive <= FundsLeftInContract, "contract is too broke to pay that much"); require (ethToReceive > 0, "nothing?"); FundsLeftInContract = FundsLeftInContract.sub(ethToReceive); //receive by user fundsRepaidTotal += ethToReceive; totalFeesCollected += fee; feesLeftInContract += fee; ethToReceive = ethToReceive.sub(fee); indexOfOrders += 1; _burn(msg.sender, amount); msg.sender.transfer(ethToReceive); order memory neworder = orders[indexOfOrders]; neworder.orderNumber = indexOfOrders; neworder.timeStamp = block.number; neworder.amount = amount; //in wei neworder.buy = false; neworder.price = bid; neworder.participant = msg.sender; neworder.eth = ethToReceive; neworder.fundingTokens = amount; orders[indexOfOrders] = neworder; allOrdersArr.push(neworder); setPrice(); return indexOfOrders; } function setPrice () public { uint rvalue = RealValue(); //per coin? bid = rvalue.mul(99).div(100).sub(1 wei); //contract is willing to pay amount x for the tokens to burn them; require( bid >= 1 wei); ask = (rvalue.mul(101)).div(100).add(1 wei); // ask = rvalue.add(pip); // contract is offering newly minted tokens for the price of x; //the contract is asking 1% too much, and biding 1% too less, this gap will generate value for the hodlers and increase the real value, pumping up the price; //this 2% gap will also leave room for traders to trade the coin on uniswap instead of on this contract, resulting in possible arbitrage possibilities. //that way tokenholders have things they can do while they waiting for enough funding to fund real world fysical projects. //the contract will always offer the total supply of eth for 1% below the real value; } function RealValue () public returns (uint) { if (FundsLeftInContract == 0) { FundsLeftInContract = 1; } uint rv = (FundsLeftInContract.mul(10**18)).div(totalSupply()); //wei / hope price too low for price per hwei real value per full coin // cutting off real value //value per hwei. require(rv >= 1 wei, 'real value is 1 wei or lower'); return rv; } function setFee (uint amount) public onlyOwner { fee = amount; } function claimFees (uint amount) public onlyOwner { claimedFees += amount; feesLeftInContract = feesLeftInContract.sub(amount); require (feesLeftInContract >= 0, "not yet earned enough fees to claim that much"); msg.sender.transfer(amount); } function setFundContract (address payable _fundcontract) public onlyOwner { Fundcontract = _fundcontract; } function registerProject (address payable projectToAdd) public onlyFundContract { openProjects[projectToAdd] = true; //register in order to be able to receive funding } function fundProject ( uint amountOfTokens, address payable projectsAddress) public onlyFundContract returns (uint){ require(openProjects[projectsAddress]); volume += amountOfTokens; burnedToFund += amountOfTokens; // require(amountOfTokens >=10**18, 'you need to sell at least 1 full token'); setPrice(); uint ethToReceive = (RealValue().mul(10**18)).mul(amountOfTokens); //dividing the tokens result in division by 0 error, so RealValue.mul10**18 instead as fix so we can sell less than 1 full token. (min 1 wei total value) //ethToReceive = ethToReceive.div(10**18); require(FundsLeftInContract >= ethToReceive, "not enough funds left in reserve for that"); indexOfOrders += 1; _burn(msg.sender, amountOfTokens); // to stake in a projects, tokens must be send to the fundingcontract. FundsLeftInContract = FundsLeftInContract.sub(ethToReceive); //receive by user fundsRepaidTotal += ethToReceive; projectsAddress.transfer(ethToReceive); order memory neworder = orders[indexOfOrders]; neworder.orderNumber = indexOfOrders; neworder.timeStamp = block.number; neworder.amount = amountOfTokens; //in wei neworder.buy = false; neworder.price = bid; neworder.participant = msg.sender; neworder.eth = ethToReceive; neworder.fundingTokens = amountOfTokens; orders[indexOfOrders] = neworder; allOrdersArr.push(neworder); setPrice(); return indexOfOrders; } function removeOwner () public { //only an owner can remove himself, not other owners. owners[msg.sender] = false; } }
ask = rvalue.add(pip); contract is offering newly minted tokens for the price of x;the contract is asking 1% too much, and biding 1% too less, this gap will generate value for the hodlers and increase the real value, pumping up the price;this 2% gap will also leave room for traders to trade the coin on uniswap instead of on this contract, resulting in possible arbitrage possibilities.that way tokenholders have things they can do while they waiting for enough funding to fund real world fysical projects.the contract will always offer the total supply of eth for 1% below the real value;
function setPrice () public { require( bid >= 1 wei); ask = (rvalue.mul(101)).div(100).add(1 wei); }
14,039,717
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization * control functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the * sender account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ERC223 { uint public totalSupply; // ERC223 and ERC20 functions and events function balanceOf(address who) public view returns (uint); function totalSupply() public view returns (uint256 _supply); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); function transfer(address to, uint value, bytes data, string customFallback) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); // ERC223 functions function name() public view returns (string _name); function symbol() public view returns (string _symbol); function decimals() public view returns (uint8 _decimals); // ERC20 functions and events function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } /** * @title ContractReceiver * @dev Contract that is working with ERC223 tokens */ contract ContractReceiver { struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint _value, bytes _data) public pure { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); /* * tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function if data of token transaction is a function execution */ } } contract NOTNCoin is ERC223, Ownable { using SafeMath for uint256; string public name = "NAOTANCOIN"; string public symbol = "NOTN"; uint8 public decimals = 8; uint256 public totalSupply = 123e8 * 1e8; uint256 public distributeAmount = 0; bool public mintingFinished = false; address public founder = 0x9Da9874008d157d8e93DF7639a46b667c65DaadB; address public Sleep = 0x32F7b01EAc87fD4cDd1c3F2Cb0dCeB409B0d9638; mapping(address => uint256) public balanceOf; mapping(address => mapping (address => uint256)) public allowance; mapping (address => bool) public frozenAccount; mapping (address => uint256) public unlockUnixTime; event FrozenFunds(address indexed target, bool frozen); event LockedFunds(address indexed target, uint256 locked); event Burn(address indexed from, uint256 amount); event Mint(address indexed to, uint256 amount); event MintFinished(); /** * @dev Constructor is called only once and can not be called again */ function NOTNCoin() public { balanceOf[founder] = totalSupply.mul(90).div(100); balanceOf[Sleep] = totalSupply.mul(10).div(100); } function name() public view returns (string _name) { return name; } function symbol() public view returns (string _symbol) { return symbol; } function decimals() public view returns (uint8 _decimals) { return decimals; } function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOf[_owner]; } function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public { require(targets.length > 0); for (uint j = 0; j < targets.length; j++) { require(targets[j] != 0x0); frozenAccount[targets[j]] = isFrozen; FrozenFunds(targets[j], isFrozen); } } function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public { require(targets.length > 0 && targets.length == unixTimes.length); for(uint j = 0; j < targets.length; j++){ require(unlockUnixTime[targets[j]] < unixTimes[j]); unlockUnixTime[targets[j]] = unixTimes[j]; LockedFunds(targets[j], unixTimes[j]); } } /** * @dev Function that is called when a user or another contract wants to transfer funds */ function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } else { return transferToAddress(_to, _value, _data); } } function transfer(address _to, uint _value, bytes _data) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } /** * @dev Standard function transfer similar to ERC20 transfer with no _data * Added due to backwards compatibility reasons */ function transfer(address _to, uint _value) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } // assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } // function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } // function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * Added due to backwards compatibility with ERC20 * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_to != address(0) && _value > 0 && balanceOf[_from] >= _value && allowance[_from][msg.sender] >= _value && frozenAccount[_from] == false && frozenAccount[_to] == false && now > unlockUnixTime[_from] && now > unlockUnixTime[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Allows _spender to spend no more than _value tokens in your behalf * Added due to backwards compatibility with ERC20 * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender * Added due to backwards compatibility with ERC20 * @param _owner address The address which owns the funds * @param _spender address The address which will spend the funds */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowance[_owner][_spender]; } /** * @dev Burns a specific amount of tokens. * @param _from The address that will burn the tokens. * @param _unitAmount The amount of token to be burned. */ function burn(address _from, uint256 _unitAmount) onlyOwner public { require(_unitAmount > 0 && balanceOf[_from] >= _unitAmount); balanceOf[_from] = balanceOf[_from].sub(_unitAmount); totalSupply = totalSupply.sub(_unitAmount); Burn(_from, _unitAmount); } modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _unitAmount The amount of tokens to mint. */ function mint(address _to, uint256 _unitAmount) onlyOwner canMint public returns (bool) { require(_unitAmount > 0); totalSupply = totalSupply.add(_unitAmount); balanceOf[_to] = balanceOf[_to].add(_unitAmount); Mint(_to, _unitAmount); Transfer(address(0), _to, _unitAmount); return true; } /** * @dev Function to stop minting new tokens. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } /** * @dev Function to distribute tokens to the list of addresses by the provided amount */ function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool) { require(amount > 0 && addresses.length > 0 && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); amount = amount.mul(1e8); uint256 totalAmount = amount.mul(addresses.length); require(balanceOf[msg.sender] >= totalAmount); for (uint j = 0; j < addresses.length; j++) { require(addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount); Transfer(msg.sender, addresses[j], amount); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } function distributeAirdrop(address[] addresses, uint[] amounts) public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); uint256 totalAmount = 0; for(uint j = 0; j < addresses.length; j++){ require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); totalAmount = totalAmount.add(amounts[j]); } require(balanceOf[msg.sender] >= totalAmount); for (j = 0; j < addresses.length; j++) { balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]); Transfer(msg.sender, addresses[j], amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } /** * @dev Function to collect tokens from the list of addresses */ function collectTokens(address[] addresses, uint[] amounts) onlyOwner public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length); uint256 totalAmount = 0; for (uint j = 0; j < addresses.length; j++) { require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); require(balanceOf[addresses[j]] >= amounts[j]); balanceOf[addresses[j]] = balanceOf[addresses[j]].sub(amounts[j]); totalAmount = totalAmount.add(amounts[j]); Transfer(addresses[j], msg.sender, amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].add(totalAmount); return true; } function setDistributeAmount(uint256 _unitAmount) onlyOwner public { distributeAmount = _unitAmount; } /** * @dev Function to distribute tokens to the msg.sender automatically * If distributeAmount is 0, this function doesn't work */ }
Constructor is called only once and can not be called again/
function NOTNCoin() public { balanceOf[founder] = totalSupply.mul(90).div(100); balanceOf[Sleep] = totalSupply.mul(10).div(100); }
13,677,113
/** *Submitted for verification at Etherscan.io on 2021-12-18 */ // Sources flattened with hardhat v2.6.5 https://hardhat.org // File contracts/libs/TransferHelper.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.6; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint)'))); (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,uint)'))); (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,uint)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File contracts/interfaces/INestBatchPriceView.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This contract implemented the mining logic of nest interface INestBatchPriceView { /// @dev Get the latest trigger price /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function triggeredPrice(uint channelId, uint pairIndex) external view returns (uint blockNumber, uint price); /// @dev Get the full information of latest trigger price /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo(uint channelId, uint pairIndex) external view returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ ); /// @dev Find the price at block number /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param height Destination block number /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function findPrice( uint channelId, uint pairIndex, uint height ) external view returns (uint blockNumber, uint price); /// @dev Get the last (num) effective price /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param count The number of prices that want to return /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price function lastPriceList(uint channelId, uint pairIndex, uint count) external view returns (uint[] memory); /// @dev Returns lastPriceList and triggered price info /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param count The number of prices that want to return /// @return prices An array which length is num * 2, each two element expresses one price like blockNumber|price /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation /// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to /// 999999999999996447, it means that the volatility has exceeded the range that can be expressed function lastPriceListAndTriggeredPriceInfo(uint channelId, uint pairIndex, uint count) external view returns ( uint[] memory prices, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ); } // File contracts/interfaces/INestBatchPrice2.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This contract implemented the mining logic of nest interface INestBatchPrice2 { /// @dev Get the latest trigger price /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 价格数组, i * 2 为第i个价格所在区块, i * 2 + 1 为第i个价格 function triggeredPrice( uint channelId, uint[] calldata pairIndices, address payback ) external payable returns (uint[] memory prices); /// @dev Get the full information of latest trigger price /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 价格数组, i * 4 为第i个价格所在区块, i * 4 + 1 为第i个价格, /// i * 4 + 2 为第i个平均价格, i * 4 + 3 为第i个波动率 function triggeredPriceInfo( uint channelId, uint[] calldata pairIndices, address payback ) external payable returns (uint[] memory prices); /// @dev Find the price at block number /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param height Destination block number /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 价格数组, i * 2 为第i个价格所在区块, i * 2 + 1 为第i个价格 function findPrice( uint channelId, uint[] calldata pairIndices, uint height, address payback ) external payable returns (uint[] memory prices); /// @dev Get the last (num) effective price /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param count The number of prices that want to return /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 结果数组,第 i * count * 2 到 (i + 1) * count * 2 - 1为第i组报价对的价格结果 function lastPriceList( uint channelId, uint[] calldata pairIndices, uint count, address payback ) external payable returns (uint[] memory prices); /// @dev Returns lastPriceList and triggered price info /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param count The number of prices that want to return /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 结果数组,第 i * (count * 2 + 4)到 (i + 1) * (count * 2 + 4)- 1为第i组报价对的价格结果 /// 其中前count * 2个为最新价格,后4个依次为:触发价格区块号,触发价格,平均价格,波动率 function lastPriceListAndTriggeredPriceInfo( uint channelId, uint[] calldata pairIndices, uint count, address payback ) external payable returns (uint[] memory prices); } // File contracts/libs/IERC20.sol // MIT pragma solidity ^0.8.6; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/interfaces/INestBatchMining.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the mining methods for nest interface INestBatchMining { /// @dev 开通报价通道 /// @param channelId 报价通道编号 /// @param token0 计价代币地址。0表示eth /// @param unit token0的单位 /// @param reward 挖矿代币地址。0表示不挖矿 event Open(uint channelId, address token0, uint unit, address reward); /// @dev Post event /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param miner Address of miner /// @param index Index of the price sheet /// @param scale 报价规模 event Post(uint channelId, uint pairIndex, address miner, uint index, uint scale, uint price); /* ========== Structures ========== */ /// @dev Nest mining configuration structure struct Config { // -- Public configuration // The number of times the sheet assets have doubled. 4 uint8 maxBiteNestedLevel; // Price effective block interval. 20 uint16 priceEffectSpan; // The amount of nest to pledge for each post (Unit: 1000). 100 uint16 pledgeNest; } /// @dev PriceSheetView structure struct PriceSheetView { // Index of the price sheet uint32 index; // Address of miner address miner; // The block number of this price sheet packaged uint32 height; // The remain number of this price sheet uint32 remainNum; // The eth number which miner will got uint32 ethNumBal; // The eth number which equivalent to token's value which miner will got uint32 tokenNumBal; // The pledged number of nest in this sheet. (Unit: 1000nest) uint24 nestNum1k; // The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses bite price sheet uint8 level; // Post fee shares, if there are many sheets in one block, this value is used to divide up mining value uint8 shares; // The token price. (1eth equivalent to (price) token) uint152 price; } // 报价通道配置 struct ChannelConfig { // 计价代币地址, 0表示eth address token0; // 计价代币单位 uint96 unit; // 矿币地址如果和token0或者token1是一种币,可能导致挖矿资产被当成矿币挖走 // 出矿代币地址 address reward; // 每个区块的标准出矿量 uint96 rewardPerBlock; // 矿币总量 //uint96 vault; // 管理地址 //address governance; // 创世区块 //uint32 genesisBlock; // Post fee(0.0001eth,DIMI_ETHER). 1000 uint16 postFeeUnit; // Single query fee (0.0001 ether, DIMI_ETHER). 100 uint16 singleFee; // 衰减系数,万分制。8000 uint16 reductionRate; address[] tokens; } /// @dev 报价对视图 struct PairView { // 报价代币地址 address target; // 报价单数量 uint96 sheetCount; } /// @dev Price channel view struct PriceChannelView { uint channelId; // 计价代币地址, 0表示eth address token0; // 计价代币单位 uint96 unit; // 矿币地址如果和token0或者token1是一种币,可能导致挖矿资产被当成矿币挖走 // 出矿代币地址 address reward; // 每个区块的标准出矿量 uint96 rewardPerBlock; // 矿币总量 uint128 vault; // The information of mining fee uint96 rewards; // Post fee(0.0001eth,DIMI_ETHER). 1000 uint16 postFeeUnit; // 报价对数量 uint16 count; // 管理地址 address governance; // 创世区块 uint32 genesisBlock; // Single query fee (0.0001 ether, DIMI_ETHER). 100 uint16 singleFee; // 衰减系数,万分制。8000 uint16 reductionRate; // 报价对信息 PairView[] pairs; } /* ========== Configuration ========== */ /// @dev Modify configuration /// @param config Configuration object function setConfig(Config calldata config) external; /// @dev Get configuration /// @return Configuration object function getConfig() external view returns (Config memory); /// @dev 开通报价通道 /// @param config 报价通道配置 function open(ChannelConfig calldata config) external; /// @dev 向报价通道注入矿币 /// @param channelId 报价通道 /// @param vault 注入矿币数量 function increase(uint channelId, uint128 vault) external payable; /// @dev 从报价通道取出矿币 /// @param channelId 报价通道 /// @param vault 注入矿币数量 function decrease(uint channelId, uint128 vault) external; /// @dev 获取报价通道信息 /// @param channelId 报价通道 /// @return 报价通道信息 function getChannelInfo(uint channelId) external view returns (PriceChannelView memory); /// @dev 报价 /// @param channelId 报价通道id /// @param scale 报价规模(token0,单位unit) /// @param equivalents 价格数组,索引和报价对一一对应 function post(uint channelId, uint scale, uint[] calldata equivalents) external payable; /// @notice Call the function to buy TOKEN/NTOKEN from a posted price sheet /// @dev bite TOKEN(NTOKEN) by ETH, (+ethNumBal, -tokenNumBal) /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号。吃单方向为拿走计价代币时,直接传报价对编号,吃单方向为拿走报价代币时,报价对编号加65536 /// @param index The position of the sheet in priceSheetList[token] /// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum * newTokenAmountPerEth /// @param newEquivalent The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth function take(uint channelId, uint pairIndex, uint index, uint takeNum, uint newEquivalent) external payable; /// @dev List sheets by page /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param offset Skip previous (offset) records /// @param count Return (count) records /// @param order Order. 0 reverse order, non-0 positive order /// @return List of price sheets function list( uint channelId, uint pairIndex, uint offset, uint count, uint order ) external view returns (PriceSheetView[] memory); /// @notice Close a batch of price sheets passed VERIFICATION-PHASE /// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed /// @param channelId 报价通道编号 /// @param indices 报价单二维数组,外层对应通道号,内层对应报价单号,如果仅关闭后面的报价对,则前面的报价对数组传空数组 function close(uint channelId, uint[][] calldata indices) external; /// @dev View the number of assets specified by the user /// @param tokenAddress Destination token address /// @param addr Destination address /// @return Number of assets function balanceOf(address tokenAddress, address addr) external view returns (uint); /// @dev Withdraw assets /// @param tokenAddress Destination token address /// @param value The value to withdraw function withdraw(address tokenAddress, uint value) external; /// @dev Estimated mining amount /// @param channelId 报价通道编号 /// @return Estimated mining amount function estimate(uint channelId) external view returns (uint); /// @dev Query the quantity of the target quotation /// @param channelId 报价通道编号 /// @param index The index of the sheet /// @return minedBlocks Mined block period from previous block /// @return totalShares Total shares of sheets in the block function getMinedBlocks( uint channelId, uint index ) external view returns (uint minedBlocks, uint totalShares); /// @dev The function returns eth rewards of specified ntoken /// @param channelId 报价通道编号 function totalETHRewards(uint channelId) external view returns (uint); /// @dev Pay /// @param channelId 报价通道编号 /// @param to Address to receive /// @param value Amount to receive function pay(uint channelId, address to, uint value) external; /// @dev 向DAO捐赠 /// @param channelId 报价通道 /// @param value Amount to receive function donate(uint channelId, uint value) external; } // File contracts/interfaces/INestLedger.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the nest ledger methods interface INestLedger { /// @dev Application Flag Changed event /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization event ApplicationChanged(address addr, uint flag); /// @dev Set DAO application /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization function setApplication(address addr, uint flag) external; /// @dev Check DAO application flag /// @param addr DAO application contract address /// @return Authorization flag, 1 means authorization, 0 means cancel authorization function checkApplication(address addr) external view returns (uint); /// @dev Add reward /// @param channelId 报价通道 function addETHReward(uint channelId) external payable; /// @dev The function returns eth rewards of specified ntoken /// @param channelId 报价通道 function totalETHRewards(uint channelId) external view returns (uint); /// @dev Pay /// @param channelId 报价通道 /// @param tokenAddress Token address of receiving funds (0 means ETH) /// @param to Address to receive /// @param value Amount to receive function pay(uint channelId, address tokenAddress, address to, uint value) external; } // File contracts/interfaces/INToken.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev ntoken interface interface INToken { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /// @dev Mint /// @param value The amount of NToken to add function increaseTotal(uint256 value) external; /// @notice The view of variables about minting /// @dev The naming follows nest v3.0 /// @return createBlock The block number where the contract was created /// @return recentlyUsedBlock The block number where the last minting went function checkBlockInfo() external view returns(uint256 createBlock, uint256 recentlyUsedBlock); /// @dev The ABI keeps unchanged with old NTokens, so as to support token-and-ntoken-mining /// @return The address of bidder function checkBidder() external view returns(address); /// @notice The view of totalSupply /// @return The total supply of ntoken function totalSupply() external view returns (uint256); /// @dev The view of balances /// @param owner The address of an account /// @return The balance of the account function balanceOf(address owner) 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); } // File contracts/interfaces/INestMapping.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev The interface defines methods for nest builtin contract address mapping interface INestMapping { /// @dev Set the built-in contract address of the system /// @param nestTokenAddress Address of nest token contract /// @param nestNodeAddress Address of nest node contract /// @param nestLedgerAddress INestLedger implementation contract address /// @param nestMiningAddress INestMining implementation contract address for nest /// @param ntokenMiningAddress INestMining implementation contract address for ntoken /// @param nestPriceFacadeAddress INestPriceFacade implementation contract address /// @param nestVoteAddress INestVote implementation contract address /// @param nestQueryAddress INestQuery implementation contract address /// @param nnIncomeAddress NNIncome contract address /// @param nTokenControllerAddress INTokenController implementation contract address function setBuiltinAddress( address nestTokenAddress, address nestNodeAddress, address nestLedgerAddress, address nestMiningAddress, address ntokenMiningAddress, address nestPriceFacadeAddress, address nestVoteAddress, address nestQueryAddress, address nnIncomeAddress, address nTokenControllerAddress ) external; /// @dev Get the built-in contract address of the system /// @return nestTokenAddress Address of nest token contract /// @return nestNodeAddress Address of nest node contract /// @return nestLedgerAddress INestLedger implementation contract address /// @return nestMiningAddress INestMining implementation contract address for nest /// @return ntokenMiningAddress INestMining implementation contract address for ntoken /// @return nestPriceFacadeAddress INestPriceFacade implementation contract address /// @return nestVoteAddress INestVote implementation contract address /// @return nestQueryAddress INestQuery implementation contract address /// @return nnIncomeAddress NNIncome contract address /// @return nTokenControllerAddress INTokenController implementation contract address function getBuiltinAddress() external view returns ( address nestTokenAddress, address nestNodeAddress, address nestLedgerAddress, address nestMiningAddress, address ntokenMiningAddress, address nestPriceFacadeAddress, address nestVoteAddress, address nestQueryAddress, address nnIncomeAddress, address nTokenControllerAddress ); /// @dev Get address of nest token contract /// @return Address of nest token contract function getNestTokenAddress() external view returns (address); /// @dev Get address of nest node contract /// @return Address of nest node contract function getNestNodeAddress() external view returns (address); /// @dev Get INestLedger implementation contract address /// @return INestLedger implementation contract address function getNestLedgerAddress() external view returns (address); /// @dev Get INestMining implementation contract address for nest /// @return INestMining implementation contract address for nest function getNestMiningAddress() external view returns (address); /// @dev Get INestMining implementation contract address for ntoken /// @return INestMining implementation contract address for ntoken function getNTokenMiningAddress() external view returns (address); /// @dev Get INestPriceFacade implementation contract address /// @return INestPriceFacade implementation contract address function getNestPriceFacadeAddress() external view returns (address); /// @dev Get INestVote implementation contract address /// @return INestVote implementation contract address function getNestVoteAddress() external view returns (address); /// @dev Get INestQuery implementation contract address /// @return INestQuery implementation contract address function getNestQueryAddress() external view returns (address); /// @dev Get NNIncome contract address /// @return NNIncome contract address function getNnIncomeAddress() external view returns (address); /// @dev Get INTokenController implementation contract address /// @return INTokenController implementation contract address function getNTokenControllerAddress() external view returns (address); /// @dev Registered address. The address registered here is the address accepted by nest system /// @param key The key /// @param addr Destination address. 0 means to delete the registration information function registerAddress(string memory key, address addr) external; /// @dev Get registered address /// @param key The key /// @return Destination address. 0 means empty function checkAddress(string memory key) external view returns (address); } // File contracts/interfaces/INestGovernance.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the governance methods interface INestGovernance is INestMapping { /// @dev Set governance authority /// @param addr Destination address /// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function setGovernance(address addr, uint flag) external; /// @dev Get governance rights /// @param addr Destination address /// @return Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function getGovernance(address addr) external view returns (uint); /// @dev Check whether the target address has governance rights for the given target /// @param addr Destination address /// @param flag Permission weight. The permission of the target address must be greater than this weight /// to pass the check /// @return True indicates permission function checkGovernance(address addr, uint flag) external view returns (bool); } // File contracts/NestBase.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev Base contract of nest contract NestBase { // Address of nest token contract address constant NEST_TOKEN_ADDRESS = 0x04abEdA201850aC0124161F037Efd70c74ddC74C; // Genesis block number of nest // NEST token contract is created at block height 6913517. However, because the mining algorithm of nest1.0 // is different from that at present, a new mining algorithm is adopted from nest2.0. The new algorithm // includes the attenuation logic according to the block. Therefore, it is necessary to trace the block // where the nest begins to decay. According to the circulation when nest2.0 is online, the new mining // algorithm is used to deduce and convert the nest, and the new algorithm is used to mine the nest2.0 // on-line flow, the actual block is 5120000 //uint constant NEST_GENESIS_BLOCK = 0; /// @dev To support open-zeppelin/upgrades /// @param nestGovernanceAddress INestGovernance implementation contract address function initialize(address nestGovernanceAddress) public virtual { require(_governance == address(0), "NEST:!initialize"); _governance = nestGovernanceAddress; } /// @dev INestGovernance implementation contract address address public _governance; /// @dev Rewritten in the implementation contract, for load other contract addresses. Call /// super.update(nestGovernanceAddress) when overriding, and override method without onlyGovernance /// @param nestGovernanceAddress INestGovernance implementation contract address function update(address nestGovernanceAddress) public virtual { address governance = _governance; require(governance == msg.sender || INestGovernance(governance).checkGovernance(msg.sender, 0), "NEST:!gov"); _governance = nestGovernanceAddress; } // /// @dev Migrate funds from current contract to NestLedger // /// @param tokenAddress Destination token address.(0 means eth) // /// @param value Migrate amount // function migrate(address tokenAddress, uint value) external onlyGovernance { // address to = INestGovernance(_governance).getNestLedgerAddress(); // if (tokenAddress == address(0)) { // INestLedger(to).addETHReward { value: value } (0); // } else { // TransferHelper.safeTransfer(tokenAddress, to, value); // } // } //---------modifier------------ modifier onlyGovernance() { require(INestGovernance(_governance).checkGovernance(msg.sender, 0), "NEST:!gov"); _; } modifier noContract() { require(msg.sender == tx.origin, "NEST:!contract"); _; } } // File contracts/NestBatchMining.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This contract implemented the mining logic of nest contract NestBatchMining is NestBase, INestBatchMining { /// @dev To support open-zeppelin/upgrades /// @param nestGovernanceAddress INestGovernance implementation contract address function initialize(address nestGovernanceAddress) public override { super.initialize(nestGovernanceAddress); // Placeholder in _accounts, the index of a real account must greater than 0 _accounts.push(); } /// @dev Definitions for the price sheet, include the full information. /// (use 256-bits, a storage unit in ethereum evm) struct PriceSheet { // Index of miner account in _accounts. for this way, mapping an address(which need 160-bits) to a 32-bits // integer, support 4 billion accounts uint32 miner; // The block number of this price sheet packaged uint32 height; // The remain number of this price sheet uint32 remainNum; // The eth number which miner will got uint32 ethNumBal; // The eth number which equivalent to token's value which miner will got uint32 tokenNumBal; // The pledged number of nest in this sheet. (Unit: 1000nest) uint24 nestNum1k; // The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses bite price sheet uint8 level; // Post fee shares, if there are many sheets in one block, this value is used to divide up mining value uint8 shares; // Represent price as this way, may lose precision, the error less than 1/10^14 // price = priceFraction * 16 ^ priceExponent uint56 priceFloat; } /// @dev Definitions for the price information struct PriceInfo { // Record the index of price sheet, for update price information from price sheet next time. uint32 index; // The block number of this price uint32 height; // The remain number of this price sheet uint32 remainNum; // Price, represent as float // Represent price as this way, may lose precision, the error less than 1/10^14 uint56 priceFloat; // Avg Price, represent as float // Represent price as this way, may lose precision, the error less than 1/10^14 uint56 avgFloat; // Square of price volatility, need divide by 2^48 uint48 sigmaSQ; } // 报价对 struct PricePair { address target; PriceInfo price; PriceSheet[] sheets; } /// @dev Price channel struct PriceChannel { // 计价代币地址, 0表示eth address token0; // 计价代币单位 uint96 unit; // 出矿代币地址 address reward; // 每个区块的标准出矿量 uint96 rewardPerBlock; // 矿币总量 uint128 vault; // The information of mining fee uint96 rewards; // Post fee(0.0001eth,DIMI_ETHER). 1000 uint16 postFeeUnit; // 报价对数量 uint16 count; // 管理地址 address governance; // 创世区块 uint32 genesisBlock; // Single query fee (0.0001 ether, DIMI_ETHER). 100 uint16 singleFee; // 衰减系数,万分制。8000 uint16 reductionRate; // 报价对数组 PricePair[0xFFFF] pairs; } /// @dev Structure is used to represent a storage location. Storage variable can be used to avoid indexing /// from mapping many times struct UINT { uint value; } /// @dev Account information struct Account { // Address of account address addr; // Balances of mining account // tokenAddress=>balance mapping(address=>UINT) balances; } // Configuration Config _config; // Registered account information Account[] _accounts; // Mapping from address to index of account. address=>accountIndex mapping(address=>uint) _accountMapping; // 报价通道映射,通过此映射避免重复添加报价通道 //mapping(uint=>uint) _channelMapping; // 报价通道 PriceChannel[] _channels; // Unit of post fee. 0.0001 ether uint constant DIMI_ETHER = 0.0001 ether; // Ethereum average block time interval, 14 seconds uint constant ETHEREUM_BLOCK_TIMESPAN = 14; // Nest ore drawing attenuation interval. 2400000 blocks, about one year uint constant NEST_REDUCTION_SPAN = 2400000; // The decay limit of nest ore drawing becomes stable after exceeding this interval. // 24 million blocks, about 10 years uint constant NEST_REDUCTION_LIMIT = 24000000; //NEST_REDUCTION_SPAN * 10; // Attenuation gradient array, each attenuation step value occupies 16 bits. The attenuation value is an integer uint constant NEST_REDUCTION_STEPS = 0x280035004300530068008300A300CC010001400190; // 0 // | (uint(400 / uint(1)) << (16 * 0)) // | (uint(400 * 8 / uint(10)) << (16 * 1)) // | (uint(400 * 8 * 8 / uint(10 * 10)) << (16 * 2)) // | (uint(400 * 8 * 8 * 8 / uint(10 * 10 * 10)) << (16 * 3)) // | (uint(400 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10)) << (16 * 4)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10)) << (16 * 5)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10)) << (16 * 6)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 7)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 8)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 9)) // //| (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 10)); // | (uint(40) << (16 * 10)); /* ========== Governance ========== */ /// @dev Modify configuration /// @param config Configuration object function setConfig(Config calldata config) external override onlyGovernance { _config = config; } /// @dev Get configuration /// @return Configuration object function getConfig() external view override returns (Config memory) { return _config; } /// @dev 开通报价通道 /// @param config 报价通道配置 function open(ChannelConfig calldata config) external override { // 计价代币 address token0 = config.token0; // 矿币 address reward = config.reward; // 触发开通事件 emit Open(_channels.length, token0, config.unit, reward); PriceChannel storage channel = _channels.push(); // 计价代币 channel.token0 = token0; // 计价代币单位 channel.unit = config.unit; // 矿币 channel.reward = reward; // 单位区块出矿币数量 channel.rewardPerBlock = config.rewardPerBlock; channel.vault = uint128(0); channel.rewards = uint96(0); // Post fee(0.0001eth,DIMI_ETHER). 1000 channel.postFeeUnit = config.postFeeUnit; channel.count = uint16(config.tokens.length); // 管理地址 channel.governance = msg.sender; // 创世区块 channel.genesisBlock = uint32(block.number); // Single query fee (0.0001 ether, DIMI_ETHER). 100 channel.singleFee = config.singleFee; // 衰减系数,万分制。8000 channel.reductionRate = config.reductionRate; // 遍历创建报价对 for (uint i = 0; i < config.tokens.length; ++i) { require(token0 != config.tokens[i], "NOM:token can't equal token0"); for (uint j = 0; j < i; ++j) { require(config.tokens[i] != config.tokens[j], "NOM:token reiterated"); } channel.pairs[i].target = config.tokens[i]; } } /// @dev 添加报价代币,与计价代币形成新的报价对(暂不支持删除,请谨慎添加) /// @param channelId 报价通道 /// @param target 目标代币地址 function addPair(uint channelId, address target) external { PriceChannel storage channel = _channels[channelId]; require(channel.governance == msg.sender, "NOM:not governance"); require(channel.token0 != target, "NOM:token can't equal token0"); uint count = uint(channel.count); for (uint j = 0; j < count; ++j) { require(channel.pairs[j].target != target, "NOM:token reiterated"); } channel.pairs[count].target = target; ++channel.count; } /// @dev 向报价通道注入矿币 /// @param channelId 报价通道 /// @param vault 注入矿币数量 function increase(uint channelId, uint128 vault) external payable override { PriceChannel storage channel = _channels[channelId]; address reward = channel.reward; if (reward == address(0)) { require(msg.value == uint(vault), "NOM:vault error"); } else { TransferHelper.safeTransferFrom(reward, msg.sender, address(this), uint(vault)); } channel.vault += vault; } /// @dev 从报价通道取出矿币 /// @param channelId 报价通道 /// @param vault 取出矿币数量 function decrease(uint channelId, uint128 vault) external override { PriceChannel storage channel = _channels[channelId]; require(channel.governance == msg.sender, "NOM:not governance"); address reward = channel.reward; channel.vault -= vault; if (reward == address(0)) { payable(msg.sender).transfer(uint(vault)); } else { TransferHelper.safeTransfer(reward, msg.sender, uint(vault)); } } /// @dev 修改治理权限地址 /// @param channelId 报价通道 /// @param newGovernance 新治理权限地址 function changeGovernance(uint channelId, address newGovernance) external { PriceChannel storage channel = _channels[channelId]; require(channel.governance == msg.sender, "NOM:not governance"); channel.governance = newGovernance; } /// @dev 获取报价通道信息 /// @param channelId 报价通道 /// @return 报价通道信息 function getChannelInfo(uint channelId) external view override returns (PriceChannelView memory) { PriceChannel storage channel = _channels[channelId]; uint count = uint(channel.count); PairView[] memory pairs = new PairView[](count); for (uint i = 0; i < count; ++i) { PricePair storage pair = channel.pairs[i]; pairs[i] = PairView(pair.target, uint96(pair.sheets.length)); } return PriceChannelView ( channelId, // 计价代币地址, 0表示eth channel.token0, // 计价代币单位 channel.unit, // 矿币地址如果和token0或者token1是一种币,可能导致挖矿资产被当成矿币挖走 // 出矿代币地址 channel.reward, // 每个区块的标准出矿量 channel.rewardPerBlock, // 矿币总量 channel.vault, // The information of mining fee channel.rewards, // Post fee(0.0001eth,DIMI_ETHER). 1000 channel.postFeeUnit, // 报价对数量 channel.count, // 管理地址 channel.governance, // 创世区块 channel.genesisBlock, // Single query fee (0.0001 ether, DIMI_ETHER). 100 channel.singleFee, // 衰减系数,万分制。8000 channel.reductionRate, pairs ); } /* ========== Mining ========== */ /// @dev 报价 /// @param channelId 报价通道id /// @param scale 报价规模(token0,单位unit) /// @param equivalents 价格数组,索引和报价对一一对应 function post(uint channelId, uint scale, uint[] calldata equivalents) external payable override { // 0. 加载配置 Config memory config = _config; // 1. Check arguments require(scale == 1, "NOM:!scale"); // 2. Load price channel PriceChannel storage channel = _channels[channelId]; // 3. Freeze assets uint accountIndex = _addressIndex(msg.sender); // Freeze token and nest // Because of the use of floating-point representation(fraction * 16 ^ exponent), it may bring some precision // loss After assets are frozen according to tokenAmountPerEth * ethNum, the part with poor accuracy may be // lost when the assets are returned, It should be frozen according to decodeFloat(fraction, exponent) * ethNum // However, considering that the loss is less than 1 / 10 ^ 14, the loss here is ignored, and the part of // precision loss can be transferred out as system income in the future mapping(address=>UINT) storage balances = _accounts[accountIndex].balances; uint cn = uint(channel.count); uint fee = msg.value; // 冻结nest fee = _freeze(balances, NEST_TOKEN_ADDRESS, cn * uint(config.pledgeNest) * 1000 ether, fee); // 冻结token0 fee = _freeze(balances, channel.token0, cn * uint(channel.unit) * scale, fee); // 冻结token1 while (cn > 0) { PricePair storage pair = channel.pairs[--cn]; uint equivalent = equivalents[cn]; require(equivalent > 0, "NOM:!equivalent"); fee = _freeze(balances, pair.target, scale * equivalent, fee); // Calculate the price // According to the current mechanism, the newly added sheet cannot take effect, so the calculated price // is placed before the sheet is added, which can reduce unnecessary traversal _stat(config, pair); // 6. Create token price sheet emit Post(channelId, cn, msg.sender, pair.sheets.length, scale, equivalent); // 只有0号报价对挖矿 _create(pair.sheets, accountIndex, uint32(scale), uint(config.pledgeNest), cn == 0 ? 1 : 0, equivalent); } // 4. Deposit fee // 只有配置了报价佣金时才检查fee uint postFeeUnit = uint(channel.postFeeUnit); if (postFeeUnit > 0) { require(fee >= postFeeUnit * DIMI_ETHER + tx.gasprice * 400000, "NM:!fee"); } if (fee > 0) { channel.rewards += _toUInt96(fee); } } /// @notice Call the function to buy TOKEN/NTOKEN from a posted price sheet /// @dev bite TOKEN(NTOKEN) by ETH, (+ethNumBal, -tokenNumBal) /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号。吃单方向为拿走计价代币时,直接传报价对编号,吃单方向为拿走报价代币时,报价对编号加65536 /// @param index The position of the sheet in priceSheetList[token] /// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum * newTokenAmountPerEth /// @param newEquivalent The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth function take( uint channelId, uint pairIndex, uint index, uint takeNum, uint newEquivalent ) external payable override { Config memory config = _config; // 1. Check arguments require(takeNum > 0, "NM:!takeNum"); require(newEquivalent > 0, "NM:!price"); // 2. Load price sheet PriceChannel storage channel = _channels[channelId]; PricePair storage pair = channel.pairs[pairIndex < 0x10000 ? pairIndex : pairIndex - 0x10000]; //PriceSheet[] storage sheets = pair.sheets; PriceSheet memory sheet = pair.sheets[index]; // 3. Check state //require(uint(sheet.remainNum) >= takeNum, "NM:!remainNum"); require(uint(sheet.height) + uint(config.priceEffectSpan) >= block.number, "NM:!state"); sheet.remainNum = uint32(uint(sheet.remainNum) - takeNum); uint accountIndex = _addressIndex(msg.sender); // Number of nest to be pledged // sheet.ethNumBal + sheet.tokenNumBal is always two times to sheet.ethNum uint needNest1k = (takeNum << 2) * uint(sheet.nestNum1k) / (uint(sheet.ethNumBal) + uint(sheet.tokenNumBal)); // 4. Calculate the number of eth, token and nest needed, and freeze them uint needEthNum = takeNum; uint level = uint(sheet.level); if (level < 255) { if (level < uint(config.maxBiteNestedLevel)) { // Double scale sheet needEthNum <<= 1; } ++level; } { // Freeze nest and token // 冻结资产:token0, token1, nest mapping(address=>UINT) storage balances = _accounts[accountIndex].balances; uint fee = msg.value; // 当吃单方向为拿走计价代币时,直接传报价对编号,当吃单方向为拿走报价代币时,传报价对编号减65536 // pairIndex < 0x10000,吃单方向为拿走计价代币 if (pairIndex < 0x10000) { // Update the bitten sheet sheet.ethNumBal = uint32(uint(sheet.ethNumBal) - takeNum); sheet.tokenNumBal = uint32(uint(sheet.tokenNumBal) + takeNum); pair.sheets[index] = sheet; // 冻结token0 fee = _freeze(balances, channel.token0, (needEthNum - takeNum) * uint(channel.unit), fee); // 冻结token1 fee = _freeze( balances, pair.target, needEthNum * newEquivalent + _decodeFloat(sheet.priceFloat) * takeNum, fee ); } // pairIndex >= 0x10000,吃单方向为拿走报价代币 else { pairIndex -= 0x10000; // Update the bitten sheet sheet.ethNumBal = uint32(uint(sheet.ethNumBal) + takeNum); sheet.tokenNumBal = uint32(uint(sheet.tokenNumBal) - takeNum); pair.sheets[index] = sheet; // 冻结token0 fee = _freeze(balances, channel.token0, (needEthNum + takeNum) * uint(channel.unit), fee); // 冻结token1 uint backTokenValue = _decodeFloat(sheet.priceFloat) * takeNum; if (needEthNum * newEquivalent > backTokenValue) { fee = _freeze(balances, pair.target, needEthNum * newEquivalent - backTokenValue, fee); } else { _unfreeze(balances, pair.target, backTokenValue - needEthNum * newEquivalent, msg.sender); } } // 冻结nest fee = _freeze(balances, NEST_TOKEN_ADDRESS, needNest1k * 1000 ether, fee); require(fee == 0, "NOM:!fee"); } // 5. Calculate the price // According to the current mechanism, the newly added sheet cannot take effect, so the calculated price // is placed before the sheet is added, which can reduce unnecessary traversal _stat(config, pair); // 6. Create price sheet emit Post(channelId, pairIndex, msg.sender, pair.sheets.length, needEthNum, newEquivalent); _create(pair.sheets, accountIndex, uint32(needEthNum), needNest1k, level << 8, newEquivalent); } /// @dev List sheets by page /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param offset Skip previous (offset) records /// @param count Return (count) records /// @param order Order. 0 reverse order, non-0 positive order /// @return List of price sheets function list( uint channelId, uint pairIndex, uint offset, uint count, uint order ) external view override noContract returns (PriceSheetView[] memory) { PriceSheet[] storage sheets = _channels[channelId].pairs[pairIndex].sheets; PriceSheetView[] memory result = new PriceSheetView[](count); uint length = sheets.length; uint i = 0; // Reverse order if (order == 0) { uint index = length - offset; uint end = index > count ? index - count : 0; while (index > end) { --index; result[i++] = _toPriceSheetView(sheets[index], index); } } // Positive order else { uint index = offset; uint end = index + count; if (end > length) { end = length; } while (index < end) { result[i++] = _toPriceSheetView(sheets[index], index); ++index; } } return result; } /// @notice Close a batch of price sheets passed VERIFICATION-PHASE /// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed /// @param channelId 报价通道编号 /// @param indices 报价单二维数组,外层对应通道号,内层对应报价单号,如果仅关闭后面的报价对,则前面的报价对数组传空数组 function close(uint channelId, uint[][] calldata indices) external override { Config memory config = _config; PriceChannel storage channel = _channels[channelId]; uint accountIndex = 0; uint reward = 0; uint nestNum1k = 0; uint ethNum = 0; // storage变量必须在定义时初始化,因此在此处赋值,但是由于accountIndex此时为0,此赋值没有意义 mapping(address=>UINT) storage balances = _accounts[0/*accountIndex*/].balances; uint[3] memory vars = [ uint(channel.rewardPerBlock), uint(channel.genesisBlock), uint(channel.reductionRate) ]; for (uint j = indices.length; j > 0;) { PricePair storage pair = channel.pairs[--j]; /////////////////////////////////////////////////////////////////////////////////////// //PriceSheet[] storage sheets = pair.sheets; uint tokenValue = 0; // 1. Traverse sheets for (uint i = indices[j].length; i > 0;) { // --------------------------------------------------------------------------------- uint index = indices[j][--i]; PriceSheet memory sheet = pair.sheets[index]; //uint height = uint(sheet.height); //uint minerIndex = uint(sheet.miner); // Batch closing quotation can only close sheet of the same user if (accountIndex == 0) { // accountIndex == 0 means the first sheet, and the number of this sheet is taken accountIndex = uint(sheet.miner); balances = _accounts[accountIndex].balances; } else { // accountIndex != 0 means that it is a follow-up sheet, and the miner number must be // consistent with the previous record require(accountIndex == uint(sheet.miner), "NM:!miner"); } // Check the status of the price sheet to see if it has reached the effective block interval // or has been finished if (accountIndex > 0 && (uint(sheet.height) + uint(config.priceEffectSpan) < block.number)) { // 后面的通道不出矿,不需要出矿逻辑 // 出矿按照第一个通道计算 if (j == 0) { uint shares = uint(sheet.shares); // Mining logic // The price sheet which shares is zero doesn't mining if (shares > 0) { // Currently, mined represents the number of blocks has mined (uint mined, uint totalShares) = _calcMinedBlocks(pair.sheets, index, sheet); // 当开通者指定的rewardPerBlock非常大时,计算出矿可能会被截断,导致实际能够得到的出矿大大减少 // 这种情况是不合理的,需要由开通者负责 reward += ( mined * shares * _reduction(uint(sheet.height) - vars[1], vars[2]) * vars[0] / totalShares / 400 ); } } nestNum1k += uint(sheet.nestNum1k); ethNum += uint(sheet.ethNumBal); tokenValue += _decodeFloat(sheet.priceFloat) * uint(sheet.tokenNumBal); // Set sheet.miner to 0, express the sheet is closed sheet.miner = uint32(0); sheet.ethNumBal = uint32(0); sheet.tokenNumBal = uint32(0); pair.sheets[index] = sheet; } // --------------------------------------------------------------------------------- } _stat(config, pair); /////////////////////////////////////////////////////////////////////////////////////// // 解冻token1 _unfreeze(balances, pair.target, tokenValue, accountIndex); } // 解冻token0 _unfreeze(balances, channel.token0, ethNum * uint(channel.unit), accountIndex); // 解冻nest _unfreeze(balances, NEST_TOKEN_ADDRESS, nestNum1k * 1000 ether, accountIndex); uint vault = uint(channel.vault); if (reward > vault) { reward = vault; } // 记录每个通道矿币的数量,防止开通者不打币,直接用资金池内的资金 channel.vault = uint96(vault - reward); // 奖励矿币 _unfreeze(balances, channel.reward, reward, accountIndex); } /// @dev View the number of assets specified by the user /// @param tokenAddress Destination token address /// @param addr Destination address /// @return Number of assets function balanceOf(address tokenAddress, address addr) external view override returns (uint) { return _accounts[_accountMapping[addr]].balances[tokenAddress].value; } /// @dev Withdraw assets /// @param tokenAddress Destination token address /// @param value The value to withdraw function withdraw(address tokenAddress, uint value) external override { // The user's locked nest and the mining pool's nest are stored together. When the nest is mined over, // the problem of taking the locked nest as the ore drawing will appear // As it will take a long time for nest to finish mining, this problem will not be considered for the time being UINT storage balance = _accounts[_accountMapping[msg.sender]].balances[tokenAddress]; //uint balanceValue = balance.value; //require(balanceValue >= value, "NM:!balance"); balance.value -= value; TransferHelper.safeTransfer(tokenAddress, msg.sender, value); } /// @dev Estimated mining amount /// @param channelId 报价通道编号 /// @return Estimated mining amount function estimate(uint channelId) external view override returns (uint) { PriceChannel storage channel = _channels[channelId]; PriceSheet[] storage sheets = channel.pairs[0].sheets; uint index = sheets.length; uint blocks = 10; while (index > 0) { PriceSheet memory sheet = sheets[--index]; if (uint(sheet.shares) > 0) { blocks = block.number - uint(sheet.height); break; } } return blocks * uint(channel.rewardPerBlock) * _reduction(block.number - uint(channel.genesisBlock), uint(channel.reductionRate)) / 400; } /// @dev Query the quantity of the target quotation /// @param channelId 报价通道编号 /// @param index The index of the sheet /// @return minedBlocks Mined block period from previous block /// @return totalShares Total shares of sheets in the block function getMinedBlocks( uint channelId, uint index ) external view override returns (uint minedBlocks, uint totalShares) { PriceSheet[] storage sheets = _channels[channelId].pairs[0].sheets; PriceSheet memory sheet = sheets[index]; // The bite sheet or ntoken sheet doesn't mining if (uint(sheet.shares) == 0) { return (0, 0); } return _calcMinedBlocks(sheets, index, sheet); } /// @dev The function returns eth rewards of specified ntoken /// @param channelId 报价通道编号 function totalETHRewards(uint channelId) external view override returns (uint) { return uint(_channels[channelId].rewards); } /// @dev Pay /// @param channelId 报价通道编号 /// @param to Address to receive /// @param value Amount to receive function pay(uint channelId, address to, uint value) external override { PriceChannel storage channel = _channels[channelId]; require(channel.governance == msg.sender, "NOM:!governance"); channel.rewards -= _toUInt96(value); // pay payable(to).transfer(value); } /// @dev 向DAO捐赠 /// @param channelId 报价通道 /// @param value Amount to receive function donate(uint channelId, uint value) external override { PriceChannel storage channel = _channels[channelId]; require(channel.governance == msg.sender, "NOM:!governance"); channel.rewards -= _toUInt96(value); INestLedger(INestMapping(_governance).getNestLedgerAddress()).addETHReward { value: value } (channelId); } /// @dev Gets the address corresponding to the given index number /// @param index The index number of the specified address /// @return The address corresponding to the given index number function indexAddress(uint index) public view returns (address) { return _accounts[index].addr; } /// @dev Gets the registration index number of the specified address /// @param addr Destination address /// @return 0 means nonexistent, non-0 means index number function getAccountIndex(address addr) external view returns (uint) { return _accountMapping[addr]; } /// @dev Get the length of registered account array /// @return The length of registered account array function getAccountCount() external view returns (uint) { return _accounts.length; } // Convert PriceSheet to PriceSheetView function _toPriceSheetView(PriceSheet memory sheet, uint index) private view returns (PriceSheetView memory) { return PriceSheetView( // Index number uint32(index), // Miner address indexAddress(sheet.miner), // The block number of this price sheet packaged sheet.height, // The remain number of this price sheet sheet.remainNum, // The eth number which miner will got sheet.ethNumBal, // The eth number which equivalent to token's value which miner will got sheet.tokenNumBal, // The pledged number of nest in this sheet. (Unit: 1000nest) sheet.nestNum1k, // The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses // bite price sheet sheet.level, // Post fee shares sheet.shares, // Price uint152(_decodeFloat(sheet.priceFloat)) ); } // Create price sheet function _create( PriceSheet[] storage sheets, uint accountIndex, uint32 ethNum, uint nestNum1k, uint level_shares, uint equivalent ) private { sheets.push(PriceSheet( uint32(accountIndex), // uint32 miner; uint32(block.number), // uint32 height; ethNum, // uint32 remainNum; ethNum, // uint32 ethNumBal; ethNum, // uint32 tokenNumBal; uint24(nestNum1k), // uint32 nestNum1k; uint8(level_shares >> 8), // uint8 level; uint8(level_shares & 0xFF), _encodeFloat(equivalent) )); } // Calculate price, average price and volatility function _stat(Config memory config, PricePair storage pair) private { PriceSheet[] storage sheets = pair.sheets; // Load token price information PriceInfo memory p0 = pair.price; // Length of sheets uint length = sheets.length; // The index of the sheet to be processed in the sheet array uint index = uint(p0.index); // The latest block number for which the price has been calculated uint prev = uint(p0.height); // It's not necessary to load the price information in p0 // Eth count variable used to calculate price uint totalEthNum = 0; // Token count variable for price calculation uint totalTokenValue = 0; // Block number of current sheet uint height = 0; // Traverse the sheets to find the effective price //uint effectBlock = block.number - uint(config.priceEffectSpan); PriceSheet memory sheet; for (; ; ++index) { // Gas attack analysis, each post transaction, calculated according to post, needs to write // at least one sheet and freeze two kinds of assets, which needs to consume at least 30000 gas, // In addition to the basic cost of the transaction, at least 50000 gas is required. // In addition, there are other reading and calculation operations. The gas consumed by each // transaction is impossible less than 70000 gas, The attacker can accumulate up to 20 blocks // of sheets to be generated. To ensure that the calculation can be completed in one block, // it is necessary to ensure that the consumption of each price does not exceed 70000 / 20 = 3500 gas, // According to the current logic, each calculation of a price needs to read a storage unit (800) // and calculate the consumption, which can not reach the dangerous value of 3500, so the gas attack // is not considered // Traverse the sheets that has reached the effective interval from the current position bool flag = index >= length || (height = uint((sheet = sheets[index]).height)) + uint(config.priceEffectSpan) >= block.number; // Not the same block (or flag is false), calculate the price and update it if (flag || prev != height) { // totalEthNum > 0 Can calculate the price if (totalEthNum > 0) { // Calculate average price and Volatility // Calculation method of volatility of follow-up price uint tmp = _decodeFloat(p0.priceFloat); // New price uint price = totalTokenValue / totalEthNum; // Update price p0.remainNum = uint32(totalEthNum); p0.priceFloat = _encodeFloat(price); // Clear cumulative values totalEthNum = 0; totalTokenValue = 0; if (tmp > 0) { // Calculate average price // avgPrice[i + 1] = avgPrice[i] * 90% + price[i] * 10% p0.avgFloat = _encodeFloat((_decodeFloat(p0.avgFloat) * 9 + price) / 10); // When the accuracy of the token is very high or the value of the token relative to // eth is very low, the price may be very large, and there may be overflow problem, // it is not considered for the moment tmp = (price << 48) / tmp; if (tmp > 0x1000000000000) { tmp = tmp - 0x1000000000000; } else { tmp = 0x1000000000000 - tmp; } // earn = price[i] / price[i - 1] - 1; // seconds = time[i] - time[i - 1]; // sigmaSQ[i + 1] = sigmaSQ[i] * 90% + (earn ^ 2 / seconds) * 10% tmp = ( uint(p0.sigmaSQ) * 9 + // It is inevitable that prev greater than p0.height ((tmp * tmp / ETHEREUM_BLOCK_TIMESPAN / (prev - uint(p0.height))) >> 48) ) / 10; // The current implementation assumes that the volatility cannot exceed 1, and // corresponding to this, when the calculated value exceeds 1, expressed as 0xFFFFFFFFFFFF if (tmp > 0xFFFFFFFFFFFF) { tmp = 0xFFFFFFFFFFFF; } p0.sigmaSQ = uint48(tmp); } // The calculation methods of average price and volatility are different for first price else { // The average price is equal to the price //p0.avgTokenAmount = uint64(price); p0.avgFloat = p0.priceFloat; // The volatility is 0 p0.sigmaSQ = uint48(0); } // Update price block number p0.height = uint32(prev); } // Move to new block number prev = height; } if (flag) { break; } // Cumulative price information totalEthNum += uint(sheet.remainNum); totalTokenValue += _decodeFloat(sheet.priceFloat) * uint(sheet.remainNum); } // Update price information if (index > uint(p0.index)) { p0.index = uint32(index); pair.price = p0; } } // Calculation number of blocks which mined function _calcMinedBlocks( PriceSheet[] storage sheets, uint index, PriceSheet memory sheet ) private view returns (uint minedBlocks, uint totalShares) { uint length = sheets.length; uint height = uint(sheet.height); totalShares = uint(sheet.shares); // Backward looking for sheets in the same block for (uint i = index; ++i < length && uint(sheets[i].height) == height;) { // Multiple sheets in the same block is a small probability event at present, so it can be ignored // to read more than once, if there are always multiple sheets in the same block, it means that the // sheets are very intensive, and the gas consumed here does not have a great impact totalShares += uint(sheets[i].shares); } //i = index; // Find sheets in the same block forward uint prev = height; while (index > 0 && uint(prev = sheets[--index].height) == height) { // Multiple sheets in the same block is a small probability event at present, so it can be ignored // to read more than once, if there are always multiple sheets in the same block, it means that the // sheets are very intensive, and the gas consumed here does not have a great impact totalShares += uint(sheets[index].shares); } if (index > 0 || height > prev) { minedBlocks = height - prev; } else { minedBlocks = 10; } } /// @dev freeze token /// @param balances Balances ledger /// @param tokenAddress Destination token address /// @param tokenValue token amount /// @param value 剩余的eth数量 function _freeze( mapping(address=>UINT) storage balances, address tokenAddress, uint tokenValue, uint value ) private returns (uint) { if (tokenAddress == address(0)) { return value - tokenValue; } else { // Unfreeze nest UINT storage balance = balances[tokenAddress]; uint balanceValue = balance.value; if (balanceValue < tokenValue) { balance.value = 0; TransferHelper.safeTransferFrom(tokenAddress, msg.sender, address(this), tokenValue - balanceValue); } else { balance.value = balanceValue - tokenValue; } return value; } } function _unfreeze( mapping(address=>UINT) storage balances, address tokenAddress, uint tokenValue, uint accountIndex ) private { if (tokenValue > 0) { if (tokenAddress == address(0)) { payable(indexAddress(accountIndex)).transfer(tokenValue); } else { balances[tokenAddress].value += tokenValue; } } } function _unfreeze( mapping(address=>UINT) storage balances, address tokenAddress, uint tokenValue, address owner ) private { if (tokenValue > 0) { if (tokenAddress == address(0)) { payable(owner).transfer(tokenValue); } else { balances[tokenAddress].value += tokenValue; } } } /// @dev Gets the index number of the specified address. If it does not exist, register /// @param addr Destination address /// @return The index number of the specified address function _addressIndex(address addr) private returns (uint) { uint index = _accountMapping[addr]; if (index == 0) { // If it exceeds the maximum number that 32 bits can store, you can't continue to register a new account. // If you need to support a new account, you need to update the contract require((_accountMapping[addr] = index = _accounts.length) < 0x100000000, "NM:!accounts"); _accounts.push().addr = addr; } return index; } // // Calculation of attenuation gradient // function _reduction(uint delta) private pure returns (uint) { // if (delta < NEST_REDUCTION_LIMIT) { // return (NEST_REDUCTION_STEPS >> ((delta / NEST_REDUCTION_SPAN) << 4)) & 0xFFFF; // } // return (NEST_REDUCTION_STEPS >> 160) & 0xFFFF; // } function _reduction(uint delta, uint reductionRate) private pure returns (uint) { if (delta < NEST_REDUCTION_LIMIT) { uint n = delta / NEST_REDUCTION_SPAN; return 400 * reductionRate ** n / 10000 ** n; } return 400 * reductionRate ** 10 / 10000 ** 10; } /* ========== Tools and methods ========== */ /// @dev Encode the uint value as a floating-point representation in the form of fraction * 16 ^ exponent /// @param value Destination uint value /// @return float format function _encodeFloat(uint value) private pure returns (uint56) { uint exponent = 0; while (value > 0x3FFFFFFFFFFFF) { value >>= 4; ++exponent; } return uint56((value << 6) | exponent); } /// @dev Decode the floating-point representation of fraction * 16 ^ exponent to uint /// @param floatValue fraction value /// @return decode format function _decodeFloat(uint56 floatValue) private pure returns (uint) { return (uint(floatValue) >> 6) << ((uint(floatValue) & 0x3F) << 2); } // 将uint转为uint96 function _toUInt96(uint value) internal pure returns (uint96) { require(value < 1000000000000000000000000); return uint96(value); } /* ========== 价格查询 ========== */ /// @dev Get the latest trigger price /// @param pair 报价对 /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function _triggeredPrice(PricePair storage pair) internal view returns (uint blockNumber, uint price) { PriceInfo memory priceInfo = pair.price; if (uint(priceInfo.remainNum) > 0) { return (uint(priceInfo.height) + uint(_config.priceEffectSpan), _decodeFloat(priceInfo.priceFloat)); } return (0, 0); } /// @dev Get the full information of latest trigger price /// @param pair 报价对 /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function _triggeredPriceInfo(PricePair storage pair) internal view returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ ) { PriceInfo memory priceInfo = pair.price; if (uint(priceInfo.remainNum) > 0) { return ( uint(priceInfo.height) + uint(_config.priceEffectSpan), _decodeFloat(priceInfo.priceFloat), _decodeFloat(priceInfo.avgFloat), (uint(priceInfo.sigmaSQ) * 1 ether) >> 48 ); } return (0, 0, 0, 0); } /// @dev Find the price at block number /// @param pair 报价对 /// @param height Destination block number /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function _findPrice( PricePair storage pair, uint height ) internal view returns (uint blockNumber, uint price) { PriceSheet[] storage sheets = pair.sheets; uint priceEffectSpan = uint(_config.priceEffectSpan); uint length = sheets.length; uint index = 0; uint sheetHeight; height -= priceEffectSpan; { // If there is no sheet in this channel, length is 0, length - 1 will overflow, uint right = length - 1; uint left = 0; // Find the index use Binary Search while (left < right) { index = (left + right) >> 1; sheetHeight = uint(sheets[index].height); if (height > sheetHeight) { left = ++index; } else if (height < sheetHeight) { // When index = 0, this statement will have an underflow exception, which usually // indicates that the effective block height passed during the call is lower than // the block height of the first quotation right = --index; } else { break; } } } // Calculate price uint totalEthNum = 0; uint totalTokenValue = 0; uint h = 0; uint remainNum; PriceSheet memory sheet; // Find sheets forward for (uint i = index; i < length;) { sheet = sheets[i++]; sheetHeight = uint(sheet.height); if (height < sheetHeight) { break; } remainNum = uint(sheet.remainNum); if (remainNum > 0) { if (h == 0) { h = sheetHeight; } else if (h != sheetHeight) { break; } totalEthNum += remainNum; totalTokenValue += _decodeFloat(sheet.priceFloat) * remainNum; } } // Find sheets backward while (index > 0) { sheet = sheets[--index]; remainNum = uint(sheet.remainNum); if (remainNum > 0) { sheetHeight = uint(sheet.height); if (h == 0) { h = sheetHeight; } else if (h != sheetHeight) { break; } totalEthNum += remainNum; totalTokenValue += _decodeFloat(sheet.priceFloat) * remainNum; } } if (totalEthNum > 0) { return (h + priceEffectSpan, totalTokenValue / totalEthNum); } return (0, 0); } /// @dev Get the last (num) effective price /// @param pair 报价对 /// @param count The number of prices that want to return /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price function _lastPriceList(PricePair storage pair, uint count) internal view returns (uint[] memory) { PriceSheet[] storage sheets = pair.sheets; PriceSheet memory sheet; uint[] memory array = new uint[](count <<= 1); uint priceEffectSpan = uint(_config.priceEffectSpan); //uint h = block.number - priceEffectSpan; uint index = sheets.length; uint totalEthNum = 0; uint totalTokenValue = 0; uint height = 0; for (uint i = 0; i < count;) { bool flag = index == 0; if (flag || height != uint((sheet = sheets[--index]).height)) { if (totalEthNum > 0 && height + priceEffectSpan < block.number) { array[i++] = height + priceEffectSpan; array[i++] = totalTokenValue / totalEthNum; } if (flag) { break; } totalEthNum = 0; totalTokenValue = 0; height = uint(sheet.height); } uint remainNum = uint(sheet.remainNum); totalEthNum += remainNum; totalTokenValue += _decodeFloat(sheet.priceFloat) * remainNum; } return array; } } // File contracts/NestBatchPlatform2.sol // GPL-3.0-or-later pragma solidity ^0.8.6; // 支持pairIndex数组,可以一次性查询多个价格 /// @dev This contract implemented the mining logic of nest contract NestBatchPlatform2 is NestBatchMining, INestBatchPriceView, INestBatchPrice2 { /* ========== INestBatchPriceView ========== */ /// @dev Get the latest trigger price /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function triggeredPrice(uint channelId, uint pairIndex) external view override noContract returns (uint blockNumber, uint price) { return _triggeredPrice(_channels[channelId].pairs[pairIndex]); } /// @dev Get the full information of latest trigger price /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo(uint channelId, uint pairIndex) external view override noContract returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ ) { return _triggeredPriceInfo(_channels[channelId].pairs[pairIndex]); } /// @dev Find the price at block number /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param height Destination block number /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function findPrice( uint channelId, uint pairIndex, uint height ) external view override noContract returns (uint blockNumber, uint price) { return _findPrice(_channels[channelId].pairs[pairIndex], height); } // /// @dev Get the latest effective price // /// @param channelId 报价通道编号 // /// @param pairIndex 报价对编号 // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // function latestPrice(uint channelId, uint pairIndex) external view override noContract returns (uint blockNumber, uint price) { // return _latestPrice(_channels[channelId].pairs[pairIndex]); // } /// @dev Get the last (num) effective price /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param count The number of prices that want to return /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price function lastPriceList(uint channelId, uint pairIndex, uint count) external view override noContract returns (uint[] memory) { return _lastPriceList(_channels[channelId].pairs[pairIndex], count); } /// @dev Returns lastPriceList and triggered price info /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param count The number of prices that want to return /// @return prices An array which length is num * 2, each two element expresses one price like blockNumber|price /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation /// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to /// 999999999999996447, it means that the volatility has exceeded the range that can be expressed function lastPriceListAndTriggeredPriceInfo(uint channelId, uint pairIndex, uint count) external view override noContract returns ( uint[] memory prices, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ) { //return _lastPriceListAndTriggeredPriceInfo(_channels[channelId].pairs[pairIndex], count); PricePair storage pair = _channels[channelId].pairs[pairIndex]; prices = _lastPriceList(pair, count); ( triggeredPriceBlockNumber, triggeredPriceValue, triggeredAvgPrice, triggeredSigmaSQ ) = _triggeredPriceInfo(pair); } /* ========== INestBatchPrice ========== */ /// @dev Get the latest trigger price /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 价格数组, i * 2 为第i个价格所在区块, i * 2 + 1 为第i个价格 function triggeredPrice( uint channelId, uint[] calldata pairIndices, address payback ) external payable override returns (uint[] memory prices) { PricePair[0xFFFF] storage pairs = _pay(channelId, payback).pairs; uint n = pairIndices.length << 1; prices = new uint[](n); while (n > 0) { n -= 2; (prices[n], prices[n + 1]) = _triggeredPrice(pairs[pairIndices[n >> 1]]); } } /// @dev Get the full information of latest trigger price /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 价格数组, i * 4 为第i个价格所在区块, i * 4 + 1 为第i个价格, i * 4 + 2 为第i个平均价格, i * 4 + 3 为第i个波动率 function triggeredPriceInfo( uint channelId, uint[] calldata pairIndices, address payback ) external payable override returns (uint[] memory prices) { PricePair[0xFFFF] storage pairs = _pay(channelId, payback).pairs; uint n = pairIndices.length << 2; prices = new uint[](n); while (n > 0) { n -= 4; (prices[n], prices[n + 1], prices[n + 2], prices[n + 3]) = _triggeredPriceInfo(pairs[pairIndices[n >> 2]]); } } /// @dev Find the price at block number /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param height Destination block number /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 价格数组, i * 2 为第i个价格所在区块, i * 2 + 1 为第i个价格 function findPrice( uint channelId, uint[] calldata pairIndices, uint height, address payback ) external payable override returns (uint[] memory prices) { PricePair[0xFFFF] storage pairs = _pay(channelId, payback).pairs; uint n = pairIndices.length << 1; prices = new uint[](n); while (n > 0) { n -= 2; (prices[n], prices[n + 1]) = _findPrice(pairs[pairIndices[n >> 1]], height); } } // /// @dev Get the latest effective price // /// @param channelId 报价通道编号 // /// @param pairIndices 报价对编号 // /// @param payback 如果费用有多余的,则退回到此地址 // /// @return prices 价格数组, i * 2 为第i个价格所在区块, i * 2 + 1 为第i个价格 // function latestPrice( // uint channelId, // uint[] calldata pairIndices, // address payback // ) external payable override returns (uint[] memory prices) { // PricePair[0xFFFF] storage pairs = _pay(channelId, payback).pairs; // uint n = pairIndices.length << 1; // prices = new uint[](n); // while (n > 0) { // n -= 2; // (prices[n], prices[n + 1]) = _latestPrice(pairs[pairIndices[n >> 1]]); // } // } /// @dev Get the last (num) effective price /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param count The number of prices that want to return /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 结果数组,第 i * count * 2 到 (i + 1) * count * 2 - 1为第i组报价对的价格结果 function lastPriceList( uint channelId, uint[] calldata pairIndices, uint count, address payback ) external payable override returns (uint[] memory prices) { PricePair[0xFFFF] storage pairs = _pay(channelId, payback).pairs; uint row = count << 1; uint n = pairIndices.length * row; prices = new uint[](n); while (n > 0) { n -= row; uint[] memory pi = _lastPriceList(pairs[pairIndices[n / row]], count); for (uint i = 0; i < row; ++i) { prices[n + i] = pi[i]; } } } /// @dev Returns lastPriceList and triggered price info /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param count The number of prices that want to return /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 结果数组,第 i * (count * 2 + 4)到 (i + 1) * (count * 2 + 4)- 1为第i组报价对的价格结果 /// 其中前count * 2个为最新价格,后4个依次为:触发价格区块号,触发价格,平均价格,波动率 function lastPriceListAndTriggeredPriceInfo( uint channelId, uint[] calldata pairIndices, uint count, address payback ) external payable override returns (uint[] memory prices) { PricePair[0xFFFF] storage pairs = _pay(channelId, payback).pairs; uint row = (count << 1) + 4; uint n = pairIndices.length * row; prices = new uint[](n); while (n > 0) { n -= row; PricePair storage pair = pairs[pairIndices[n / row]]; uint[] memory pi = _lastPriceList(pair, count); for (uint i = 0; i + 4 < row; ++i) { prices[n + i] = pi[i]; } uint j = n + row - 4; ( prices[j], prices[j + 1], prices[j + 2], prices[j + 3] ) = _triggeredPriceInfo(pair); } } // Payment of transfer fee function _pay(uint channelId, address payback) private returns (PriceChannel storage channel) { channel = _channels[channelId]; uint fee = uint(channel.singleFee) * DIMI_ETHER; if (msg.value > fee) { payable(payback).transfer(msg.value - fee); // TODO: BSC上采用的是老的gas计算策略,直接转账可能导致代理合约gas超出,要改用下面的方式转账 //TransferHelper.safeTransferETH(payback, msg.value - fee); } else { require(msg.value == fee, "NOP:!fee"); } channel.rewards += _toUInt96(fee); } }
开通报价通道 config 报价通道配置 计价代币 矿币 触发开通事件 计价代币 计价代币单位 矿币 单位区块出矿币数量 Post fee(0.0001eth,DIMI_ETHER). 1000 管理地址 创世区块 Single query fee (0.0001 ether, DIMI_ETHER). 100 衰减系数,万分制。8000 遍历创建报价对
function open(ChannelConfig calldata config) external override { address token0 = config.token0; address reward = config.reward; emit Open(_channels.length, token0, config.unit, reward); PriceChannel storage channel = _channels.push(); channel.token0 = token0; channel.unit = config.unit; channel.reward = reward; channel.rewardPerBlock = config.rewardPerBlock; channel.vault = uint128(0); channel.rewards = uint96(0); channel.postFeeUnit = config.postFeeUnit; channel.count = uint16(config.tokens.length); channel.governance = msg.sender; channel.genesisBlock = uint32(block.number); channel.singleFee = config.singleFee; channel.reductionRate = config.reductionRate; for (uint i = 0; i < config.tokens.length; ++i) { require(token0 != config.tokens[i], "NOM:token can't equal token0"); for (uint j = 0; j < i; ++j) { require(config.tokens[i] != config.tokens[j], "NOM:token reiterated"); } channel.pairs[i].target = config.tokens[i]; } }
6,699,933
./partial_match/1/0x694532928Af9288F83AACBa5B932caf51fEC22d5/sources/Vat.sol
--- CDP Manipulation --- system is live ilk has been initialised either debt has decreased, or debt ceilings are not exceeded urn is either less risky than before, or it is safe urn is either more safe, or the owner consents collateral src consents debt dst consents urn has no debt, or a non-dusty amount
function frob(bytes32 i, address u, address v, address w, int dink, int dart) external note { require(live == 1, "Vat/not-live"); Urn memory urn = urns[i][u]; Ilk memory ilk = ilks[i]; require(ilk.rate != 0, "Vat/ilk-not-init"); urn.ink = add(urn.ink, dink); urn.art = add(urn.art, dart); ilk.Art = add(ilk.Art, dart); int dtab = mul(ilk.rate, dart); uint tab = mul(ilk.rate, urn.art); debt = add(debt, dtab); require(either(dart <= 0, both(mul(ilk.Art, ilk.rate) <= ilk.line, debt <= Line)), "Vat/ceiling-exceeded"); require(either(both(dart <= 0, dink >= 0), tab <= mul(urn.ink, ilk.spot)), "Vat/not-safe"); require(either(both(dart <= 0, dink >= 0), wish(u, msg.sender)), "Vat/not-allowed-u"); require(either(dink <= 0, wish(v, msg.sender)), "Vat/not-allowed-v"); require(either(dart >= 0, wish(w, msg.sender)), "Vat/not-allowed-w"); require(either(urn.art == 0, tab >= ilk.dust), "Vat/dust"); gem[i][v] = sub(gem[i][v], dink); dai[w] = add(dai[w], dtab); urns[i][u] = urn; ilks[i] = ilk; }
2,607,068
pragma solidity ^0.5.16; import "./Context.sol"; import "./Math.sol"; import "./SafeERC20.sol"; import "./Ownable.sol"; contract TokenDispenserBase is Context, Ownable { using KineSafeMath for uint; using SafeERC20 for IERC20; event TransferAllocation(address indexed sender, address indexed recipient, uint amount); event AddAllocation(address indexed recipient, uint addAllocation, uint newAllocation); event ReplaceAllocation(address indexed oldAddress, address indexed newAddress, uint allocation); event TransferPaused(); event TransferUnpaused(); event AddTransferWhitelist(address account); event RemoveTransferWhitelist(address account); IERC20 kine; uint public startTime; uint public vestedPerAllocationStored; uint public lastUpdateTime; uint public totalAllocation; mapping(address => uint) public accountAllocations; struct AccountVestedDetail { uint vestedPerAllocationUpdated; uint accruedVested; uint claimed; } mapping(address => AccountVestedDetail) public accountVestedDetails; uint public totalClaimed; bool public transferPaused; // @dev transfer whitelist maintains a list of accounts that can receive allocations // owner transfer isn't limitted by this whitelist mapping(address => bool) public transferWhitelist; modifier onlyAfterStart() { require(block.timestamp >= startTime, "not started yet"); _; } modifier onlyInTransferWhitelist(address account) { require(transferWhitelist[account], "receipient not in transfer whitelist"); _; } modifier updateVested(address account) { updateVestedInternal(account); _; } modifier onlyTransferNotPaused() { require(!transferPaused, "transfer paused"); _; } modifier onlyTransferPaused() { require(transferPaused, "transfer not paused"); _; } function updateVestedInternal(address account) internal { vestedPerAllocationStored = vestedPerAllocation(); lastUpdateTime = block.timestamp; if (account != address(0)) { accountVestedDetails[account].accruedVested = vested(account); accountVestedDetails[account].vestedPerAllocationUpdated = vestedPerAllocationStored; } } // @dev should be implemented by inheritent contract function vestedPerAllocation() public view returns (uint); function vested(address account) public view returns (uint) { return accountAllocations[account] .mul(vestedPerAllocation().sub(accountVestedDetails[account].vestedPerAllocationUpdated)) .div(1e18) .add(accountVestedDetails[account].accruedVested); } function claimed(address account) public view returns (uint) { return accountVestedDetails[account].claimed; } function claim() external onlyAfterStart updateVested(msg.sender) { AccountVestedDetail storage detail = accountVestedDetails[msg.sender]; uint accruedVested = detail.accruedVested; if (accruedVested > 0) { detail.claimed = detail.claimed.add(accruedVested); totalClaimed = totalClaimed.add(accruedVested); detail.accruedVested = 0; kine.safeTransfer(msg.sender, accruedVested); } } // @notice User may transfer part or full of its allocations to others. // The vested tokens right before transfer belongs to the user account, and the to-be vested tokens will belong to recipient after transfer. // Transfer will revert if transfer is paused by owner. // Only whitelisted account may transfer their allocations. function transferAllocation(address recipient, uint amount) external onlyTransferNotPaused onlyInTransferWhitelist(recipient) updateVested(msg.sender) updateVested(recipient) returns (bool) { address payable sender = _msgSender(); require(sender != address(0), "transfer from the zero address"); require(recipient != address(0), "transfer to the zero address"); accountAllocations[sender] = accountAllocations[sender].sub(amount, "transfer amount exceeds balance"); accountAllocations[recipient] = accountAllocations[recipient].add(amount); emit TransferAllocation(sender, recipient, amount); return true; } ////////////////////////////////////////// // allocation management by owner // @notice Only owner may add allocations to accounts. // When owner add allocations to recipients after distribution start time, recipients can only recieve partial tokens. function addAllocation(address[] calldata recipients, uint[] calldata allocations) external onlyOwner { require(recipients.length == allocations.length, "recipients and allocations length not match"); if (block.timestamp <= startTime) { // if distribution has't start, just add allocations to recipients for (uint i = 0; i < recipients.length; i++) { accountAllocations[recipients[i]] = accountAllocations[recipients[i]].add(allocations[i]); totalAllocation = totalAllocation.add(allocations[i]); transferWhitelist[recipients[i]] = true; emit AddAllocation(recipients[i], allocations[i], accountAllocations[recipients[i]]); emit AddTransferWhitelist(recipients[i]); } } else { // if distribution already started, need to update recipients vested allocations before add allocations for (uint i = 0; i < recipients.length; i++) { updateVestedInternal(recipients[i]); accountAllocations[recipients[i]] = accountAllocations[recipients[i]].add(allocations[i]); totalAllocation = totalAllocation.add(allocations[i]); transferWhitelist[recipients[i]] = true; emit AddAllocation(recipients[i], allocations[i], accountAllocations[recipients[i]]); emit AddTransferWhitelist(recipients[i]); } } } ////////////////////////////////////////////// // transfer management by owner function pauseTransfer() external onlyOwner onlyTransferNotPaused { transferPaused = true; emit TransferPaused(); } function unpauseTransfer() external onlyOwner onlyTransferPaused { transferPaused = false; emit TransferUnpaused(); } // @notice Owner is able to transfer allocation between any accounts in case special cases happened, e.g. someone lost their address/key. // However, the vested tokens before transfer will remain in the account before transfer. // Onwer transfer is not limited by the transfer pause status. function transferAllocationFrom(address from, address recipient, uint amount) external onlyOwner updateVested(from) updateVested(recipient) returns (bool) { require(from != address(0), "transfer from the zero address"); require(recipient != address(0), "transfer to the zero address"); accountAllocations[from] = accountAllocations[from].sub(amount, "transfer amount exceeds balance"); accountAllocations[recipient] = accountAllocations[recipient].add(amount); emit TransferAllocation(from, recipient, amount); return true; } // @notice Owner is able to replace accountVestedDetails address with a new one, in case of receipient give us an unoperateable address (like exchange address) // The unclaimed allocations will all be transferred to new address including the vest status. function replaceAccountWith(address oldAddress, address newAddress) external onlyOwner { require(oldAddress != address(0), "replace from the zero address"); require(newAddress != address(0), "replace to the zero address"); uint allocation = accountAllocations[oldAddress]; AccountVestedDetail memory avd = accountVestedDetails[oldAddress]; AccountVestedDetail storage navd = accountVestedDetails[newAddress]; require(accountAllocations[newAddress] == 0, "new address already has allocation"); require(navd.vestedPerAllocationUpdated == 0, "new address already has vestedPerAllocationUpdated"); accountAllocations[newAddress] = allocation; navd.accruedVested = avd.accruedVested; navd.vestedPerAllocationUpdated = avd.vestedPerAllocationUpdated; navd.claimed = avd.claimed; transferWhitelist[newAddress] = true; delete accountAllocations[oldAddress]; delete accountVestedDetails[oldAddress]; delete transferWhitelist[oldAddress]; emit RemoveTransferWhitelist(oldAddress); emit AddTransferWhitelist(newAddress); emit ReplaceAllocation(oldAddress, newAddress, allocation); } function addTransferWhitelist(address account) external onlyOwner { transferWhitelist[account] = true; emit AddTransferWhitelist(account); } function removeTransferWhitelist(address account) external onlyOwner { delete transferWhitelist[account]; emit RemoveTransferWhitelist(account); } }
Only owner may add allocations to accounts. When owner add allocations to recipients after distribution start time, recipients can only recieve partial tokens. if distribution has't start, just add allocations to recipients if distribution already started, need to update recipients vested allocations before add allocations
function addAllocation(address[] calldata recipients, uint[] calldata allocations) external onlyOwner { require(recipients.length == allocations.length, "recipients and allocations length not match"); if (block.timestamp <= startTime) { for (uint i = 0; i < recipients.length; i++) { accountAllocations[recipients[i]] = accountAllocations[recipients[i]].add(allocations[i]); totalAllocation = totalAllocation.add(allocations[i]); transferWhitelist[recipients[i]] = true; emit AddAllocation(recipients[i], allocations[i], accountAllocations[recipients[i]]); emit AddTransferWhitelist(recipients[i]); } for (uint i = 0; i < recipients.length; i++) { updateVestedInternal(recipients[i]); accountAllocations[recipients[i]] = accountAllocations[recipients[i]].add(allocations[i]); totalAllocation = totalAllocation.add(allocations[i]); transferWhitelist[recipients[i]] = true; emit AddAllocation(recipients[i], allocations[i], accountAllocations[recipients[i]]); emit AddTransferWhitelist(recipients[i]); } } }
12,964,904
./full_match/5/0x2fED5faFef6007bf27C72a835fa0971F2F698845/sources/browser/TINVtokencontract.sol
Add totalSupply to the owner address
function addTokenToTotalSupply(uint _value) public { require(_value > 0); balances[msg.sender] = balances[msg.sender] + _value; totalSupply_ = totalSupply_ + _value; }
1,921,458
./full_match/3/0xf4f349D166CD9E671798B12dC09A13e6E680e678/sources/contracts/DAdope_Token.sol
public if(whitelisted[msg.sender] != true) { }
function mint(address _to, uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused); require(_mintAmount > 0); require(_mintAmount <= maxMintAmount, "Max limit"); require(supply + _mintAmount <= maxSupply, "Max limit"); if (msg.sender != owner()) { require(msg.value >= cost * _mintAmount, "Value below price"); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(_to, supply + i); } }
14,230,200
/** *Submitted for verification at Etherscan.io on 2020-05-28 */ pragma solidity 0.5.16; pragma experimental ABIEncoderV2; interface MassetStructs { /** @dev Stores high level basket info */ struct Basket { /** @dev Array of Bassets currently active */ Basset[] bassets; /** @dev Max number of bAssets that can be present in any Basket */ uint8 maxBassets; /** @dev Some bAsset is undergoing re-collateralisation */ bool undergoingRecol; /** * @dev In the event that we do not raise enough funds from the auctioning of a failed Basset, * The Basket is deemed as failed, and is undercollateralised to a certain degree. * The collateralisation ratio is used to calc Masset burn rate. */ bool failed; uint256 collateralisationRatio; } /** @dev Stores bAsset info. The struct takes 5 storage slots per Basset */ struct Basset { /** @dev Address of the bAsset */ address addr; /** @dev Status of the basset, */ BassetStatus status; // takes uint8 datatype (1 byte) in storage /** @dev An ERC20 can charge transfer fee, for example USDT, DGX tokens. */ bool isTransferFeeCharged; // takes a byte in storage /** * @dev 1 Basset * ratio / ratioScale == x Masset (relative value) * If ratio == 10e8 then 1 bAsset = 10 mAssets * A ratio is divised as 10^(18-tokenDecimals) * measurementMultiple(relative value of 1 base unit) */ uint256 ratio; /** @dev Target weights of the Basset (100% == 1e18) */ uint256 maxWeight; /** @dev Amount of the Basset that is held in Collateral */ uint256 vaultBalance; } /** @dev Status of the Basset - has it broken its peg? */ enum BassetStatus { Default, Normal, BrokenBelowPeg, BrokenAbovePeg, Blacklisted, Liquidating, Liquidated, Failed } /** @dev Internal details on Basset */ struct BassetDetails { Basset bAsset; address integrator; uint8 index; } /** @dev All details needed to Forge with multiple bAssets */ struct ForgePropsMulti { bool isValid; // Flag to signify that forge bAssets have passed validity check Basset[] bAssets; address[] integrators; uint8[] indexes; } /** @dev All details needed for proportionate Redemption */ struct RedeemPropsMulti { uint256 colRatio; Basset[] bAssets; address[] integrators; uint8[] indexes; } } contract IForgeValidator is MassetStructs { function validateMint(uint256 _totalVault, Basset calldata _basset, uint256 _bAssetQuantity) external pure returns (bool, string memory); function validateMintMulti(uint256 _totalVault, Basset[] calldata _bassets, uint256[] calldata _bAssetQuantities) external pure returns (bool, string memory); function validateSwap(uint256 _totalVault, Basset calldata _inputBasset, Basset calldata _outputBasset, uint256 _quantity) external pure returns (bool, string memory, uint256, bool); function validateRedemption( bool basketIsFailed, uint256 _totalVault, Basset[] calldata _allBassets, uint8[] calldata _indices, uint256[] calldata _bassetQuantities) external pure returns (bool, string memory, bool); function calculateRedemptionMulti( uint256 _mAssetQuantity, Basset[] calldata _allBassets) external pure returns (bool, string memory, uint256[] memory); } interface IPlatformIntegration { /** * @dev Deposit the given bAsset to Lending platform * @param _bAsset bAsset address * @param _amount Amount to deposit */ function deposit(address _bAsset, uint256 _amount, bool isTokenFeeCharged) external returns (uint256 quantityDeposited); /** * @dev Withdraw given bAsset from Lending platform */ function withdraw(address _receiver, address _bAsset, uint256 _amount, bool _isTokenFeeCharged) external; /** * @dev Returns the current balance of the given bAsset */ function checkBalance(address _bAsset) external returns (uint256 balance); } contract IBasketManager is MassetStructs { /** @dev Setters for mAsset to update balances */ function increaseVaultBalance( uint8 _bAsset, address _integrator, uint256 _increaseAmount) external; function increaseVaultBalances( uint8[] calldata _bAsset, address[] calldata _integrator, uint256[] calldata _increaseAmount) external; function decreaseVaultBalance( uint8 _bAsset, address _integrator, uint256 _decreaseAmount) external; function decreaseVaultBalances( uint8[] calldata _bAsset, address[] calldata _integrator, uint256[] calldata _decreaseAmount) external; function collectInterest() external returns (uint256 interestCollected, uint256[] memory gains); /** @dev Setters for Gov to update Basket composition */ function addBasset( address _basset, address _integration, bool _isTransferFeeCharged) external returns (uint8 index); function setBasketWeights(address[] calldata _bassets, uint256[] calldata _weights) external; function setTransferFeesFlag(address _bAsset, bool _flag) external; /** @dev Getters to retrieve Basket information */ function getBasket() external view returns (Basket memory b); function prepareForgeBasset(address _token, uint256 _amt, bool _mint) external returns (bool isValid, BassetDetails memory bInfo); function prepareSwapBassets(address _input, address _output, bool _isMint) external view returns (bool, string memory, BassetDetails memory, BassetDetails memory); function prepareForgeBassets(address[] calldata _bAssets, uint256[] calldata _amts, bool _mint) external returns (ForgePropsMulti memory props); function prepareRedeemMulti() external view returns (RedeemPropsMulti memory props); function getBasset(address _token) external view returns (Basset memory bAsset); function getBassets() external view returns (Basset[] memory bAssets, uint256 len); /** @dev Recollateralisation */ function handlePegLoss(address _basset, bool _belowPeg) external returns (bool actioned); function negateIsolation(address _basset) external; } contract IMasset is MassetStructs { /** @dev Calc interest */ function collectInterest() external returns (uint256 massetMinted, uint256 newTotalSupply); /** @dev Minting */ function mint(address _basset, uint256 _bassetQuantity) external returns (uint256 massetMinted); function mintTo(address _basset, uint256 _bassetQuantity, address _recipient) external returns (uint256 massetMinted); function mintMulti(address[] calldata _bAssets, uint256[] calldata _bassetQuantity, address _recipient) external returns (uint256 massetMinted); /** @dev Swapping */ function swap( address _input, address _output, uint256 _quantity, address _recipient) external returns (uint256 output); function getSwapOutput( address _input, address _output, uint256 _quantity) external view returns (bool, string memory, uint256 output); /** @dev Redeeming */ function redeem(address _basset, uint256 _bassetQuantity) external returns (uint256 massetRedeemed); function redeemTo(address _basset, uint256 _bassetQuantity, address _recipient) external returns (uint256 massetRedeemed); function redeemMulti(address[] calldata _bAssets, uint256[] calldata _bassetQuantities, address _recipient) external returns (uint256 massetRedeemed); function redeemMasset(uint256 _mAssetQuantity, address _recipient) external; /** @dev Setters for the Manager or Gov to update module info */ function upgradeForgeValidator(address _newForgeValidator) external; /** @dev Setters for Gov to set system params */ function setSwapFee(uint256 _swapFee) external; /** @dev Getters */ function getBasketManager() external view returns(address); } /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall ; //inject UNINIT LOCAL/STATE VAR if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self ; //inject UNINIT LOCAL/STATE VAR uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c ; //inject UNINIT LOCAL/STATE VAR 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 ; //inject UNINIT LOCAL/STATE VAR 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 ; //inject UNINIT LOCAL/STATE VAR 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 ; //inject UNINIT LOCAL/STATE VAR // 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; } } /** * @dev Implementation of the {IERC20} interface. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } contract InitializableERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. * @notice To avoid variable shadowing appended `Arg` after arguments name. */ function _initialize(string memory nameArg, string memory symbolArg, uint8 decimalsArg) internal { _name = nameArg; _symbol = symbolArg; _decimals = decimalsArg; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } contract InitializableToken is ERC20, InitializableERC20Detailed { /** * @dev Initialization function for implementing contract * @notice To avoid variable shadowing appended `Arg` after arguments name. */ function _initialize(string memory _nameArg, string memory _symbolArg) internal { InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18); } } contract InitializableModuleKeys { // Governance // Phases bytes32 internal KEY_GOVERNANCE; // 2.x bytes32 internal KEY_STAKING; // 1.2 bytes32 internal KEY_PROXY_ADMIN; // 1.0 // mStable bytes32 internal KEY_ORACLE_HUB; // 1.2 bytes32 internal KEY_MANAGER; // 1.2 bytes32 internal KEY_RECOLLATERALISER; // 2.x bytes32 internal KEY_META_TOKEN; // 1.1 bytes32 internal KEY_SAVINGS_MANAGER; // 1.0 /** * @dev Initialize function for upgradable proxy contracts. This function should be called * via Proxy to initialize constants in the Proxy contract. */ function _initialize() internal { // keccak256() values are evaluated only once at the time of this function call. // Hence, no need to assign hard-coded values to these variables. KEY_GOVERNANCE = keccak256("Governance"); KEY_STAKING = keccak256("Staking"); KEY_PROXY_ADMIN = keccak256("ProxyAdmin"); KEY_ORACLE_HUB = keccak256("OracleHub"); KEY_MANAGER = keccak256("Manager"); KEY_RECOLLATERALISER = keccak256("Recollateraliser"); KEY_META_TOKEN = keccak256("MetaToken"); KEY_SAVINGS_MANAGER = keccak256("SavingsManager"); } } interface INexus { function governor() external view returns (address); function getModule(bytes32 key) external view returns (address); function proposeModule(bytes32 _key, address _addr) external; function cancelProposedModule(bytes32 _key) external; function acceptProposedModule(bytes32 _key) external; function acceptProposedModules(bytes32[] calldata _keys) external; function requestLockModule(bytes32 _key) external; function cancelLockModule(bytes32 _key) external; function lockModule(bytes32 _key) external; } contract InitializableModule is InitializableModuleKeys { INexus public nexus; /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyGovernor() { require(msg.sender == _governor(), "Only governor can execute"); _; } /** * @dev Modifier to allow function calls only from the Governance. * Governance is either Governor address or Governance address. */ modifier onlyGovernance() { require( msg.sender == _governor() || msg.sender == _governance(), "Only governance can execute" ); _; } /** * @dev Modifier to allow function calls only from the ProxyAdmin. */ modifier onlyProxyAdmin() { require( msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute" ); _; } /** * @dev Modifier to allow function calls only from the Manager. */ modifier onlyManager() { require(msg.sender == _manager(), "Only manager can execute"); _; } /** * @dev Initialization function for upgradable proxy contracts * @param _nexus Nexus contract address */ function _initialize(address _nexus) internal { require(_nexus != address(0), "Nexus address is zero"); nexus = INexus(_nexus); InitializableModuleKeys._initialize(); } /** * @dev Returns Governor address from the Nexus * @return Address of Governor Contract */ function _governor() internal view returns (address) { return nexus.governor(); } /** * @dev Returns Governance Module address from the Nexus * @return Address of the Governance (Phase 2) */ function _governance() internal view returns (address) { return nexus.getModule(KEY_GOVERNANCE); } /** * @dev Return Staking Module address from the Nexus * @return Address of the Staking Module contract */ function _staking() internal view returns (address) { return nexus.getModule(KEY_STAKING); } /** * @dev Return ProxyAdmin Module address from the Nexus * @return Address of the ProxyAdmin Module contract */ function _proxyAdmin() internal view returns (address) { return nexus.getModule(KEY_PROXY_ADMIN); } /** * @dev Return MetaToken Module address from the Nexus * @return Address of the MetaToken Module contract */ function _metaToken() internal view returns (address) { return nexus.getModule(KEY_META_TOKEN); } /** * @dev Return OracleHub Module address from the Nexus * @return Address of the OracleHub Module contract */ function _oracleHub() internal view returns (address) { return nexus.getModule(KEY_ORACLE_HUB); } /** * @dev Return Manager Module address from the Nexus * @return Address of the Manager Module contract */ function _manager() internal view returns (address) { return nexus.getModule(KEY_MANAGER); } /** * @dev Return SavingsManager Module address from the Nexus * @return Address of the SavingsManager Module contract */ function _savingsManager() internal view returns (address) { return nexus.getModule(KEY_SAVINGS_MANAGER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _recollateraliser() internal view returns (address) { return nexus.getModule(KEY_RECOLLATERALISER); } } contract InitializableReentrancyGuard { bool private _notEntered; function _initialize() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } library StableMath { using SafeMath for uint256; /** * @dev Scaling unit for use in specific calculations, * where 1 * 10**18, or 1e18 represents a unit '1' */ uint256 private constant FULL_SCALE = 1e18; /** * @notice Token Ratios are used when converting between units of bAsset, mAsset and MTA * Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold) * @dev bAsset ratio unit for use in exact calculations, * where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit */ uint256 private constant RATIO_SCALE = 1e8; /** * @dev Provides an interface to the scaling unit * @return Scaling unit (1e18 or 1 * 10**18) */ function getFullScale() internal pure returns (uint256) { return FULL_SCALE; } /** * @dev Provides an interface to the ratio unit * @return Ratio scale unit (1e8 or 1 * 10**8) */ function getRatioScale() internal pure returns (uint256) { return RATIO_SCALE; } /** * @dev Scales a given integer to the power of the full scale. * @param x Simple uint256 to scale * @return Scaled value a to an exact number */ function scaleInteger(uint256 x) internal pure returns (uint256) { return x.mul(FULL_SCALE); } /*************************************** PRECISE ARITHMETIC ****************************************/ /** * @dev Multiplies two precise units, and then truncates by the full scale * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) { return mulTruncateScale(x, y, FULL_SCALE); } /** * @dev Multiplies two precise units, and then truncates by the given scale. For example, * when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18 * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @param scale Scale unit * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncateScale(uint256 x, uint256 y, uint256 scale) internal pure returns (uint256) { // e.g. assume scale = fullScale // z = 10e18 * 9e17 = 9e36 uint256 z ; //inject UNINIT LOCAL/STATE VAR // return 9e38 / 1e18 = 9e18 return z.div(scale); } /** * @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit, rounded up to the closest base unit. */ function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) { uint256 scaled ; //inject UNINIT LOCAL/STATE VAR uint256 ceil ; //inject UNINIT LOCAL/STATE VAR return ceil.div(FULL_SCALE); } /** * @dev Precisely divides two units, by first scaling the left hand operand. Useful * for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) * @param x Left hand input to division * @param y Right hand input to division * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z ; //inject UNINIT LOCAL/STATE VAR return z.div(y); } /*************************************** RATIO FUNCS ****************************************/ /** * @dev Multiplies and truncates a token ratio, essentially flooring the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand operand to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return Result after multiplying the two inputs and then dividing by the ratio scale */ function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) { return mulTruncateScale(x, ratio, RATIO_SCALE); } /** * @dev Multiplies and truncates a token ratio, rounding up the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand input to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return Result after multiplying the two inputs and then dividing by the shared * ratio scale, rounded up to the closest base unit. */ function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) { uint256 scaled ; //inject UNINIT LOCAL/STATE VAR uint256 ceil ; //inject UNINIT LOCAL/STATE VAR return ceil.div(RATIO_SCALE); } /** * @dev Precisely divides two ratioed units, by first scaling the left hand operand * i.e. How much bAsset is this mAsset worth? * @param x Left hand operand in division * @param ratio bAsset ratio * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) { uint256 y ; //inject UNINIT LOCAL/STATE VAR return y.div(ratio); } /*************************************** HELPERS ****************************************/ /** * @dev Calculates minimum of two numbers * @param x Left hand input * @param y Right hand input * @return Minimum of the two inputs */ function min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } /** * @dev Calculated maximum of two numbers * @param x Left hand input * @param y Right hand input * @return Maximum of the two inputs */ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? x : y; } /** * @dev Clamps a value to an upper bound * @param x Left hand input * @param upperBound Maximum possible value to return * @return Input x clamped to a maximum value, upperBound */ function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) { return x > upperBound ? upperBound : x; } } /** * @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 ; //inject UNINIT LOCAL/STATE VAR // 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"); } } 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 ; //inject UNINIT LOCAL/STATE VAR callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance ; //inject UNINIT LOCAL/STATE VAR 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 MassetHelpers { using StableMath for uint256; using SafeMath for uint256; using SafeERC20 for IERC20; function transferTokens( address _sender, address _recipient, address _basset, bool _erc20TransferFeeCharged, uint256 _qty ) internal returns (uint256 receivedQty) { receivedQty = _qty; if(_erc20TransferFeeCharged) { uint256 balBefore ; //inject UNINIT LOCAL/STATE VAR IERC20(_basset).safeTransferFrom(_sender, _recipient, _qty); uint256 balAfter ; //inject UNINIT LOCAL/STATE VAR receivedQty = StableMath.min(_qty, balAfter.sub(balBefore)); } else { IERC20(_basset).safeTransferFrom(_sender, _recipient, _qty); } } function safeInfiniteApprove(address _asset, address _spender) internal { IERC20(_asset).safeApprove(_spender, 0); IERC20(_asset).safeApprove(_spender, uint256(-1)); } } /** * @title Masset * @author Stability Labs Pty. Ltd. * @notice The Masset is a token that allows minting and redemption at a 1:1 ratio * for underlying basket assets (bAssets) of the same peg (i.e. USD, * EUR, Gold). Composition and validation is enforced via the BasketManager. * @dev VERSION: 1.0 * DATE: 2020-05-05 */ contract Masset is Initializable, IMasset, InitializableToken, InitializableModule, InitializableReentrancyGuard { using StableMath for uint256; // Forging Events event Minted(address indexed minter, address recipient, uint256 mAssetQuantity, address bAsset, uint256 bAssetQuantity); event MintedMulti(address indexed minter, address recipient, uint256 mAssetQuantity, address[] bAssets, uint256[] bAssetQuantities); event Swapped(address indexed swapper, address input, address output, uint256 outputAmount, address recipient); event Redeemed(address indexed redeemer, address recipient, uint256 mAssetQuantity, address[] bAssets, uint256[] bAssetQuantities); event RedeemedMasset(address indexed redeemer, address recipient, uint256 mAssetQuantity); event PaidFee(address indexed payer, address asset, uint256 feeQuantity); // State Events event SwapFeeChanged(uint256 fee); event ForgeValidatorChanged(address forgeValidator); // Modules and connectors IForgeValidator public forgeValidator; bool private forgeValidatorLocked; IBasketManager private basketManager; // Basic redemption fee information uint256 public swapFee; uint256 private MAX_FEE; /** * @dev Constructor * @notice To avoid variable shadowing appended `Arg` after arguments name. */ function initialize( string calldata _nameArg, string calldata _symbolArg, address _nexus, address _forgeValidator, address _basketManager ) external initializer { InitializableToken._initialize(_nameArg, _symbolArg); InitializableModule._initialize(_nexus); InitializableReentrancyGuard._initialize(); forgeValidator = IForgeValidator(_forgeValidator); basketManager = IBasketManager(_basketManager); MAX_FEE = 2e16; swapFee = 4e15; } /** * @dev Verifies that the caller is the Savings Manager contract */ modifier onlySavingsManager() { require(_savingsManager() == msg.sender, "Must be savings manager"); _; } /*************************************** MINTING (PUBLIC) ****************************************/ /** * @dev Mint a single bAsset, at a 1:1 ratio with the bAsset. This contract * must have approval to spend the senders bAsset * @param _bAsset Address of the bAsset to mint * @param _bAssetQuantity Quantity in bAsset units * @return massetMinted Number of newly minted mAssets */ function mint( address _bAsset, uint256 _bAssetQuantity ) external nonReentrant returns (uint256 massetMinted) { return _mintTo(_bAsset, _bAssetQuantity, msg.sender); } /** * @dev Mint a single bAsset, at a 1:1 ratio with the bAsset. This contract * must have approval to spend the senders bAsset * @param _bAsset Address of the bAsset to mint * @param _bAssetQuantity Quantity in bAsset units * @param _recipient receipient of the newly minted mAsset tokens * @return massetMinted Number of newly minted mAssets */ function mintTo( address _bAsset, uint256 _bAssetQuantity, address _recipient ) external nonReentrant returns (uint256 massetMinted) { return _mintTo(_bAsset, _bAssetQuantity, _recipient); } /** * @dev Mint with multiple bAssets, at a 1:1 ratio to mAsset. This contract * must have approval to spend the senders bAssets * @param _bAssets Non-duplicate address array of bAssets with which to mint * @param _bAssetQuantity Quantity of each bAsset to mint. Order of array * should mirror the above * @param _recipient Address to receive the newly minted mAsset tokens * @return massetMinted Number of newly minted mAssets */ function mintMulti( address[] calldata _bAssets, uint256[] calldata _bAssetQuantity, address _recipient ) external nonReentrant returns(uint256 massetMinted) { return _mintTo(_bAssets, _bAssetQuantity, _recipient); } /*************************************** MINTING (INTERNAL) ****************************************/ /** @dev Mint Single */ function _mintTo( address _bAsset, uint256 _bAssetQuantity, address _recipient ) internal returns (uint256 massetMinted) { require(_recipient != address(0), "Must be a valid recipient"); require(_bAssetQuantity > 0, "Quantity must not be 0"); (bool isValid, BassetDetails memory bInfo) = basketManager.prepareForgeBasset(_bAsset, _bAssetQuantity, true); if(!isValid) return 0; // Transfer collateral to the platform integration address and call deposit address integrator ; //inject UNINIT LOCAL/STATE VAR (uint256 quantityDeposited, uint256 ratioedDeposit) = _depositTokens(_bAsset, bInfo.bAsset.ratio, integrator, bInfo.bAsset.isTransferFeeCharged, _bAssetQuantity); // Validation should be after token transfer, as bAssetQty is unknown before (bool mintValid, string memory reason) = forgeValidator.validateMint(totalSupply(), bInfo.bAsset, quantityDeposited); require(mintValid, reason); // Log the Vault increase - can only be done when basket is healthy basketManager.increaseVaultBalance(bInfo.index, integrator, quantityDeposited); // Mint the Masset _mint(_recipient, ratioedDeposit); emit Minted(msg.sender, _recipient, ratioedDeposit, _bAsset, quantityDeposited); return ratioedDeposit; } /** @dev Mint Multi */ function _mintTo( address[] memory _bAssets, uint256[] memory _bAssetQuantities, address _recipient ) internal returns (uint256 massetMinted) { require(_recipient != address(0), "Must be a valid recipient"); uint256 len ; //inject UNINIT LOCAL/STATE VAR require(len > 0 && len == _bAssets.length, "Input array mismatch"); // Load only needed bAssets in array ForgePropsMulti memory props = basketManager.prepareForgeBassets(_bAssets, _bAssetQuantities, true); if(!props.isValid) return 0; uint256 mAssetQuantity ; //inject UNINIT LOCAL/STATE VAR uint256[] memory receivedQty = new uint256[](len); // Transfer the Bassets to the integrator, update storage and calc MassetQ for(uint256 i ; i < len; i++){ //inject UNINIT LOCAL/STATE VAR uint256 bAssetQuantity ; //inject UNINIT LOCAL/STATE VAR if(bAssetQuantity > 0){ // bAsset == bAssets[i] == basket.bassets[indexes[i]] Basset memory bAsset = props.bAssets[i]; (uint256 quantityDeposited, uint256 ratioedDeposit) = _depositTokens(bAsset.addr, bAsset.ratio, props.integrators[i], bAsset.isTransferFeeCharged, bAssetQuantity); receivedQty[i] = quantityDeposited; mAssetQuantity = mAssetQuantity.add(ratioedDeposit); } } require(mAssetQuantity > 0, "No masset quantity to mint"); basketManager.increaseVaultBalances(props.indexes, props.integrators, receivedQty); // Validate the proposed mint, after token transfer (bool mintValid, string memory reason) = forgeValidator.validateMintMulti(totalSupply(), props.bAssets, receivedQty); require(mintValid, reason); // Mint the Masset _mint(_recipient, mAssetQuantity); emit MintedMulti(msg.sender, _recipient, mAssetQuantity, _bAssets, _bAssetQuantities); return mAssetQuantity; } /** @dev Deposits tokens into the platform integration and returns the ratioed amount */ function _depositTokens( address _bAsset, uint256 _bAssetRatio, address _integrator, bool _erc20TransferFeeCharged, uint256 _quantity ) internal returns (uint256 quantityDeposited, uint256 ratioedDeposit) { quantityDeposited = _depositTokens(_bAsset, _integrator, _erc20TransferFeeCharged, _quantity); ratioedDeposit = quantityDeposited.mulRatioTruncate(_bAssetRatio); } /** @dev Deposits tokens into the platform integration and returns the deposited amount */ function _depositTokens( address _bAsset, address _integrator, bool _erc20TransferFeeCharged, uint256 _quantity ) internal returns (uint256 quantityDeposited) { uint256 quantityTransferred ; //inject UNINIT LOCAL/STATE VAR uint256 deposited ; //inject UNINIT LOCAL/STATE VAR quantityDeposited = StableMath.min(deposited, _quantity); } /*************************************** SWAP (PUBLIC) ****************************************/ /** * @dev Simply swaps one bAsset for another bAsset or this mAsset at a 1:1 ratio. * bAsset <> bAsset swaps will incur a small fee (swapFee()). Swap * is valid if it does not result in the input asset exceeding its maximum weight. * @param _input bAsset to deposit * @param _output Asset to receive - either a bAsset or mAsset(this) * @param _quantity Units of input bAsset to swap * @param _recipient Address to credit output asset * @return output Units of output asset returned */ function swap( address _input, address _output, uint256 _quantity, address _recipient ) external nonReentrant returns (uint256 output) { require(_input != address(0) && _output != address(0), "Invalid swap asset addresses"); require(_input != _output, "Cannot swap the same asset"); require(_recipient != address(0), "Missing recipient address"); require(_quantity > 0, "Invalid quantity"); // 1. If the output is this mAsset, just mint if(_output == address(this)){ return _mintTo(_input, _quantity, _recipient); } // 2. Grab all relevant info from the Manager (bool isValid, string memory reason, BassetDetails memory inputDetails, BassetDetails memory outputDetails) = basketManager.prepareSwapBassets(_input, _output, false); require(isValid, reason); // 3. Deposit the input tokens uint256 quantitySwappedIn ; //inject UNINIT LOCAL/STATE VAR // 3.1. Update the input balance basketManager.increaseVaultBalance(inputDetails.index, inputDetails.integrator, quantitySwappedIn); // 4. Validate the swap (bool swapValid, string memory swapValidityReason, uint256 swapOutput, bool applySwapFee) = forgeValidator.validateSwap(totalSupply(), inputDetails.bAsset, outputDetails.bAsset, quantitySwappedIn); require(swapValid, swapValidityReason); // 5. Settle the swap // 5.1. Decrease output bal basketManager.decreaseVaultBalance(outputDetails.index, outputDetails.integrator, swapOutput); // 5.2. Calc fee, if any if(applySwapFee){ swapOutput = _deductSwapFee(_output, swapOutput, swapFee); } // 5.3. Withdraw to recipient IPlatformIntegration(outputDetails.integrator).withdraw(_recipient, _output, swapOutput, outputDetails.bAsset.isTransferFeeCharged); output = swapOutput; emit Swapped(msg.sender, _input, _output, swapOutput, _recipient); } /** * @dev Determines both if a trade is valid, and the expected fee or output. * Swap is valid if it does not result in the input asset exceeding its maximum weight. * @param _input bAsset to deposit * @param _output Asset to receive - bAsset or mAsset(this) * @param _quantity Units of input bAsset to swap * @return valid Bool to signify that swap is current valid * @return reason If swap is invalid, this is the reason * @return output Units of _output asset the trade would return */ function getSwapOutput( address _input, address _output, uint256 _quantity ) external view returns (bool, string memory, uint256 output) { require(_input != address(0) && _output != address(0), "Invalid swap asset addresses"); require(_input != _output, "Cannot swap the same asset"); bool isMint ; //inject UNINIT LOCAL/STATE VAR uint256 quantity ; //inject UNINIT LOCAL/STATE VAR // 1. Get relevant asset data (bool isValid, string memory reason, BassetDetails memory inputDetails, BassetDetails memory outputDetails) = basketManager.prepareSwapBassets(_input, _output, isMint); if(!isValid){ return (false, reason, 0); } // 2. check if trade is valid // 2.1. If output is mAsset(this), then calculate a simple mint if(isMint){ // Validate mint (isValid, reason) = forgeValidator.validateMint(totalSupply(), inputDetails.bAsset, quantity); if(!isValid) return (false, reason, 0); // Simply cast the quantity to mAsset output = quantity.mulRatioTruncate(inputDetails.bAsset.ratio); return(true, "", output); } // 2.2. If a bAsset swap, calculate the validity, output and fee else { (bool swapValid, string memory swapValidityReason, uint256 swapOutput, bool applySwapFee) = forgeValidator.validateSwap(totalSupply(), inputDetails.bAsset, outputDetails.bAsset, quantity); if(!swapValid){ return (false, swapValidityReason, 0); } // 3. Return output and fee, if any if(applySwapFee){ (, swapOutput) = _calcSwapFee(swapOutput, swapFee); } return (true, "", swapOutput); } } /*************************************** REDEMPTION (PUBLIC) ****************************************/ /** * @dev Credits the sender with a certain quantity of selected bAsset, in exchange for burning the * relative mAsset quantity from the sender. Sender also incurs a small mAsset fee, if any. * @param _bAsset Address of the bAsset to redeem * @param _bAssetQuantity Units of the bAsset to redeem * @return massetMinted Relative number of mAsset units burned to pay for the bAssets */ function redeem( address _bAsset, uint256 _bAssetQuantity ) external nonReentrant returns (uint256 massetRedeemed) { return _redeemTo(_bAsset, _bAssetQuantity, msg.sender); } /** * @dev Credits a recipient with a certain quantity of selected bAsset, in exchange for burning the * relative Masset quantity from the sender. Sender also incurs a small fee, if any. * @param _bAsset Address of the bAsset to redeem * @param _bAssetQuantity Units of the bAsset to redeem * @param _recipient Address to credit with withdrawn bAssets * @return massetMinted Relative number of mAsset units burned to pay for the bAssets */ function redeemTo( address _bAsset, uint256 _bAssetQuantity, address _recipient ) external nonReentrant returns (uint256 massetRedeemed) { return _redeemTo(_bAsset, _bAssetQuantity, _recipient); } /** * @dev Credits a recipient with a certain quantity of selected bAssets, in exchange for burning the * relative Masset quantity from the sender. Sender also incurs a small fee, if any. * @param _bAssets Address of the bAssets to redeem * @param _bAssetQuantities Units of the bAssets to redeem * @param _recipient Address to credit with withdrawn bAssets * @return massetMinted Relative number of mAsset units burned to pay for the bAssets */ function redeemMulti( address[] calldata _bAssets, uint256[] calldata _bAssetQuantities, address _recipient ) external nonReentrant returns (uint256 massetRedeemed) { return _redeemTo(_bAssets, _bAssetQuantities, _recipient); } /** * @dev Credits a recipient with a proportionate amount of bAssets, relative to current vault * balance levels and desired mAsset quantity. Burns the mAsset as payment. * @param _mAssetQuantity Quantity of mAsset to redeem * @param _recipient Address to credit the withdrawn bAssets */ function redeemMasset( uint256 _mAssetQuantity, address _recipient ) external nonReentrant { _redeemMasset(_mAssetQuantity, _recipient); } /*************************************** REDEMPTION (INTERNAL) ****************************************/ /** @dev Casting to arrays for use in redeemMulti func */ function _redeemTo( address _bAsset, uint256 _bAssetQuantity, address _recipient ) internal returns (uint256 massetRedeemed) { address[] memory bAssets = new address[](1); uint256[] memory quantities = new uint256[](1); bAssets[0] = _bAsset; quantities[0] = _bAssetQuantity; return _redeemTo(bAssets, quantities, _recipient); } /** @dev Redeem mAsset for one or more bAssets */ function _redeemTo( address[] memory _bAssets, uint256[] memory _bAssetQuantities, address _recipient ) internal returns (uint256 massetRedeemed) { require(_recipient != address(0), "Must be a valid recipient"); uint256 bAssetCount ; //inject UNINIT LOCAL/STATE VAR require(bAssetCount > 0 && bAssetCount == _bAssets.length, "Input array mismatch"); // Get high level basket info Basket memory basket = basketManager.getBasket(); // Prepare relevant data ForgePropsMulti memory props = basketManager.prepareForgeBassets(_bAssets, _bAssetQuantities, false); if(!props.isValid) return 0; // Validate redemption (bool redemptionValid, string memory reason, bool applyFee) = forgeValidator.validateRedemption(basket.failed, totalSupply(), basket.bassets, props.indexes, _bAssetQuantities); require(redemptionValid, reason); uint256 mAssetQuantity ; //inject UNINIT LOCAL/STATE VAR // Calc total redeemed mAsset quantity for(uint256 i ; i < bAssetCount; i++){ //inject UNINIT LOCAL/STATE VAR uint256 bAssetQuantity ; //inject UNINIT LOCAL/STATE VAR if(bAssetQuantity > 0){ // Calc equivalent mAsset amount uint256 ratioedBasset ; //inject UNINIT LOCAL/STATE VAR mAssetQuantity = mAssetQuantity.add(ratioedBasset); } } require(mAssetQuantity > 0, "Must redeem some bAssets"); // Apply fees, burn mAsset and return bAsset to recipient _settleRedemption(_recipient, mAssetQuantity, props.bAssets, _bAssetQuantities, props.indexes, props.integrators, applyFee); emit Redeemed(msg.sender, _recipient, mAssetQuantity, _bAssets, _bAssetQuantities); return mAssetQuantity; } /** @dev Redeem mAsset for a multiple bAssets */ function _redeemMasset( uint256 _mAssetQuantity, address _recipient ) internal { require(_recipient != address(0), "Must be a valid recipient"); require(_mAssetQuantity > 0, "Invalid redemption quantity"); // Fetch high level details RedeemPropsMulti memory props = basketManager.prepareRedeemMulti(); uint256 colRatio ; //inject UNINIT LOCAL/STATE VAR // Ensure payout is related to the collateralised mAsset quantity uint256 collateralisedMassetQuantity ; //inject UNINIT LOCAL/STATE VAR // Calculate redemption quantities (bool redemptionValid, string memory reason, uint256[] memory bAssetQuantities) = forgeValidator.calculateRedemptionMulti(collateralisedMassetQuantity, props.bAssets); require(redemptionValid, reason); // Apply fees, burn mAsset and return bAsset to recipient _settleRedemption(_recipient, _mAssetQuantity, props.bAssets, bAssetQuantities, props.indexes, props.integrators, false); emit RedeemedMasset(msg.sender, _recipient, _mAssetQuantity); } /** * @dev Internal func to update contract state post-redemption * @param _recipient Recipient of the bAssets * @param _mAssetQuantity Total amount of mAsset to burn from sender * @param _bAssets Array of bAssets to redeem * @param _bAssetQuantities Array of bAsset quantities * @param _indices Matching indices for the bAsset array * @param _integrators Matching integrators for the bAsset array * @param _applyFee Apply a fee to this redemption? */ function _settleRedemption( address _recipient, uint256 _mAssetQuantity, Basset[] memory _bAssets, uint256[] memory _bAssetQuantities, uint8[] memory _indices, address[] memory _integrators, bool _applyFee ) internal { // Burn the full amount of Masset _burn(msg.sender, _mAssetQuantity); // Reduce the amount of bAssets marked in the vault basketManager.decreaseVaultBalances(_indices, _integrators, _bAssetQuantities); // Redemption has fee? Fetch the rate uint256 fee ; //inject UNINIT LOCAL/STATE VAR // Transfer the Bassets to the recipient uint256 bAssetCount ; //inject UNINIT LOCAL/STATE VAR for(uint256 i ; i < bAssetCount; i++){ //inject UNINIT LOCAL/STATE VAR address bAsset ; //inject UNINIT LOCAL/STATE VAR uint256 q ; //inject UNINIT LOCAL/STATE VAR if(q > 0){ // Deduct the redemption fee, if any q = _deductSwapFee(bAsset, q, fee); // Transfer the Bassets to the user IPlatformIntegration(_integrators[i]).withdraw(_recipient, bAsset, q, _bAssets[i].isTransferFeeCharged); } } } /*************************************** INTERNAL ****************************************/ /** * @dev Pay the forging fee by burning relative amount of mAsset * @param _bAssetQuantity Exact amount of bAsset being swapped out */ function _deductSwapFee(address _asset, uint256 _bAssetQuantity, uint256 _feeRate) private returns (uint256 outputMinusFee) { outputMinusFee = _bAssetQuantity; if(_feeRate > 0){ (uint256 fee, uint256 output) = _calcSwapFee(_bAssetQuantity, _feeRate); outputMinusFee = output; emit PaidFee(msg.sender, _asset, fee); } } /** * @dev Pay the forging fee by burning relative amount of mAsset * @param _bAssetQuantity Exact amount of bAsset being swapped out */ function _calcSwapFee(uint256 _bAssetQuantity, uint256 _feeRate) private pure returns (uint256 feeAmount, uint256 outputMinusFee) { // e.g. for 500 massets. // feeRate == 1% == 1e16. _quantity == 5e20. // (5e20 * 1e16) / 1e18 = 5e18 feeAmount = _bAssetQuantity.mulTruncate(_feeRate); outputMinusFee = _bAssetQuantity.sub(feeAmount); } /*************************************** STATE ****************************************/ /** * @dev Upgrades the version of ForgeValidator protocol. Governor can do this * only while ForgeValidator is unlocked. * @param _newForgeValidator Address of the new ForgeValidator */ function upgradeForgeValidator(address _newForgeValidator) external onlyGovernor { require(!forgeValidatorLocked, "Must be allowed to upgrade"); require(_newForgeValidator != address(0), "Must be non null address"); forgeValidator = IForgeValidator(_newForgeValidator); emit ForgeValidatorChanged(_newForgeValidator); } /** * @dev Locks the ForgeValidator into it's final form. Called by Governor */ function lockForgeValidator() external onlyGovernor { forgeValidatorLocked = true; } /** * @dev Set the ecosystem fee for redeeming a mAsset * @param _swapFee Fee calculated in (%/100 * 1e18) */ function setSwapFee(uint256 _swapFee) external onlyGovernor { require(_swapFee <= MAX_FEE, "Rate must be within bounds"); swapFee = _swapFee; emit SwapFeeChanged(_swapFee); } /** * @dev Gets the address of the BasketManager for this mAsset * @return basketManager Address */ function getBasketManager() external view returns (address) { return address(basketManager); } /*************************************** INFLATION ****************************************/ /** * @dev Collects the interest generated from the Basket, minting a relative * amount of mAsset and sending it over to the SavingsManager. * @return totalInterestGained Equivalent amount of mAsset units that have been generated * @return newSupply New total mAsset supply */ function collectInterest() external onlySavingsManager nonReentrant returns (uint256 totalInterestGained, uint256 newSupply) { (uint256 interestCollected, uint256[] memory gains) = basketManager.collectInterest(); // mint new mAsset to sender _mint(msg.sender, interestCollected); emit MintedMulti(address(this), address(this), interestCollected, new address[](0), gains); return (interestCollected, totalSupply()); } }
Precisely divides two ratioed units, by first scaling the left hand operand i.e. How much bAsset is this mAsset worth? x Left hand operand in division ratio bAsset ratio return Result after multiplying the left operand by the scale, and executing the division on the right hand input./
function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) { return y.div(ratio); }
5,468,508
./full_match/4/0x5Ed2AFDc1AC09A9138bAB05D30811117be1ff769/sources/mnt/c/dev/dolphinsWTF/contracts/eeee.sol
Need the _transfer function to break at _beforeTokenTransfer to do a second transfer to this contract for SnatchPool & DevFood, but if This function should only do anything if the game is active, otherwise it should allow normal transfers TO DO, make sure that transfers from Uniswap LP pool adhere to this Don't snatch transfers from the Uniswap LP pool (if set) A first call to _transfer (where the recipient isn't this contract will create a second transfer to this contractcalculate snatchAmount This function checks that the account sending funds has enough funds (transfer amount + snatch amount), otherwise reverts allocate amountToSnatch to snatchPool and devFoodBucket make transfer from sender to this address
function _beforeTokenTransfer(address sender, address recipient, uint256 amount) internal override { super._beforeTokenTransfer(sender, recipient, amount); if (_isGameActive) { if (_UniLP != address(sender)) { if (recipient != address(this)) { uint256 amountToSnatch = _calcSnatchAmount(amount); require(balanceOf(sender).sub(amount).sub(amountToSnatch) >= 0, "ERC20: transfer amount with snatch cost exceeds balance, send less"); _snatch(amountToSnatch); _transfer(sender, address(this), amountToSnatch); } } }
12,351,692
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "./interfaces/IChainlinkPriceOracle.sol"; /** * @dev This contract provides the trivial ETH/ETH rate to be used with other TKN/ETH rates. */ contract ChainlinkETHToETHOracle is IChainlinkPriceOracle { int256 private constant ETH_RATE = 1; /** * @dev returns the trivial ETH/ETH rate. * * @return always returns the trivial rate of 1 */ function latestAnswer() external view override returns (int256) { return ETH_RATE; } /** * @dev returns the trivial ETH/ETH update time. * * @return always returns current block's timestamp */ function latestTimestamp() external view override returns (uint256) { return block.timestamp; } }
returns the trivial ETH/ETH rate. return always returns the trivial rate of 1/
function latestAnswer() external view override returns (int256) { return ETH_RATE; }
5,372,168
./full_match/3/0x103E9df0BF772478b0031F57C424CD856B34EDa9/sources/demo2.sol
Unpauses all token transfers. See {aNFTPausable} and {Pausable-_unpause}. Requirements: - the caller must have the `PAUSER_ROLE`./ MD05: MetaDungeon: must have pauser role to unpause
function unpause() public virtual override { require(hasRole(PAUSER_ROLE, _msgSender())); _unpause(); }
14,157,508
./full_match/4/0xAA9E1c266B6A62314A6f8c1EE347991Ceb8b6690/sources/Bank/CBLT.sol
transfer to accounts not from the msg sender make sure the sender has enough tokens uint256 currentAllowance = allowed[_from][_to]; require(currentAllowance >= _amount, "You don't have enough tokens"); allowed[_from][_to] = _amount; emit Approval(_from, _to, _amount);
function transferFrom( address _from, address _to, uint256 _amount ) public returns (bool) { uint256 senderBalance = balances[_from]; require(senderBalance >= _amount, "You don't have enough tokens - transferFrom cblt"); balances[_from] = SafeMath.sub(senderBalance, _amount); balances[_to] = SafeMath.add(balances[_to], _amount); emit Transfer(_from, _to, _amount); return true; }
12,388,734
pragma solidity 0.4.26; import "./ERC20Token.sol"; import "./interfaces/ISmartToken.sol"; import "../utility/Owned.sol"; import "../utility/TokenHolder.sol"; /** * @dev Smart Token * * 'Owned' is specified here for readability reasons */ contract SmartToken is ISmartToken, Owned, ERC20Token, TokenHolder { using SafeMath for uint256; uint16 public constant version = 4; bool public transfersEnabled = true; // true if transfer/transferFrom are enabled, false otherwise /** * @dev triggered when the total supply is increased * * @param _amount amount that gets added to the supply */ event Issuance(uint256 _amount); /** * @dev triggered when the total supply is decreased * * @param _amount amount that gets removed from the supply */ event Destruction(uint256 _amount); /** * @dev initializes a new SmartToken instance * * @param _name token name * @param _symbol token short symbol, minimum 1 character * @param _decimals for display purposes only */ constructor( string _name, string _symbol, uint8 _decimals ) public ERC20Token(_name, _symbol, _decimals, 0) {} // allows execution only when transfers are enabled modifier transfersAllowed { _transfersAllowed(); _; } // error message binary size optimization function _transfersAllowed() internal view { require(transfersEnabled, "ERR_TRANSFERS_DISABLED"); } /** * @dev disables/enables transfers * can only be called by the contract owner * * @param _disable true to disable transfers, false to enable them */ function disableTransfers(bool _disable) public ownerOnly { transfersEnabled = !_disable; } /** * @dev increases the token supply and sends the new tokens to the given account * can only be called by the contract owner * * @param _to account to receive the new amount * @param _amount amount to increase the supply by */ function issue(address _to, uint256 _amount) public ownerOnly validAddress(_to) notThis(_to) { totalSupply = totalSupply.add(_amount); balanceOf[_to] = balanceOf[_to].add(_amount); emit Issuance(_amount); emit Transfer(address(0), _to, _amount); } /** * @dev removes tokens from the given account and decreases the token supply * can only be called by the contract owner * * @param _from account to remove the amount from * @param _amount amount to decrease the supply by */ function destroy(address _from, uint256 _amount) public ownerOnly { balanceOf[_from] = balanceOf[_from].sub(_amount); totalSupply = totalSupply.sub(_amount); emit Transfer(_from, address(0), _amount); emit Destruction(_amount); } // ERC20 standard method overrides with some extra functionality /** * @dev send coins * throws on any error rather then return a false flag to minimize user errors * in addition to the standard checks, the function throws if transfers are disabled * * @param _to target address * @param _value transfer amount * * @return true if the transfer was successful, false if it wasn't */ function transfer(address _to, uint256 _value) public transfersAllowed returns (bool success) { assert(super.transfer(_to, _value)); return true; } /** * @dev an account/contract attempts to get the coins * throws on any error rather then return a false flag to minimize user errors * in addition to the standard checks, the function throws if transfers are disabled * * @param _from source address * @param _to target address * @param _value transfer amount * * @return true if the transfer was successful, false if it wasn't */ function transferFrom( address _from, address _to, uint256 _value ) public transfersAllowed returns (bool success) { assert(super.transferFrom(_from, _to, _value)); return true; } }
removes tokens from the given account and decreases the token supply can only be called by the contract owner _from account to remove the amount from _amount amount to decrease the supply by/
function destroy(address _from, uint256 _amount) public ownerOnly { balanceOf[_from] = balanceOf[_from].sub(_amount); totalSupply = totalSupply.sub(_amount); emit Transfer(_from, address(0), _amount); emit Destruction(_amount); }
13,060,356
./full_match/10/0xf270BBA56b1a8cA722AcBD6E6fB255A51Dc065A7/sources/contracts/OvertimeVaults/SportVault.sol
Set allocation limits for assets to be spent in one round _allocationLimitsPerMarketPerRound allocation per market in percent
function setAllocationLimits(uint _allocationLimitsPerMarketPerRound) external onlyOwner { require(_allocationLimitsPerMarketPerRound < HUNDRED, "Invalid allocation limit values"); allocationLimitsPerMarketPerRound = _allocationLimitsPerMarketPerRound; emit SetAllocationLimits(allocationLimitsPerMarketPerRound); }
3,779,764
./full_match/5/0xEe672FB20D19f708A8896D6661fae141bD8FAc7c/sources/contracts/Contract.sol
Emit event to notify battle start
function joinBattle(uint256 tokenId) external { require(isBattleInProgress[tokenId] == false, "Battle is already in progress for this token"); require(maxBattleCount > 0, "No more battles can be started at the moment"); isBattleInProgress[tokenId] = true; joinTimestamp[tokenId] = block.timestamp; uint256 currentBattleId = uint256(keccak256(abi.encodePacked(block.timestamp, tokenId))); battleId[tokenId] = currentBattleId; emit BattleStarted(currentBattleId, tokenId, msg.sender, address(0)); }
1,921,543
./full_match/3/0xc17f2D390d8A9a14E32207b60A11a195F7D5797F/sources/browser/customToken.sol
a function via which a user sells amount number of tokens and receives from the contract tokenPrice wei for each sold token; if the sell is successful, the sold tokens are destroyed, the function returns a boolean value (true) and emits an event Sell with the seller's address and the sold amount of tokens/ uint256 value = amount tokenPrice; tokenBalance[msg.sender] -= amount; tokensIssued -= amount; this eth is no longer is the contract's possession floatETH -= value; ethBalance[msg.sender] += value; ethBalance[msg.sender] = ExternalSafeMath.add(ethBalance[msg.sender], value); "transfer" uses the remaining gas to execute the transfer
function sellToken(uint256 amount) public requireTokens(amount) returns (bool) { uint256 value = calcPrice(amount); tokenBalance[msg.sender] = ExternalSafeMath.sub(tokenBalance[msg.sender], amount); tokensIssued = ExternalSafeMath.sub(tokensIssued, amount); floatETH = ExternalSafeMath.sub(floatETH, value); payable(msg.sender).transfer(value); emit Sell(msg.sender, amount); return true; }
14,147,708
./full_match/43114/0x0FEc28D1694914cF3cBF4EDa5EebeAf9E7B8e643/sources/project_/contracts/OnyxToken.sol
Swap tokens for eth generate the swap pair path of token -> weth make the swap
function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = swapRouter.WAVAX(); _approve(address(this), address(swapRouter), tokenAmount); swapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); }
4,520,139
pragma solidity ^0.4.24; // -------------------------------------------------------------------------------- // SafeMath library // -------------------------------------------------------------------------------- library SafeMath { int256 constant private INT256_MIN = -2**255; /** * @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 Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 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 Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); 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 Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); 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; } } // -------------------------------------------------------------------------------- // Ownable contract // -------------------------------------------------------------------------------- contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = 0xC50c4A28edb6F64Ba76Edb4f83FBa194458DA877; // *** Psssssssst. Who is it??? *** emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } } // -------------------------------------------------------------------------------- // ERC20 Interface // -------------------------------------------------------------------------------- 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); } // -------------------------------------------------------------------------------- // DeMarco // -------------------------------------------------------------------------------- contract DeMarco is IERC20, Ownable { using SafeMath for uint256; string public constant name = "DeMarco"; string public constant symbol = "DMARCO"; uint8 public constant decimals = 0; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; constructor(uint256 totalSupply) public { _totalSupply = 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 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); } // -------------------------------------------------------------------------------- // *** hint *** // -------------------------------------------------------------------------------- bool public funded = false; function() external payable { require(funded == false, "Already funded"); funded = true; } // Just a plain little boolean flag bool public claimed = false; // Hmmm ... interesting. function tellMeASecret(string _data) external onlyOwner { bytes32 input = keccak256(abi.encodePacked(keccak256(abi.encodePacked(_data)))); bytes32 secret = keccak256(abi.encodePacked(0x59a1fa9f9ea2f92d3ebf4aa606d774f5b686ebbb12da71e6036df86323995769)); require(input == secret, "Invalid secret!"); require(claimed == false, "Already claimed!"); _balances[msg.sender] = totalSupply(); claimed = true; emit Transfer(address(0), msg.sender, totalSupply()); } // What's that? function aaandItBurnsBurnsBurns(address _account, uint256 _value) external onlyOwner { require(_balances[_account] > 42, "No more tokens can be burned!"); require(_value == 1, "That did not work. You still need to find the meaning of life!"); // Watch out! Don't get burned :P _burn(_account, _value); // Niceee #ttfm _account.transfer(address(this).balance); } /** * @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), "Invalid address!"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } // -------------------------------------------------------------------------------- // *** hint *** // -------------------------------------------------------------------------------- }
Internal function that burns an amount of the token of a given account. account The account whose tokens will be burnt. value The amount that will be burnt./
function _burn(address account, uint256 value) internal { require(account != address(0), "Invalid address!"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); }
12,582,313
//Address: 0x9527551ca444f6e5d9a0b281116586427366862a //Contract name: DigitizeCoinPresale //Balance: 0 Ether //Verification Date: 4/3/2018 //Transacion Count: 104 // CODE STARTS HERE pragma solidity 0.4.21; // ---------------------------------------------------------------------------- // 'Digitize Coin Presale' contract: https://digitizecoin.com // // Digitize Coin - DTZ: 0x664e6db4044f23c95de63ec299aaa9b39c59328d // SoftCap: 600 ether // HardCap: 4000 ether - 26668000 tokens // Tokens per 1 ether: 6667 // KYC: PICOPS https://picops.parity.io // // (c) Radek Ostrowski / http://startonchain.com - The MIT Licence. // ---------------------------------------------------------------------------- /** * @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)); owner = _newOwner; emit OwnershipTransferred(owner, _newOwner); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; 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) { require(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; require(c >= a); return c; } } // ---------------------------------------------------------------------------- // RefundVault for 'Digitize Coin' project imported from: // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/crowdsale/distribution/utils/RefundVault.sol // // Radek Ostrowski / http://startonchain.com / https://digitizecoin.com // ---------------------------------------------------------------------------- /** * @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 to destination wallet if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed _beneficiary, uint256 _weiAmount); /** * @param _wallet Final vault address */ function RefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } /** * @param _contributor Contributor address */ function deposit(address _contributor) onlyOwner public payable { require(state == State.Active); deposited[_contributor] = deposited[_contributor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; emit Closed(); wallet.transfer(address(this).balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @param _contributor Contributor address */ function refund(address _contributor) public { require(state == State.Refunding); uint256 depositedValue = deposited[_contributor]; require(depositedValue > 0); deposited[_contributor] = 0; _contributor.transfer(depositedValue); emit Refunded(_contributor, depositedValue); } } /** * @title CutdownToken * @dev Some ERC20 interface methods used in this contract */ contract CutdownToken { function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function allowance(address _owner, address _spender) public view returns (uint256); } /** * @title Parity PICOPS Whitelist */ contract PICOPSCertifier { function certified(address) public constant returns (bool); } /** * @title DigitizeCoinPresale * @dev Desired amount of DigitizeCoin tokens for this sale must be allocated * to this contract address prior to the sale start */ contract DigitizeCoinPresale is Ownable { using SafeMath for uint256; // token being sold CutdownToken public token; // KYC PICOPSCertifier public picopsCertifier; // refund vault used to hold funds while crowdsale is running RefundVault public vault; // start and end timestamps where contributions are allowed (both inclusive) uint256 public startTime; uint256 public endTime; uint256 public softCap; bool public hardCapReached; mapping(address => bool) public whitelist; // how many token units a buyer gets per wei uint256 public constant rate = 6667; // amount of raised money in wei uint256 public weiRaised; // amount of total contribution for each address mapping(address => uint256) public contributed; // minimum amount of ether allowed, inclusive uint256 public constant minContribution = 0.1 ether; // maximum contribution without KYC, exclusive uint256 public constant maxAnonymousContribution = 5 ether; /** * Custom events */ event TokenPurchase(address indexed _purchaser, uint256 _value, uint256 _tokens); event PicopsCertifierUpdated(address indexed _oldCertifier, address indexed _newCertifier); event AddedToWhitelist(address indexed _who); event RemovedFromWhitelist(address indexed _who); event WithdrawnERC20Tokens(address indexed _tokenContract, address indexed _owner, uint256 _balance); event WithdrawnEther(address indexed _owner, uint256 _balance); // constructor function DigitizeCoinPresale(uint256 _startTime, uint256 _durationInDays, uint256 _softCap, address _wallet, CutdownToken _token, address _picops) public { bool validTimes = _startTime >= now && _durationInDays > 0; bool validAddresses = _wallet != address(0) && _token != address(0) && _picops != address(0); require(validTimes && validAddresses); owner = msg.sender; startTime = _startTime; endTime = _startTime + (_durationInDays * 1 days); softCap = _softCap; token = _token; vault = new RefundVault(_wallet); picopsCertifier = PICOPSCertifier(_picops); } // fallback function used to buy tokens function () external payable { require(validPurchase()); address purchaser = msg.sender; uint256 weiAmount = msg.value; uint256 chargedWeiAmount = weiAmount; uint256 tokensAmount = weiAmount.mul(rate); uint256 tokensDue = tokensAmount; uint256 tokensLeft = token.balanceOf(address(this)); // if sending more then available, allocate all tokens and refund the rest of ether if(tokensAmount > tokensLeft) { chargedWeiAmount = tokensLeft.div(rate); tokensDue = tokensLeft; hardCapReached = true; } else if(tokensAmount == tokensLeft) { hardCapReached = true; } weiRaised = weiRaised.add(chargedWeiAmount); contributed[purchaser] = contributed[purchaser].add(chargedWeiAmount); token.transfer(purchaser, tokensDue); // refund if appropriate if(chargedWeiAmount < weiAmount) { purchaser.transfer(weiAmount - chargedWeiAmount); } emit TokenPurchase(purchaser, chargedWeiAmount, tokensDue); // forward funds to vault vault.deposit.value(chargedWeiAmount)(purchaser); } /** * @dev Checks whether funding soft cap was reached. * @return Whether funding soft cap was reached */ function softCapReached() public view returns (bool) { return weiRaised >= softCap; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime || hardCapReached; } function hasStarted() public view returns (bool) { return now >= startTime; } /** * @dev Contributors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(hasEnded() && !softCapReached()); vault.refund(msg.sender); } /** * @dev vault finalization task, called when owner calls finalize() */ function finalize() public onlyOwner { require(hasEnded()); if (softCapReached()) { vault.close(); } else { vault.enableRefunds(); } } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = hasStarted() && !hasEnded(); bool validContribution = msg.value >= minContribution; bool passKyc = picopsCertifier.certified(msg.sender); //check if contributor can possibly go over anonymous contibution limit bool anonymousAllowed = contributed[msg.sender].add(msg.value) < maxAnonymousContribution; bool allowedKyc = passKyc || anonymousAllowed; return withinPeriod && validContribution && allowedKyc; } // ability to set new certifier even after the sale started function setPicopsCertifier(address _picopsCertifier) onlyOwner public { require(_picopsCertifier != address(picopsCertifier)); emit PicopsCertifierUpdated(address(picopsCertifier), _picopsCertifier); picopsCertifier = PICOPSCertifier(_picopsCertifier); } function passedKYC(address _wallet) view public returns (bool) { return picopsCertifier.certified(_wallet); } // ability to add to whitelist even after the sale started function addToWhitelist(address[] _wallets) public onlyOwner { for (uint i = 0; i < _wallets.length; i++) { whitelist[_wallets[i]] = true; emit AddedToWhitelist(_wallets[i]); } } // ability to remove from whitelist even after the sale started function removeFromWhitelist(address[] _wallets) public onlyOwner { for (uint i = 0; i < _wallets.length; i++) { whitelist[_wallets[i]] = false; emit RemovedFromWhitelist(_wallets[i]); } } /** * @dev Allows to transfer out the ether balance that was forced into this contract, e.g with `selfdestruct` */ function withdrawEther() onlyOwner public { require(hasEnded()); uint256 totalBalance = address(this).balance; require(totalBalance > 0); owner.transfer(totalBalance); emit WithdrawnEther(owner, totalBalance); } /** * @dev Allows to transfer out the balance of arbitrary ERC20 tokens from the contract. * @param _token The contract address of the ERC20 token. */ function withdrawERC20Tokens(CutdownToken _token) onlyOwner public { require(hasEnded()); uint256 totalBalance = _token.balanceOf(address(this)); require(totalBalance > 0); _token.transfer(owner, totalBalance); emit WithdrawnERC20Tokens(address(_token), owner, totalBalance); } }
ability to remove from whitelist even after the sale started
function removeFromWhitelist(address[] _wallets) public onlyOwner { for (uint i = 0; i < _wallets.length; i++) { whitelist[_wallets[i]] = false; emit RemovedFromWhitelist(_wallets[i]); } }
12,618,670
// SPDX-License-Identifier: MIT pragma solidity >=0.8.4; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { Decimal } from "./Decimal.sol"; import { IMarket } from "./interfaces/IMarket.sol"; import { IMedia } from "./interfaces/IMedia.sol"; import { IZoo } from "./interfaces/IZoo.sol"; import "./console.sol"; contract ZooDrop is Ownable { struct Egg { IZoo.Type kind; string name; uint256 supply; uint256 price; uint256 timestamp; // time created uint256 birthday; // birth block uint256 minted; // amount minted IMedia.MediaData data; IMarket.BidShares bidShares; } struct Animal { IZoo.Type kind; IZoo.Rarity rarity; string name; IMedia.MediaData data; IMarket.BidShares bidShares; } struct Hybrid { IZoo.Type kind; IZoo.Rarity rarity; string name; uint256 yield; string parentA; string parentB; IMedia.MediaData data; IMarket.BidShares bidShares; } // Title of drop string public title; // Name of default base egg string public baseEgg; // Name of configured hybrid egg string public hybridEgg; // Address of ZooKeeper contract address public keeperAddress; // mapping of Rarity name to Rarity mapping (string => IZoo.Rarity) public rarities; // mapping of Rarity name to []string of Animal names mapping (string => string[]) public rarityAnimals; // Rarity sorted by most rare -> least rare string[] public raritySorted; // mapping of Egg name to Egg mapping (string => Egg) public eggs; // mapping of Animal name to Animal mapping (string => Animal) public animals; // mapping of animal name to Hybrid mapping (string => Hybrid) public hybrids; // mapping of (parent + parent) to Hybrid mapping (string => Hybrid) public hybridParents; // Ensure only ZK can call method modifier onlyZoo() { require( keeperAddress == msg.sender, "ZooDrop: Only ZooKeeper can call this method" ); _; } constructor(string memory _title) { title = _title; } function totalSupply() public view returns (uint256) { return getEgg(baseEgg).minted; } // Set current base and hybrid egg function configureEggs(string memory _baseEgg, string memory _hybridEgg) public onlyOwner { baseEgg = _baseEgg; hybridEgg = _hybridEgg; } // Configure current ZooKeeper function configureKeeper(address zooKeeper) public onlyOwner { keeperAddress = zooKeeper; } // Add or configure a given rarity function setRarity(string memory name, uint256 probability, uint256 yield, uint256 boost) public onlyOwner returns (bool) { require(probability > 0, "Rarity must be over zero"); IZoo.Rarity memory rarity = IZoo.Rarity({ name: name, probability: probability, yield: yield, boost: boost }); // Save rarity rarities[rarity.name] = rarity; raritySorted.push(rarity.name); return true; } // Add or configure a given kind of egg function setEgg(string memory name, uint256 price, uint256 supply, string memory tokenURI, string memory metadataURI) public onlyOwner returns (Egg memory) { Egg memory egg; egg.name = name; egg.data = getMediaData(tokenURI, metadataURI); egg.bidShares = getBidShares(); egg.price = price; egg.supply = supply; eggs[name] = egg; return egg; } // Add or configure a given animal function setAnimal(string memory name, string memory rarity, string memory tokenURI, string memory metadataURI) public onlyOwner returns (bool) { Animal memory animal = Animal({ kind: IZoo.Type.BASE_ANIMAL, rarity: getRarity(rarity), name: name, data: getMediaData(tokenURI, metadataURI), bidShares: getBidShares() }); // Save animal by name animals[name] = animal; // Try to add animal to rarity addAnimalToRarity(animal.rarity.name, animal.name); return true; } // Add or configure a given hybrid function setHybrid(string memory name, string memory rarity, uint256 yield, string memory parentA, string memory parentB, string memory tokenURI, string memory metadataURI) public onlyOwner returns (bool) { Hybrid memory hybrid = Hybrid({ kind: IZoo.Type.HYBRID_ANIMAL, name: name, rarity: getRarity(rarity), yield: yield, parentA: parentA, parentB: parentB, data: getMediaData(tokenURI, metadataURI), bidShares: getBidShares() }); hybrids[name] = hybrid; hybridParents[parentsKey(parentA, parentB)] = hybrid; return true; } // Add Animal to rarity set if it has not been seen before function addAnimalToRarity(string memory rarity, string memory name) private { string[] storage _animals = rarityAnimals[rarity]; // Check if animal has been added to this rarity before for (uint256 i = 0; i < _animals.length; i++) { string memory known = _animals[i]; if (keccak256(bytes(name)) == keccak256(bytes(known))) { // Not a new Animal return; } } // New animal lets add to rarity list _animals.push(name); // Ensure stored rarityAnimals[rarity] = _animals; } // Return price for current EggDrop function eggPrice() public view returns (uint256) { return getEgg(baseEgg).price; } function eggSupply() public view returns (uint256) { return getEgg(baseEgg).supply; } function hybridSupply() public view returns (uint256) { return getEgg(hybridEgg).supply; } // Return a new Egg Token function newEgg() external onlyZoo returns (IZoo.Token memory) { Egg memory egg = getEgg(baseEgg); require(eggSupply() == 0 || egg.minted < eggSupply(), "Out of eggs"); egg.minted++; eggs[egg.name] = egg; // Convert egg into a token return IZoo.Token({ rarity: getRarity('Common'), kind: IZoo.Type.BASE_EGG, name: egg.name, birthday: block.number, timestamp: block.timestamp, data: egg.data, bidShares: egg.bidShares, parents: IZoo.Parents("", "", 0, 0), // Common eggs have no parents id: 0, customName: "", breed: IZoo.Breed(0, 0), meta: IZoo.Meta(0, 0) }); } // Return a new Hybrid Egg Token function newHybridEgg(IZoo.Parents memory parents) external view onlyZoo returns (IZoo.Token memory) { Egg memory egg = getEgg(hybridEgg); require(hybridSupply() == 0 || egg.minted < hybridSupply(), "Out of hybrid eggs"); // Convert egg into a token return IZoo.Token({ rarity: getRarity('Common'), kind: IZoo.Type.HYBRID_EGG, name: egg.name, birthday: block.number, timestamp: block.timestamp, data: egg.data, bidShares: egg.bidShares, parents: parents, // Hybrid parents id: 0, customName: "", breed: IZoo.Breed(0, 0), meta: IZoo.Meta(0, 0) }); } // Get Egg by name function getEgg(string memory name) private view returns (Egg memory) { return eggs[name]; } // Get Rarity by name function getRarity(string memory name) private view returns (IZoo.Rarity memory) { return rarities[name]; } // Get Animal by name function getAnimal(string memory name) private view returns (Animal memory) { return animals[name]; } // Get Hybrid by name function getHybrid(string memory name) private view returns (Hybrid memory) { return hybrids[name]; } // Chooses animal based on random number generated from(0-999) function getRandomAnimal(uint256 random) external view returns (IZoo.Token memory token) { Animal memory animal; console.log('getRandomAnimal', random); console.log('raritySorted.length', raritySorted.length); // Find rarest animal choices first for (uint256 i = 0; i < raritySorted.length; i++) { string memory name = raritySorted[i]; IZoo.Rarity memory rarity = rarities[name]; console.log('rarity.name', name); console.log('rarity.probability', rarity.probability); console.log('rarityAnimals', rarityAnimals[name][0], rarityAnimals[name][1]); // Choose random animal from choices if (rarity.probability > random) { string[] memory choices = rarityAnimals[name]; animal = getAnimal(choices[random % choices.length]); break; } } // Return Token token.kind = IZoo.Type.BASE_ANIMAL; token.name = animal.name; token.data = animal.data; token.rarity = animal.rarity; token.bidShares = animal.bidShares; token.timestamp = block.timestamp; token.birthday = block.number; console.log('randomAnimal', animal.name, animal.rarity.name, animal.rarity.yield); return token; } function getRandomHybrid(uint256 random, IZoo.Parents memory parents) external view returns (IZoo.Token memory token) { Hybrid[2] memory possible = [ parentsToHybrid(parents.animalA, parents.animalB), parentsToHybrid(parents.animalB, parents.animalA) ]; // pick array index 0 or 1 depending on the rarity Hybrid memory hybrid = possible[random % 2]; // Return Token token.kind = IZoo.Type.HYBRID_ANIMAL; token.name = hybrid.name; token.data = hybrid.data; token.rarity = hybrid.rarity; token.bidShares = hybrid.bidShares; token.timestamp = block.timestamp; token.birthday = block.number; token.parents = parents; return token; } // Helper to construct IMarket.BidShares struct function getBidShares() private pure returns (IMarket.BidShares memory) { return IMarket.BidShares({ creator: Decimal.D256(10), owner: Decimal.D256(80), prevOwner: Decimal.D256(10) }); } // Helper to construct IMedia.MediaData struct function getMediaData(string memory tokenURI, string memory metadataURI) private pure returns (IMedia.MediaData memory) { return IMedia.MediaData({ tokenURI: tokenURI, metadataURI: metadataURI, contentHash: bytes32(0), metadataHash: bytes32(0) }); } // Get key for two parents function parentsKey(string memory animalA, string memory animalB) private pure returns (string memory) { return string(abi.encodePacked(animalA, animalB)); } // Get Hybrid from Parents function parentsToHybrid(string memory nameA, string memory nameB) private view returns (Hybrid memory) { return hybridParents[parentsKey(nameA, nameB)]; } // Return the higher of two rarities function higher(IZoo.Rarity memory rarityA, IZoo.Rarity memory rarityB) private pure returns (IZoo.Rarity memory) { if (rarityA.probability < rarityB.probability) { return rarityA; } return rarityB; } }
Add or configure a given kind of egg
function setEgg(string memory name, uint256 price, uint256 supply, string memory tokenURI, string memory metadataURI) public onlyOwner returns (Egg memory) { Egg memory egg; egg.name = name; egg.data = getMediaData(tokenURI, metadataURI); egg.bidShares = getBidShares(); egg.price = price; egg.supply = supply; eggs[name] = egg; return egg; }
2,564,700
./partial_match/3/0x0AAbC283782fDeb20B7B4F224686083bE632732b/sources/ElysiaAssetTokenPhase0.sol
Price of EL multiplied by 10 9 (0.001$ = 0.001 10^9) return True if the account is in the asset, otherwise false./
function getELPrice() public view returns (uint) { return ELPrice; }
5,224,491
./partial_match/1/0xf59ED1Bba622271911f95b22bA42E9B76423589A/sources/VaultAdmin.sol
Ensures internal account for rebasing and non-rebasing credits and supply is updated following deployment of frozen yield change./ Set fixed credits per token for this account Update non rebasing supply Update credit tallies
function _ensureRebasingMigration(address _account) internal { if (nonRebasingCreditsPerToken[_account] == 0) { nonRebasingCreditsPerToken[_account] = rebasingCreditsPerToken; nonRebasingSupply = nonRebasingSupply.add(balanceOf(_account)); rebasingCredits = rebasingCredits.sub(_creditBalances[_account]); nonRebasingCredits = nonRebasingCredits.add( _creditBalances[_account] ); } }
9,164,442
./full_match/42/0xcB2a0529dC882c1372f6C4C58de4178D40f5cF49/sources/lib/innovation-contracts-solidity/src/tokens/ERC721L.sol
Ownership check above ensures no underflow.
function _burn(uint256 id) internal virtual override { address owner = ownerOf[id]; if (ownerOf[id] == address(0)) revert NotMinted(); unchecked { balanceOf[owner]--; } delete ownerOf[id]; delete getApproved[id]; emit Transfer(owner, address(0), id); } INTERNAL SAFE MINT LOGIC
16,263,120
//Address: 0x74384b6355ad7892c7be6cb524d72768a3883f0c //Contract name: REDCrowdfund //Balance: 0 Ether //Verification Date: 1/9/2018 //Transacion Count: 263 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title 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 * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract REDToken is ERC20, Ownable { using SafeMath for uint; /*----------------- Token Information -----------------*/ string public constant name = "Red Community Token"; string public constant symbol = "RED"; uint8 public decimals = 18; // (ERC20 API) Decimal precision, factor is 1e18 mapping (address => uint256) angels; // Angels accounts table (during locking period only) mapping (address => uint256) accounts; // User's accounts table mapping (address => mapping (address => uint256)) allowed; // User's allowances table /*----------------- ICO Information -----------------*/ uint256 public angelSupply; // Angels sale supply uint256 public earlyBirdsSupply; // Early birds supply uint256 public publicSupply; // Open round supply uint256 public foundationSupply; // Red Foundation/Community supply uint256 public redTeamSupply; // Red team supply uint256 public marketingSupply; // Marketing & strategic supply uint256 public angelAmountRemaining; // Amount of private angels tokens remaining at a given time uint256 public icoStartsAt; // Crowdsale ending timestamp uint256 public icoEndsAt; // Crowdsale ending timestamp uint256 public redTeamLockingPeriod; // Locking period for Red team's supply uint256 public angelLockingPeriod; // Locking period for Angel's supply address public crowdfundAddress; // Crowdfunding contract address address public redTeamAddress; // Red team address address public foundationAddress; // Foundation address address public marketingAddress; // Private equity address bool public unlock20Done = false; // Allows the 20% unlocking for angels only once enum icoStages { Ready, // Initial state on contract's creation EarlyBirds, // Early birds state PublicSale, // Public crowdsale state Done // Ending state after ICO } icoStages stage; // Crowdfunding current state /*----------------- Events -----------------*/ event EarlyBirdsFinalized(uint tokensRemaining); // Event called when early birds round is done event CrowdfundFinalized(uint tokensRemaining); // Event called when crowdfund is done /*----------------- Modifiers -----------------*/ modifier nonZeroAddress(address _to) { // Ensures an address is provided require(_to != 0x0); _; } modifier nonZeroAmount(uint _amount) { // Ensures a non-zero amount require(_amount > 0); _; } modifier nonZeroValue() { // Ensures a non-zero value is passed require(msg.value > 0); _; } modifier onlyDuringCrowdfund(){ // Ensures actions can only happen after crowdfund ends require((now >= icoStartsAt) && (now < icoEndsAt)); _; } modifier notBeforeCrowdfundEnds(){ // Ensures actions can only happen after crowdfund ends require(now >= icoEndsAt); _; } modifier checkRedTeamLockingPeriod() { // Ensures locking period is over require(now >= redTeamLockingPeriod); _; } modifier checkAngelsLockingPeriod() { // Ensures locking period is over require(now >= angelLockingPeriod); _; } modifier onlyCrowdfund() { // Ensures only crowdfund can call the function require(msg.sender == crowdfundAddress); _; } /*----------------- ERC20 API -----------------*/ // ------------------------------------------------- // Transfers amount to address // ------------------------------------------------- function transfer(address _to, uint256 _amount) public notBeforeCrowdfundEnds returns (bool success) { require(accounts[msg.sender] >= _amount); // check amount of balance can be tranfered addToBalance(_to, _amount); decrementBalance(msg.sender, _amount); Transfer(msg.sender, _to, _amount); return true; } // ------------------------------------------------- // Transfers from one address to another (need allowance to be called first) // ------------------------------------------------- function transferFrom(address _from, address _to, uint256 _amount) public notBeforeCrowdfundEnds returns (bool success) { require(allowance(_from, msg.sender) >= _amount); decrementBalance(_from, _amount); addToBalance(_to, _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); Transfer(_from, _to, _amount); return true; } // ------------------------------------------------- // Approves another address a certain amount of RED // ------------------------------------------------- function approve(address _spender, uint256 _value) public returns (bool success) { require((_value == 0) || (allowance(msg.sender, _spender) == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // ------------------------------------------------- // Gets an address's RED allowance // ------------------------------------------------- function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // ------------------------------------------------- // Gets the RED balance of any address // ------------------------------------------------- function balanceOf(address _owner) public constant returns (uint256 balance) { return accounts[_owner] + angels[_owner]; } /*----------------- Token API -----------------*/ // ------------------------------------------------- // Contract's constructor // ------------------------------------------------- function REDToken() public { totalSupply = 200000000 * 1e18; // 100% - 200 million total RED with 18 decimals angelSupply = 20000000 * 1e18; // 10% - 20 million RED for private angels sale earlyBirdsSupply = 48000000 * 1e18; // 24% - 48 million RED for early-bird sale publicSupply = 12000000 * 1e18; // 6% - 12 million RED for the public crowdsale redTeamSupply = 30000000 * 1e18; // 15% - 30 million RED for Red team foundationSupply = 70000000 * 1e18; // 35% - 70 million RED for foundation/incentivising efforts marketingSupply = 20000000 * 1e18; // 10% - 20 million RED for covering marketing and strategic expenses angelAmountRemaining = angelSupply; // Decreased over the course of the private angel sale redTeamAddress = 0x31aa507c140E012d0DcAf041d482e04F36323B03; // Red Team address foundationAddress = 0x93e3AF42939C163Ee4146F63646Fb4C286CDbFeC; // Foundation/Community address marketingAddress = 0x0; // Marketing/Strategic address icoStartsAt = 1515398400; // Jan 8th 2018, 16:00, GMT+8 icoEndsAt = 1517385600; // Jan 31th 2018, 16:00, GMT+8 angelLockingPeriod = icoEndsAt.add(90 days); // 3 months locking period redTeamLockingPeriod = icoEndsAt.add(365 days); // 12 months locking period addToBalance(foundationAddress, foundationSupply); stage = icoStages.Ready; // Initializes state } // ------------------------------------------------- // Opens early birds sale // ------------------------------------------------- function startCrowdfund() external onlyCrowdfund onlyDuringCrowdfund returns(bool) { require(stage == icoStages.Ready); stage = icoStages.EarlyBirds; addToBalance(crowdfundAddress, earlyBirdsSupply); return true; } // ------------------------------------------------- // Returns TRUE if early birds round is currently going on // ------------------------------------------------- function isEarlyBirdsStage() external view returns(bool) { return (stage == icoStages.EarlyBirds); } // ------------------------------------------------- // Sets the crowdfund address, can only be done once // ------------------------------------------------- function setCrowdfundAddress(address _crowdfundAddress) external onlyOwner nonZeroAddress(_crowdfundAddress) { require(crowdfundAddress == 0x0); crowdfundAddress = _crowdfundAddress; } // ------------------------------------------------- // Function for the Crowdfund to transfer tokens // ------------------------------------------------- function transferFromCrowdfund(address _to, uint256 _amount) external onlyCrowdfund nonZeroAmount(_amount) nonZeroAddress(_to) returns (bool success) { require(balanceOf(crowdfundAddress) >= _amount); decrementBalance(crowdfundAddress, _amount); addToBalance(_to, _amount); Transfer(0x0, _to, _amount); return true; } // ------------------------------------------------- // Releases Red team supply after locking period is passed // ------------------------------------------------- function releaseRedTeamTokens() external checkRedTeamLockingPeriod onlyOwner returns(bool success) { require(redTeamSupply > 0); addToBalance(redTeamAddress, redTeamSupply); Transfer(0x0, redTeamAddress, redTeamSupply); redTeamSupply = 0; return true; } // ------------------------------------------------- // Releases Marketing & strategic supply // ------------------------------------------------- function releaseMarketingTokens() external onlyOwner returns(bool success) { require(marketingSupply > 0); addToBalance(marketingAddress, marketingSupply); Transfer(0x0, marketingAddress, marketingSupply); marketingSupply = 0; return true; } // ------------------------------------------------- // Finalizes early birds round. If some RED are left, let them overflow to the crowdfund // ------------------------------------------------- function finalizeEarlyBirds() external onlyOwner returns (bool success) { require(stage == icoStages.EarlyBirds); uint256 amount = balanceOf(crowdfundAddress); addToBalance(crowdfundAddress, publicSupply); stage = icoStages.PublicSale; EarlyBirdsFinalized(amount); // event log return true; } // ------------------------------------------------- // Finalizes crowdfund. If there are leftover RED, let them overflow to foundation // ------------------------------------------------- function finalizeCrowdfund() external onlyCrowdfund { require(stage == icoStages.PublicSale); uint256 amount = balanceOf(crowdfundAddress); if (amount > 0) { accounts[crowdfundAddress] = 0; addToBalance(foundationAddress, amount); Transfer(crowdfundAddress, foundationAddress, amount); } stage = icoStages.Done; CrowdfundFinalized(amount); // event log } // ------------------------------------------------- // Changes Red Team wallet // ------------------------------------------------- function changeRedTeamAddress(address _wallet) external onlyOwner { redTeamAddress = _wallet; } // ------------------------------------------------- // Changes Marketing&Strategic wallet // ------------------------------------------------- function changeMarketingAddress(address _wallet) external onlyOwner { marketingAddress = _wallet; } // ------------------------------------------------- // Function to unlock 20% RED to private angels investors // ------------------------------------------------- function partialUnlockAngelsAccounts(address[] _batchOfAddresses) external onlyOwner notBeforeCrowdfundEnds returns (bool success) { require(unlock20Done == false); uint256 amount; address holder; for (uint256 i = 0; i < _batchOfAddresses.length; i++) { holder = _batchOfAddresses[i]; amount = angels[holder].mul(20).div(100); angels[holder] = angels[holder].sub(amount); addToBalance(holder, amount); } unlock20Done = true; return true; } // ------------------------------------------------- // Function to unlock all remaining RED to private angels investors (after 3 months) // ------------------------------------------------- function fullUnlockAngelsAccounts(address[] _batchOfAddresses) external onlyOwner checkAngelsLockingPeriod returns (bool success) { uint256 amount; address holder; for (uint256 i = 0; i < _batchOfAddresses.length; i++) { holder = _batchOfAddresses[i]; amount = angels[holder]; angels[holder] = 0; addToBalance(holder, amount); } return true; } // ------------------------------------------------- // Function to reserve RED to private angels investors (initially locked) // the amount of RED is in Wei // ------------------------------------------------- function deliverAngelsREDAccounts(address[] _batchOfAddresses, uint[] _amountOfRED) external onlyOwner onlyDuringCrowdfund returns (bool success) { for (uint256 i = 0; i < _batchOfAddresses.length; i++) { deliverAngelsREDBalance(_batchOfAddresses[i], _amountOfRED[i]); } return true; } /*----------------- Helper functions -----------------*/ // ------------------------------------------------- // If one address has contributed more than once, // the contributions will be aggregated // ------------------------------------------------- function deliverAngelsREDBalance(address _accountHolder, uint _amountOfBoughtRED) internal onlyOwner { require(angelAmountRemaining > 0); angels[_accountHolder] = angels[_accountHolder].add(_amountOfBoughtRED); Transfer(0x0, _accountHolder, _amountOfBoughtRED); angelAmountRemaining = angelAmountRemaining.sub(_amountOfBoughtRED); } // ------------------------------------------------- // Adds to balance // ------------------------------------------------- function addToBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].add(_amount); } // ------------------------------------------------- // Removes from balance // ------------------------------------------------- function decrementBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].sub(_amount); } } contract REDCrowdfund is Ownable { using SafeMath for uint; mapping (address => bool) whiteList; // Buyers whitelisting mapping bool public isOpen = false; // Is the crowd fund open? address public tokenAddress; // Address of the deployed RED token contract address public wallet; // Address of secure wallet to receive crowdfund contributions uint256 public weiRaised = 0; uint256 public startsAt; // Crowdfund starting time (Epoch format) uint256 public endsAt; // Crowdfund ending time (Epoch format) REDToken public RED; // Instance of the RED token contract /*----------------- Events -----------------*/ event WalletAddressChanged(address _wallet); // Triggered upon owner changing the wallet address event AmountRaised(address beneficiary, uint amountRaised); // Triggered upon crowdfund being finalized event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); // Triggered upon purchasing tokens /*----------------- Modifiers -----------------*/ modifier nonZeroAddress(address _to) { // Ensures an address is provided require(_to != 0x0); _; } modifier nonZeroValue() { // Ensures a non-zero value is passed require(msg.value > 0); _; } modifier crowdfundIsActive() { // Ensures the crowdfund is ongoing require(isOpen && now >= startsAt && now <= endsAt); _; } modifier notBeforeCrowdfundEnds(){ // Ensures actions can only happen after crowdfund ends require(now >= endsAt); _; } modifier onlyWhiteList() { // Ensures only whitelisted address can buy tokens require(whiteList[msg.sender]); _; } /*----------------- Crowdfunding API -----------------*/ // ------------------------------------------------- // Contract's constructor // ------------------------------------------------- function REDCrowdfund(address _tokenAddress) public { wallet = 0xc65f0d8a880f3145157117Af73fe2e6e8E60eF3c; // ICO wallet address startsAt = 1515398400; // Jan 8th 2018, 16:00, GMT+8 endsAt = 1517385600; // Jan 31th 2018, 16:00, GMT+8 tokenAddress = _tokenAddress; // RED token Address RED = REDToken(tokenAddress); } // ------------------------------------------------- // Changes main contribution wallet // ------------------------------------------------- function changeWalletAddress(address _wallet) external onlyOwner { wallet = _wallet; WalletAddressChanged(_wallet); } // ------------------------------------------------- // Opens the crowdfunding // ------------------------------------------------- function openCrowdfund() external onlyOwner returns (bool success) { require(isOpen == false); RED.startCrowdfund(); isOpen = true; return true; } // ------------------------------------------------- // Function to buy RED. One can also buy RED by calling this function directly and send // it to another destination. // ------------------------------------------------- function buyTokens(address _to) public crowdfundIsActive onlyWhiteList nonZeroAddress(_to) nonZeroValue payable { uint256 weiAmount = msg.value; uint256 tokens; uint price = 2500; if (RED.isEarlyBirdsStage()) {price = 2750;} // 10% discount for early birds tokens = weiAmount * price; weiRaised = weiRaised.add(weiAmount); wallet.transfer(weiAmount); if (!RED.transferFromCrowdfund(_to, tokens)) {revert();} TokenPurchase(_to, weiAmount, tokens); } // ------------------------------------------------- // Closes the crowdfunding. Any unsold RED will go back to the foundation. // ------------------------------------------------- function closeCrowdfund() external notBeforeCrowdfundEnds onlyOwner returns (bool success) { AmountRaised(wallet, weiRaised); RED.finalizeCrowdfund(); isOpen = false; return true; } // ------------------------------------------------- // Function to whitelist buyers // ------------------------------------------------- function whitelistAccounts(address[] _batchOfAddresses) external onlyOwner returns (bool success) { for (uint256 i = 0; i < _batchOfAddresses.length; i++) { whiteList[_batchOfAddresses[i]] = true; } return true; } /*----------------- Entry point -----------------*/ // ------------------------------------------------- // To contribute, send a value transaction to the crowdfund address. // Please include at least 100000 gas. // ------------------------------------------------- function () public payable { buyTokens(msg.sender); } }
------------------------------------------------- Adds to balance -------------------------------------------------
function addToBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].add(_amount); }
5,346,922
./partial_match/1/0x4D3e53EB6175d9aE9eafAbc21FC5C44153F99079/sources/chalUniswapMining.sol
claim CHAL based on current state
function claimchal() public whenNotPaused { updateMiningState(); uint claimablechal = claimablechal(msg.sender); stakerIndexes[msg.sender] = miningStateIndex; if(claimablechal > 0){ stakerClaimed[msg.sender] = stakerClaimed[msg.sender].add(claimablechal); totalClaimed = totalClaimed.add(claimablechal); chalToken.transfer(msg.sender, claimablechal); emit Claimedchal(msg.sender, claimablechal, stakerClaimed[msg.sender]); } }
2,672,849
// ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // ODIN token contract // ---------------------------------------------------------------------------- pragma solidity ^0.4.21; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address private newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { owner = _newOwner; OwnershipTransferred(msg.sender, _newOwner); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract OdinToken is ERC20Interface, Owned { using SafeMath for uint256; string public symbol; string public name; uint8 public decimals; uint private _totalSupply; bool private _whitelistAll; struct balanceData { bool locked; uint balance; uint airDropQty; } mapping(address => balanceData) balances; mapping(address => mapping(address => uint)) allowed; /** * @dev Constructor for Odin creation * @dev Initially assigns the totalSupply to the contract creator */ function OdinToken() public { // owner of this contract address owner; owner = msg.sender; symbol = "ODIN"; name = "ODIN Token"; decimals = 18; _whitelistAll=false; _totalSupply = 100000000000000000000000; balances[owner].balance = _totalSupply; Transfer(address(0), msg.sender, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[owner].balance; } // ------------------------------------------------------------------------ // whitelist an address // ------------------------------------------------------------------------ function whitelistAddress(address to) public returns (bool) { require(msg.sender == owner); balances[to].airDropQty = 0; return true; } /** * @dev Whitelist all addresses early * @return An bool showing if the function succeeded. */ function whitelistAllAddresses() public returns (bool) { require (msg.sender == owner); _whitelistAll = true; return true; } /** * @dev Gets the balance of the specified address. * @param tokenOwner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner].balance; } /** * @dev transfer token for a specified address * @param to The address to transfer to. * @param tokens The amount to be transferred. */ function transfer(address to, uint tokens) public returns (bool success) { require (msg.sender != to); // cannot send to yourself require(to != address(0)); // cannot send to address(0) require(tokens <= balances[msg.sender].balance); // do you have enough to send? uint sep_1_2018_ts = 1535760000; uint dec_31_2018_ts = 1546214400; uint mar_31_2019_ts = 1553990400; uint jun_30_2019_ts = 1561852800; uint oct_2_2019_ts = 1569974400; if (!_whitelistAll) { // do not allow transfering air dropped tokens prior to Sep 1 2018 if (msg.sender != owner && block.timestamp < sep_1_2018_ts && balances[msg.sender].airDropQty>0) { require(tokens < 0); } // after Sep 1 2018 and before Dec 31, 2018, do not allow transfering more than 10% of air dropped tokens if (msg.sender != owner && block.timestamp < dec_31_2018_ts && balances[msg.sender].airDropQty>0) { require((balances[msg.sender].balance - tokens) >= (balances[msg.sender].airDropQty / 10 * 9)); } // after Dec 31 2018 and before March 31, 2019, do not allow transfering more than 25% of air dropped tokens if (msg.sender != owner && block.timestamp < mar_31_2019_ts && balances[msg.sender].airDropQty>0) { require((balances[msg.sender].balance - tokens) >= balances[msg.sender].airDropQty / 4 * 3); } // after March 31, 2019 and before Jun 30, 2019, do not allow transfering more than 50% of air dropped tokens if (msg.sender != owner && block.timestamp < jun_30_2019_ts && balances[msg.sender].airDropQty>0) { require((balances[msg.sender].balance - tokens) >= balances[msg.sender].airDropQty / 2); } // after Jun 30, 2019 and before Oct 2, 2019, do not allow transfering more than 75% of air dropped tokens if (msg.sender != owner && block.timestamp < jun_30_2019_ts && balances[msg.sender].airDropQty>0) { require((balances[msg.sender].balance - tokens) >= balances[msg.sender].airDropQty / 4); } // otherwise, no transfer restrictions } balances[msg.sender].balance = balances[msg.sender].balance.sub(tokens); balances[to].balance = balances[to].balance.add(tokens); if (msg.sender == owner) { balances[to].airDropQty = balances[to].airDropQty.add(tokens); } Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // not implemented // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { return false; } // ------------------------------------------------------------------------ // not implemented // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { return false; } // ------------------------------------------------------------------------ // not implemented // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return 0; } // ------------------------------------------------------------------------ // not implemented // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { return false; } function () { //if ether is sent to this address, send it back. throw; } }
------------------------------------------------------------------------ whitelist an address ------------------------------------------------------------------------
function whitelistAddress(address to) public returns (bool) { require(msg.sender == owner); balances[to].airDropQty = 0; return true; }
12,074,687
./partial_match/80001/0x5c653357289333a22AF4c4b4DD61d930ACdA09A0/sources/contracts/upgradeable/XPassportV1.sol
Check the eqaulity of the two strings -> keccak256() -> converts input to a unique 32-byte hash, abi.encodePacked() -> encode string to bytes array
function isEqualString(string memory first, string memory second) private pure returns (bool) { return keccak256(abi.encodePacked(first)) == keccak256(abi.encodePacked(second)); }
8,799,464
./partial_match/1/0x01BD87bC97e27CB11e3c45dAB9B59Bc44edC4fc6/sources/TrueFiPool2.sol
Currency token balance return Currency token balance/
function currencyBalance() internal view returns (uint256) { return token.balanceOf(address(this)).sub(claimableFees); }
4,004,178
/* solhint-disable avoid-low-level-calls */ /* solhint-disable no-inline-assembly */ /* solhint-disable not-rely-on-time */ /* solhint-disable avoid-tx-origin */ /* solhint-disable bracket-align */ // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; // #if ENABLE_CONSOLE_LOG import "hardhat/console.sol"; // #endif import "./utils/MinLibBytes.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./utils/GsnUtils.sol"; import "./utils/GsnEip712Library.sol"; import "./utils/RelayHubValidator.sol"; import "./utils/GsnTypes.sol"; import "./interfaces/IRelayHub.sol"; import "./interfaces/IPaymaster.sol"; import "./forwarder/IForwarder.sol"; import "./interfaces/IStakeManager.sol"; import "./interfaces/IRelayRegistrar.sol"; import "./interfaces/IStakeManager.sol"; /** * @title The RelayHub Implementation * @notice This contract implements the `IRelayHub` interface for the EVM-compatible networks. */ contract RelayHub is IRelayHub, Ownable, ERC165 { using ERC165Checker for address; using Address for address; address private constant DRY_RUN_ADDRESS = 0x0000000000000000000000000000000000000000; /// @inheritdoc IRelayHub function versionHub() override virtual public pure returns (string memory){ return "3.0.0-alpha.5+opengsn.hub.irelayhub"; } IStakeManager internal immutable stakeManager; address internal immutable penalizer; address internal immutable batchGateway; address internal immutable relayRegistrar; RelayHubConfig internal config; /// @inheritdoc IRelayHub function getConfiguration() public override view returns (RelayHubConfig memory) { return config; } /// @inheritdoc IRelayHub function setConfiguration(RelayHubConfig memory _config) public override onlyOwner { require(_config.devFee < 100, "dev fee too high"); config = _config; emit RelayHubConfigured(config); } // maps ERC-20 token address to a minimum stake for it mapping(IERC20 => uint256) internal minimumStakePerToken; /// @inheritdoc IRelayHub function setMinimumStakes(IERC20[] memory token, uint256[] memory minimumStake) public override onlyOwner { require(token.length == minimumStake.length, "setMinimumStakes: wrong length"); for (uint256 i = 0; i < token.length; i++) { minimumStakePerToken[token[i]] = minimumStake[i]; emit StakingTokenDataChanged(address(token[i]), minimumStake[i]); } } // maps relay worker's address to its manager's address mapping(address => address) internal workerToManager; // maps relay managers to the number of their workers mapping(address => uint256) internal workerCount; mapping(address => uint256) internal balances; uint256 internal immutable creationBlock; uint256 internal deprecationTime = type(uint256).max; constructor ( IStakeManager _stakeManager, address _penalizer, address _batchGateway, address _relayRegistrar, RelayHubConfig memory _config ) { creationBlock = block.number; stakeManager = _stakeManager; penalizer = _penalizer; batchGateway = _batchGateway; relayRegistrar = _relayRegistrar; setConfiguration(_config); } /// @inheritdoc IRelayHub function getCreationBlock() external override virtual view returns (uint256){ return creationBlock; } /// @inheritdoc IRelayHub function getDeprecationTime() external override view returns (uint256) { return deprecationTime; } /// @inheritdoc IRelayHub function getStakeManager() external override view returns (IStakeManager) { return stakeManager; } /// @inheritdoc IRelayHub function getPenalizer() external override view returns (address) { return penalizer; } /// @inheritdoc IRelayHub function getBatchGateway() external override view returns (address) { return batchGateway; } /// @inheritdoc IRelayHub function getRelayRegistrar() external override view returns (address) { return relayRegistrar; } /// @inheritdoc IRelayHub function getMinimumStakePerToken(IERC20 token) external override view returns (uint256) { return minimumStakePerToken[token]; } /// @inheritdoc IRelayHub function getWorkerManager(address worker) external override view returns (address) { return workerToManager[worker]; } /// @inheritdoc IRelayHub function getWorkerCount(address manager) external override view returns (uint256) { return workerCount[manager]; } /// @inheritdoc IERC165 function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) { return interfaceId == type(IRelayHub).interfaceId || interfaceId == type(Ownable).interfaceId || super.supportsInterface(interfaceId); } /// @inheritdoc IRelayHub function onRelayServerRegistered(address relayManager) external override { require(msg.sender == relayRegistrar, "caller is not relay registrar"); verifyRelayManagerStaked(relayManager); require(workerCount[relayManager] > 0, "no relay workers"); stakeManager.updateRelayKeepaliveTime(relayManager); } /// @inheritdoc IRelayHub function addRelayWorkers(address[] calldata newRelayWorkers) external override { address relayManager = msg.sender; uint256 newWorkerCount = workerCount[relayManager] + newRelayWorkers.length; workerCount[relayManager] = newWorkerCount; require(newWorkerCount <= config.maxWorkerCount, "too many workers"); verifyRelayManagerStaked(relayManager); for (uint256 i = 0; i < newRelayWorkers.length; i++) { require(workerToManager[newRelayWorkers[i]] == address(0), "this worker has a manager"); workerToManager[newRelayWorkers[i]] = relayManager; } emit RelayWorkersAdded(relayManager, newRelayWorkers, newWorkerCount); } /// @inheritdoc IRelayHub function depositFor(address target) public virtual override payable { require(target.supportsInterface(type(IPaymaster).interfaceId), "target is not a valid IPaymaster"); uint256 amount = msg.value; balances[target] = balances[target] + amount; emit Deposited(target, msg.sender, amount); } /// @inheritdoc IRelayHub function balanceOf(address target) external override view returns (uint256) { return balances[target]; } /// @inheritdoc IRelayHub function withdraw(address payable dest, uint256 amount) public override { uint256[] memory amounts = new uint256[](1); address payable[] memory destinations = new address payable[](1); amounts[0] = amount; destinations[0] = dest; withdrawMultiple(destinations, amounts); } /// @inheritdoc IRelayHub function withdrawMultiple(address payable[] memory dest, uint256[] memory amount) public override { address payable account = payable(msg.sender); for (uint256 i = 0; i < amount.length; i++) { // #if ENABLE_CONSOLE_LOG console.log("withdrawMultiple %s %s %s", balances[account], dest[i], amount[i]); // #endif uint256 balance = balances[account]; require(balance >= amount[i], "insufficient funds"); balances[account] = balance - amount[i]; (bool success, ) = dest[i].call{value: amount[i]}(""); require(success, "Transfer failed."); emit Withdrawn(account, dest[i], amount[i]); } } function verifyGasAndDataLimits( uint256 maxAcceptanceBudget, GsnTypes.RelayRequest calldata relayRequest, uint256 initialGasLeft ) private view returns (IPaymaster.GasAndDataLimits memory gasAndDataLimits, uint256 maxPossibleGas) { gasAndDataLimits = IPaymaster(relayRequest.relayData.paymaster).getGasAndDataLimits{gas:50000}(); require(msg.data.length <= gasAndDataLimits.calldataSizeLimit, "msg.data exceeded limit" ); require(maxAcceptanceBudget >= gasAndDataLimits.acceptanceBudget, "acceptance budget too high"); require(gasAndDataLimits.acceptanceBudget >= gasAndDataLimits.preRelayedCallGasLimit, "acceptance budget too low"); maxPossibleGas = relayRequest.relayData.transactionCalldataGasUsed + initialGasLeft; uint256 maxPossibleCharge = calculateCharge( maxPossibleGas, relayRequest.relayData ); // We don't yet know how much gas will be used by the recipient, so we make sure there are enough funds to pay // for the maximum possible charge. require(maxPossibleCharge <= balances[relayRequest.relayData.paymaster], "Paymaster balance too low"); } struct RelayCallData { bool success; bytes4 functionSelector; uint256 initialGasLeft; bytes recipientContext; bytes relayedCallReturnValue; IPaymaster.GasAndDataLimits gasAndDataLimits; RelayCallStatus status; uint256 innerGasUsed; uint256 maxPossibleGas; uint256 innerGasLimit; uint256 gasBeforeInner; uint256 gasUsed; uint256 devCharge; bytes retData; address relayManager; bytes32 relayRequestId; } /// @inheritdoc IRelayHub function relayCall( uint256 maxAcceptanceBudget, GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData ) external override returns ( bool paymasterAccepted, uint256 charge, IRelayHub.RelayCallStatus status, bytes memory returnValue) { RelayCallData memory vars; vars.initialGasLeft = aggregateGasleft(); vars.relayRequestId = GsnUtils.getRelayRequestID(relayRequest, signature); // #if ENABLE_CONSOLE_LOG console.log("relayCall relayRequestId"); console.logBytes32(vars.relayRequestId); console.log("relayCall relayRequest.request.from", relayRequest.request.from); console.log("relayCall relayRequest.request.to", relayRequest.request.to); console.log("relayCall relayRequest.request.value", relayRequest.request.value); console.log("relayCall relayRequest.request.gas", relayRequest.request.gas); console.log("relayCall relayRequest.request.nonce", relayRequest.request.nonce); console.log("relayCall relayRequest.request.validUntilTime", relayRequest.request.validUntilTime); console.log("relayCall relayRequest.relayData.maxFeePerGas", relayRequest.relayData.maxFeePerGas); console.log("relayCall relayRequest.relayData.maxPriorityFeePerGas", relayRequest.relayData.maxPriorityFeePerGas); console.log("relayCall relayRequest.relayData.pctRelayFee", relayRequest.relayData.pctRelayFee); console.log("relayCall relayRequest.relayData.baseRelayFee", relayRequest.relayData.baseRelayFee); console.log("relayCall relayRequest.relayData.transactionCalldataGasUsed", relayRequest.relayData.transactionCalldataGasUsed); console.log("relayCall relayRequest.relayData.relayWorker", relayRequest.relayData.relayWorker); console.log("relayCall relayRequest.relayData.paymaster", relayRequest.relayData.paymaster); console.log("relayCall relayRequest.relayData.forwarder", relayRequest.relayData.forwarder); console.log("relayCall relayRequest.relayData.clientId", relayRequest.relayData.clientId); console.log("relayCall signature"); console.logBytes(signature); console.log("relayCall approvalData"); console.logBytes(approvalData); console.log("relayCall relayRequest.request.data"); console.logBytes(relayRequest.request.data); console.log("relayCall relayRequest.relayData.paymasterData"); console.logBytes(relayRequest.relayData.paymasterData); console.log("relayCall maxAcceptanceBudget", maxAcceptanceBudget); // #endif require(!isDeprecated(), "hub deprecated"); vars.functionSelector = relayRequest.request.data.length>=4 ? MinLibBytes.readBytes4(relayRequest.request.data, 0) : bytes4(0); if (msg.sender != batchGateway && tx.origin != DRY_RUN_ADDRESS) { require(signature.length != 0, "missing signature or bad gateway"); require(msg.sender == tx.origin, "relay worker must be EOA"); require(msg.sender == relayRequest.relayData.relayWorker, "Not a right worker"); } if (tx.origin != DRY_RUN_ADDRESS) { vars.relayManager = workerToManager[relayRequest.relayData.relayWorker]; require(vars.relayManager != address(0), "Unknown relay worker"); verifyRelayManagerStaked(vars.relayManager); } (vars.gasAndDataLimits, vars.maxPossibleGas) = verifyGasAndDataLimits(maxAcceptanceBudget, relayRequest, vars.initialGasLeft); RelayHubValidator.verifyTransactionPacking(relayRequest,signature,approvalData); { //How much gas to pass down to innerRelayCall. must be lower than the default 63/64 // actually, min(gasleft*63/64, gasleft-GAS_RESERVE) might be enough. vars.innerGasLimit = gasleft()*63/64- config.gasReserve; vars.gasBeforeInner = aggregateGasleft(); /* Preparing to calculate "gasUseWithoutPost": MPG = calldataGasUsage + vars.initialGasLeft :: max possible gas, an approximate gas limit for the current transaction GU1 = MPG - gasleft(called right before innerRelayCall) :: gas actually used by current transaction until that point GU2 = innerGasLimit - gasleft(called inside the innerRelayCall just before preRelayedCall) :: gas actually used by innerRelayCall before calling postRelayCall GWP1 = GU1 + GU2 :: gas actually used by the entire transaction before calling postRelayCall TGO = config.gasOverhead + config.postOverhead :: extra that will be added to the charge to cover hidden costs GWP = GWP1 + TGO :: transaction "gas used without postRelayCall" */ uint256 _tmpInitialGas = relayRequest.relayData.transactionCalldataGasUsed + vars.initialGasLeft + vars.innerGasLimit + config.gasOverhead + config.postOverhead; // Calls to the recipient are performed atomically inside an inner transaction which may revert in case of // errors in the recipient. In either case (revert or regular execution) the return data encodes the // RelayCallStatus value. (bool success, bytes memory relayCallStatus) = address(this).call{gas:vars.innerGasLimit}( abi.encodeWithSelector(RelayHub.innerRelayCall.selector, relayRequest, signature, approvalData, vars.gasAndDataLimits, _tmpInitialGas - aggregateGasleft(), /* totalInitialGas */ vars.maxPossibleGas ) ); vars.success = success; vars.innerGasUsed = vars.gasBeforeInner-aggregateGasleft(); (vars.status, vars.relayedCallReturnValue) = abi.decode(relayCallStatus, (RelayCallStatus, bytes)); if ( vars.relayedCallReturnValue.length>0 ) { emit TransactionResult(vars.status, vars.relayedCallReturnValue); } } { if (!vars.success) { //Failure cases where the PM doesn't pay if (vars.status == RelayCallStatus.RejectedByPreRelayed || (vars.innerGasUsed <= vars.gasAndDataLimits.acceptanceBudget + relayRequest.relayData.transactionCalldataGasUsed) && ( vars.status == RelayCallStatus.RejectedByForwarder || vars.status == RelayCallStatus.RejectedByRecipientRevert //can only be thrown if rejectOnRecipientRevert==true )) { emit TransactionRejectedByPaymaster( vars.relayManager, relayRequest.relayData.paymaster, vars.relayRequestId, relayRequest.request.from, relayRequest.request.to, msg.sender, vars.functionSelector, vars.innerGasUsed, vars.relayedCallReturnValue); return (false, 0, vars.status, vars.relayedCallReturnValue); } } // We now perform the actual charge calculation, based on the measured gas used vars.gasUsed = relayRequest.relayData.transactionCalldataGasUsed + (vars.initialGasLeft - aggregateGasleft()) + config.gasOverhead; charge = calculateCharge(vars.gasUsed, relayRequest.relayData); vars.devCharge = calculateDevCharge(charge); balances[relayRequest.relayData.paymaster] = balances[relayRequest.relayData.paymaster] - charge; balances[vars.relayManager] = balances[vars.relayManager] + (charge - vars.devCharge); if (vars.devCharge > 0) { // save some gas in case of zero dev charge balances[config.devAddress] = balances[config.devAddress] + vars.devCharge; } { address from = relayRequest.request.from; address to = relayRequest.request.to; address paymaster = relayRequest.relayData.paymaster; emit TransactionRelayed( vars.relayManager, msg.sender, vars.relayRequestId, from, to, paymaster, vars.functionSelector, vars.status, charge); } // avoid variable size memory copying after gas calculation completed on-chain if (tx.origin == DRY_RUN_ADDRESS) { return (true, charge, vars.status, vars.relayedCallReturnValue); } return (true, charge, vars.status, ""); } } struct InnerRelayCallData { uint256 initialGasLeft; uint256 gasUsedToCallInner; uint256 balanceBefore; bytes32 preReturnValue; bool relayedCallSuccess; bytes relayedCallReturnValue; bytes recipientContext; bytes data; bool rejectOnRecipientRevert; } /** * @notice This method can only by called by this `RelayHub`. * It wraps the execution of the `RelayRequest` in a revertable frame context. */ function innerRelayCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, IPaymaster.GasAndDataLimits calldata gasAndDataLimits, uint256 totalInitialGas, uint256 maxPossibleGas ) external returns (RelayCallStatus, bytes memory) { InnerRelayCallData memory vars; vars.initialGasLeft = aggregateGasleft(); vars.gasUsedToCallInner = totalInitialGas - gasleft(); // A new gas measurement is performed inside innerRelayCall, since // due to EIP150 available gas amounts cannot be directly compared across external calls // This external function can only be called by RelayHub itself, creating an internal transaction. Calls to the // recipient (preRelayedCall, the relayedCall, and postRelayedCall) are called from inside this transaction. require(msg.sender == address(this), "Must be called by RelayHub"); // If either pre or post reverts, the whole internal transaction will be reverted, reverting all side effects on // the recipient. The recipient will still be charged for the used gas by the relay. // The paymaster is no allowed to withdraw balance from RelayHub during a relayed transaction. We check pre and // post state to ensure this doesn't happen. vars.balanceBefore = balances[relayRequest.relayData.paymaster]; // First preRelayedCall is executed. // Note: we open a new block to avoid growing the stack too much. vars.data = abi.encodeWithSelector( IPaymaster.preRelayedCall.selector, relayRequest, signature, approvalData, maxPossibleGas ); { bool success; bytes memory retData; (success, retData) = relayRequest.relayData.paymaster.call{gas:gasAndDataLimits.preRelayedCallGasLimit}(vars.data); if (!success) { GsnEip712Library.truncateInPlace(retData); revertWithStatus(RelayCallStatus.RejectedByPreRelayed, retData); } (vars.recipientContext, vars.rejectOnRecipientRevert) = abi.decode(retData, (bytes,bool)); } // The actual relayed call is now executed. The sender's address is appended at the end of the transaction data { bool forwarderSuccess; (forwarderSuccess, vars.relayedCallSuccess, vars.relayedCallReturnValue) = GsnEip712Library.execute(relayRequest, signature); if ( !forwarderSuccess ) { revertWithStatus(RelayCallStatus.RejectedByForwarder, vars.relayedCallReturnValue); } if (vars.rejectOnRecipientRevert && !vars.relayedCallSuccess) { // we trusted the recipient, but it reverted... revertWithStatus(RelayCallStatus.RejectedByRecipientRevert, vars.relayedCallReturnValue); } } // Finally, postRelayedCall is executed, with the relayedCall execution's status and a charge estimate // We now determine how much the recipient will be charged, to pass this value to postRelayedCall for accurate // accounting. vars.data = abi.encodeWithSelector( IPaymaster.postRelayedCall.selector, vars.recipientContext, vars.relayedCallSuccess, vars.gasUsedToCallInner + (vars.initialGasLeft - aggregateGasleft()), /*gasUseWithoutPost*/ relayRequest.relayData ); { (bool successPost,bytes memory ret) = relayRequest.relayData.paymaster.call{gas:gasAndDataLimits.postRelayedCallGasLimit}(vars.data); if (!successPost) { revertWithStatus(RelayCallStatus.PostRelayedFailed, ret); } } if (balances[relayRequest.relayData.paymaster] < vars.balanceBefore) { revertWithStatus(RelayCallStatus.PaymasterBalanceChanged, ""); } return (vars.relayedCallSuccess ? RelayCallStatus.OK : RelayCallStatus.RelayedCallFailed, vars.relayedCallReturnValue); } /** * @dev Reverts the transaction with return data set to the ABI encoding of the status argument (and revert reason data) */ function revertWithStatus(RelayCallStatus status, bytes memory ret) private pure { bytes memory data = abi.encode(status, ret); GsnEip712Library.truncateInPlace(data); assembly { let dataSize := mload(data) let dataPtr := add(data, 32) revert(dataPtr, dataSize) } } /// @inheritdoc IRelayHub function calculateDevCharge(uint256 charge) public override virtual view returns (uint256){ if (config.devFee == 0){ // save some gas in case of zero dev charge return 0; } unchecked { return charge * config.devFee / 100; } } /// @inheritdoc IRelayHub function calculateCharge(uint256 gasUsed, GsnTypes.RelayData calldata relayData) public override virtual view returns (uint256) { uint256 basefee; if (relayData.maxFeePerGas == relayData.maxPriorityFeePerGas) { basefee = 0; } else { basefee = block.basefee; } uint256 chargeableGasPrice = Math.min(relayData.maxFeePerGas, Math.min(tx.gasprice, basefee + relayData.maxPriorityFeePerGas)); return relayData.baseRelayFee + (gasUsed * chargeableGasPrice * (relayData.pctRelayFee + 100)) / 100; } /// @inheritdoc IRelayHub function verifyRelayManagerStaked(address relayManager) public override view { (IStakeManager.StakeInfo memory info, bool isHubAuthorized) = stakeManager.getStakeInfo(relayManager); uint256 minimumStake = minimumStakePerToken[info.token]; require(info.token != IERC20(address(0)), "relay manager not staked"); require(info.stake >= minimumStake, "stake amount is too small"); require(minimumStake != 0, "staking this token is forbidden"); require(info.unstakeDelay >= config.minimumUnstakeDelay, "unstake delay is too small"); require(info.withdrawTime == 0, "stake has been withdrawn"); require(isHubAuthorized, "this hub is not authorized by SM"); } /// @inheritdoc IRelayHub function deprecateHub(uint256 _deprecationTime) public override onlyOwner { require(!isDeprecated(), "Already deprecated"); deprecationTime = _deprecationTime; emit HubDeprecated(deprecationTime); } /// @inheritdoc IRelayHub function isDeprecated() public override view returns (bool) { return block.timestamp >= deprecationTime; } /// @notice Prevents any address other than the `Penalizer` from calling this method. modifier penalizerOnly () { require(msg.sender == penalizer, "Not penalizer"); _; } /// @inheritdoc IRelayHub function penalize(address relayWorker, address payable beneficiary) external override penalizerOnly { address relayManager = workerToManager[relayWorker]; // The worker must be controlled by a manager with a locked stake require(relayManager != address(0), "Unknown relay worker"); (IStakeManager.StakeInfo memory stakeInfo,) = stakeManager.getStakeInfo(relayManager); require(stakeInfo.stake > 0, "relay manager not staked"); stakeManager.penalizeRelayManager(relayManager, beneficiary, stakeInfo.stake); } /// @inheritdoc IRelayHub function isRelayEscheatable(address relayManager) public view override returns (bool){ return stakeManager.isRelayEscheatable(relayManager); } /// @inheritdoc IRelayHub function escheatAbandonedRelayBalance(address relayManager) external override onlyOwner { require(stakeManager.isRelayEscheatable(relayManager), "relay server not escheatable yet"); uint256 balance = balances[relayManager]; balances[relayManager] = 0; balances[config.devAddress] = balances[config.devAddress] + balance; emit AbandonedRelayManagerBalanceEscheated(relayManager, balance); } /// @inheritdoc IRelayHub function aggregateGasleft() public override virtual view returns (uint256){ return gasleft(); } }
This method can only by called by this `RelayHub`. It wraps the execution of the `RelayRequest` in a revertable frame context./ A new gas measurement is performed inside innerRelayCall, since due to EIP150 available gas amounts cannot be directly compared across external calls This external function can only be called by RelayHub itself, creating an internal transaction. Calls to the recipient (preRelayedCall, the relayedCall, and postRelayedCall) are called from inside this transaction. If either pre or post reverts, the whole internal transaction will be reverted, reverting all side effects on the recipient. The recipient will still be charged for the used gas by the relay. The paymaster is no allowed to withdraw balance from RelayHub during a relayed transaction. We check pre and post state to ensure this doesn't happen. First preRelayedCall is executed. Note: we open a new block to avoid growing the stack too much.
{ InnerRelayCallData memory vars; vars.initialGasLeft = aggregateGasleft(); vars.gasUsedToCallInner = totalInitialGas - gasleft(); require(msg.sender == address(this), "Must be called by RelayHub"); vars.balanceBefore = balances[relayRequest.relayData.paymaster]; vars.data = abi.encodeWithSelector( IPaymaster.preRelayedCall.selector, relayRequest, signature, approvalData, maxPossibleGas ); function innerRelayCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, IPaymaster.GasAndDataLimits calldata gasAndDataLimits, uint256 totalInitialGas, uint256 maxPossibleGas ) external returns (RelayCallStatus, bytes memory) { bool success; bytes memory retData; if (!success) { GsnEip712Library.truncateInPlace(retData); revertWithStatus(RelayCallStatus.RejectedByPreRelayed, retData); } (vars.recipientContext, vars.rejectOnRecipientRevert) = abi.decode(retData, (bytes,bool)); } (success, retData) = relayRequest.relayData.paymaster.call{gas:gasAndDataLimits.preRelayedCallGasLimit}(vars.data); function innerRelayCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, IPaymaster.GasAndDataLimits calldata gasAndDataLimits, uint256 totalInitialGas, uint256 maxPossibleGas ) external returns (RelayCallStatus, bytes memory) { bool success; bytes memory retData; if (!success) { GsnEip712Library.truncateInPlace(retData); revertWithStatus(RelayCallStatus.RejectedByPreRelayed, retData); } (vars.recipientContext, vars.rejectOnRecipientRevert) = abi.decode(retData, (bytes,bool)); } { bool forwarderSuccess; (forwarderSuccess, vars.relayedCallSuccess, vars.relayedCallReturnValue) = GsnEip712Library.execute(relayRequest, signature); if ( !forwarderSuccess ) { revertWithStatus(RelayCallStatus.RejectedByForwarder, vars.relayedCallReturnValue); } if (vars.rejectOnRecipientRevert && !vars.relayedCallSuccess) { revertWithStatus(RelayCallStatus.RejectedByRecipientRevert, vars.relayedCallReturnValue); } } IPaymaster.postRelayedCall.selector, vars.recipientContext, vars.relayedCallSuccess, vars.gasUsedToCallInner + (vars.initialGasLeft - aggregateGasleft()), /*gasUseWithoutPost*/ relayRequest.relayData ); { bool forwarderSuccess; (forwarderSuccess, vars.relayedCallSuccess, vars.relayedCallReturnValue) = GsnEip712Library.execute(relayRequest, signature); if ( !forwarderSuccess ) { revertWithStatus(RelayCallStatus.RejectedByForwarder, vars.relayedCallReturnValue); } if (vars.rejectOnRecipientRevert && !vars.relayedCallSuccess) { revertWithStatus(RelayCallStatus.RejectedByRecipientRevert, vars.relayedCallReturnValue); } } IPaymaster.postRelayedCall.selector, vars.recipientContext, vars.relayedCallSuccess, vars.gasUsedToCallInner + (vars.initialGasLeft - aggregateGasleft()), /*gasUseWithoutPost*/ relayRequest.relayData ); { bool forwarderSuccess; (forwarderSuccess, vars.relayedCallSuccess, vars.relayedCallReturnValue) = GsnEip712Library.execute(relayRequest, signature); if ( !forwarderSuccess ) { revertWithStatus(RelayCallStatus.RejectedByForwarder, vars.relayedCallReturnValue); } if (vars.rejectOnRecipientRevert && !vars.relayedCallSuccess) { revertWithStatus(RelayCallStatus.RejectedByRecipientRevert, vars.relayedCallReturnValue); } } IPaymaster.postRelayedCall.selector, vars.recipientContext, vars.relayedCallSuccess, vars.gasUsedToCallInner + (vars.initialGasLeft - aggregateGasleft()), /*gasUseWithoutPost*/ relayRequest.relayData ); vars.data = abi.encodeWithSelector( { if (!successPost) { revertWithStatus(RelayCallStatus.PostRelayedFailed, ret); } } (bool successPost,bytes memory ret) = relayRequest.relayData.paymaster.call{gas:gasAndDataLimits.postRelayedCallGasLimit}(vars.data); { if (!successPost) { revertWithStatus(RelayCallStatus.PostRelayedFailed, ret); } } if (balances[relayRequest.relayData.paymaster] < vars.balanceBefore) { revertWithStatus(RelayCallStatus.PaymasterBalanceChanged, ""); } return (vars.relayedCallSuccess ? RelayCallStatus.OK : RelayCallStatus.RelayedCallFailed, vars.relayedCallReturnValue); }
6,429,698
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/access/IAccessControl.sol pragma solidity ^0.8.0; interface IAccessControl { event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); 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; } // File: @openzeppelin/contracts/utils/Context.sol abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/utils/Strings.sol library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } 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); } function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol 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/access/AccessControl.sol 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; modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } 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) ) ) ); } } function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: @openzeppelin/contracts/access/Ownable.sol abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { _setOwner(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/security/Pausable.sol abstract contract Pausable is Context { event Paused(address account); event Unpaused(address account); bool private _paused; constructor() { _paused = false; } function paused() public view virtual returns (bool) { return _paused; } modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol abstract contract ReentrancyGuard { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } 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; _; _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol 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); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // File: contracts/libraries/ERC20.sol 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; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } 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; } 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); _afterTokenTransfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: contracts/SoulPower.sol contract SoulPower is ERC20('SoulPower', 'SOUL'), AccessControl { address public supreme; // supreme divine bytes32 public anunnaki; // admin role bytes32 public thoth; // minter role bytes32 public constant DOMAIN_TYPEHASH = // EIP-712 typehash for the contract's domain keccak256('EIP712Domain(string name,uint chainId,address verifyingContract)'); bytes32 public constant DELEGATION_TYPEHASH = // EIP-712 typehash for the delegation struct used by the contract keccak256('Delegation(address delegatee,uint nonce,uint expiry)'); // mappings for user accounts (address) mapping(address => mapping(uint => Checkpoint)) public checkpoints; // vote checkpoints mapping(address => uint) public numCheckpoints; // checkpoint count mapping(address => uint) public nonces; // signing / validating states mapping(address => address) internal _delegates; // each accounts' delegate struct Checkpoint { // checkpoint for marking number of votes from a given timestamp uint fromTime; uint votes; } event NewSupreme(address supreme); event Rethroned(bytes32 role, address oldAccount, address newAccount); event DelegateChanged( // emitted when an account changes its delegate address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); event DelegateVotesChanged( // emitted when a delegate account's vote balance changes address indexed delegate, uint previousBalance, uint newBalance ); // restricted to the house of the role passed as an object to obey modifier obey(bytes32 role) { _checkRole(role, _msgSender()); _; } // channels the authority vested in anunnaki and thoth to the supreme constructor() { supreme = msg.sender; // WARNING: set to multi-sig when deploying anunnaki = keccak256('anunnaki'); // alpha supreme thoth = keccak256('thoth'); // god of wisdom and magic _divinationRitual(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE, supreme); // supreme as root admin _divinationRitual(anunnaki, anunnaki, supreme); // anunnaki as admin of anunnaki _divinationRitual(thoth, anunnaki, supreme); // anunnaki as admin of thoth mint(supreme, 50_000_000 * 1e18); // mints initial supply of 50M } // solidifies roles (internal) function _divinationRitual(bytes32 _role, bytes32 _adminRole, address _account) internal { _setupRole(_role, _account); _setRoleAdmin(_role, _adminRole); } // grants `role` to `newAccount` && renounces `role` from `oldAccount` (public role) function rethroneRitual(bytes32 role, address oldAccount, address newAccount) public obey(role) { require(oldAccount != newAccount, 'must be a new address'); grantRole(role, newAccount); // grants new account renounceRole(role, oldAccount); // removes old account of role emit Rethroned(role, oldAccount, newAccount); } // updates supreme address (public anunnaki) function newSupreme(address _supreme) public obey(anunnaki) { require(supreme != _supreme, 'make a change, be the change'); // prevents self-destruct rethroneRitual(DEFAULT_ADMIN_ROLE, supreme, _supreme); // empowers new supreme supreme = _supreme; emit NewSupreme(supreme); } // checks whether sender has divine role (public view) function hasDivineRole(bytes32 role) public view returns (bool) { return hasRole(role, msg.sender); } // mints soul power as the house of thoth so wills (public thoth) function mint(address _to, uint _amount) public obey(thoth) { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // destroys `amount` tokens from the caller (public) function burn(uint amount) public { _burn(_msgSender(), amount); _moveDelegates(_delegates[_msgSender()], address(0), amount); } // destroys `amount` tokens from the `account` (public) function burnFrom(address account, uint amount) public { uint currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, 'burn amount exceeds allowance'); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); _moveDelegates(_delegates[account], address(0), amount); } // returns the address delegated by a given delegator (external view) function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } // delegates to the `delegatee` (external) function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } // delegates votes from signatory to `delegatee` (external) function delegateBySig( address delegatee, uint nonce, uint 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), 'delegateBySig: invalid signature'); require(nonce == nonces[signatory]++, 'delegateBySig: invalid nonce'); require(block.timestamp <= expiry, 'delegateBySig: signature expired'); return _delegate(signatory, delegatee); } // returns current votes balance for `account` (external view) function getCurrentVotes(address account) external view returns (uint) { uint nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } // returns an account's prior vote count as of a given timestamp (external view) function getPriorVotes(address account, uint blockTimestamp) external view returns (uint) { require(blockTimestamp < block.timestamp, 'getPriorVotes: not yet determined'); uint nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // checks most recent balance if (checkpoints[account][nCheckpoints - 1].fromTime <= blockTimestamp) { return checkpoints[account][nCheckpoints - 1].votes; } // checks implicit zero balance if (checkpoints[account][0].fromTime > blockTimestamp) { return 0; } uint lower = 0; uint upper = nCheckpoints - 1; while (upper > lower) { uint center = upper - (upper - lower) / 2; // avoids overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromTime == blockTimestamp) { return cp.votes; } else if (cp.fromTime < blockTimestamp) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function safe256(uint n, string memory errorMessage) internal pure returns (uint) { require(n < type(uint).max, errorMessage); return uint(n); } function getChainId() internal view returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint delegatorBalance = balanceOf(delegator); // balance of underlying SOUL (not scaled) _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decreases old representative uint srcRepNum = numCheckpoints[srcRep]; uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint srcRepNew = srcRepOld - amount; _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increases new representative uint dstRepNum = numCheckpoints[dstRep]; uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint dstRepNew = dstRepOld + amount; _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint nCheckpoints, uint oldVotes, uint newVotes ) internal { uint blockTimestamp = safe256(block.timestamp, 'block timestamp exceeds 256 bits'); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromTime == blockTimestamp) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockTimestamp, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } } // File: contracts/libraries/Operable.sol abstract contract Operable is Context, Ownable { address[] public operators; mapping(address => bool) public operator; event OperatorUpdated(address indexed operator, bool indexed access); constructor () { address msgSender = _msgSender(); operator[msgSender] = true; operators.push(msgSender); emit OperatorUpdated(msgSender, true); } modifier onlyOperator() { address msgSender = _msgSender(); require(operator[msgSender], "Operator: caller is not an operator"); _; } function removeOperator(address removingOperator) public virtual onlyOperator { require(operator[removingOperator], 'Operable: address is not an operator'); operator[removingOperator] = false; for (uint8 i; i < operators.length; i++) { if (operators[i] == removingOperator) { operators[i] = operators[i+1]; operators.pop(); emit OperatorUpdated(removingOperator, false); return; } } } function addOperator(address newOperator) public virtual onlyOperator { require(newOperator != address(0), "Operable: new operator is the zero address"); require(!operator[newOperator], 'Operable: address is already an operator'); operator[newOperator] = true; operators.push(newOperator); emit OperatorUpdated(newOperator, true); } } // File: contracts/SeanceCircle.sol // SeanceCircle with Governance. contract SeanceCircle is ERC20('SeanceCircle', 'SEANCE'), Ownable, Operable { SoulPower public soul; bool isInitialized; function mint(address _to, uint256 _amount) public onlyOperator { require(isInitialized, 'the circle has not yet begun'); _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function burn(address _from ,uint256 _amount) public onlyOperator { _burn(_from, _amount); _moveDelegates(_delegates[_from], address(0), _amount); } function initialize(SoulPower _soul) external onlyOwner { require(!isInitialized, 'the circle has already begun'); soul = _soul; isInitialized = true; } // safe soul transfer function, just in case if rounding error causes pool to not have enough SOUL. function safeSoulTransfer(address _to, uint256 _amount) public onlyOperator { uint256 soulBal = soul.balanceOf(address(this)); if (_amount > soulBal) { soul.transfer(_to, soulBal); } else { soul.transfer(_to, _amount); } } // record of each accounts delegate mapping (address => address) internal _delegates; // checkpoint for marking number of votes from a given block timestamp struct Checkpoint { uint256 fromTime; uint256 votes; } // record of votes checkpoints for each account, by index mapping (address => mapping (uint256 => Checkpoint)) public checkpoints; // number of checkpoints for each account mapping (address => uint256) public numCheckpoints; // EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); // EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); // record of states for signing / validating signatures mapping (address => uint) public nonces; // emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); // emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); // returns the address delegated by a given delegator (external view) function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } // delegates to the `delegatee` (external) function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } // delegates votes from signatory to `delegatee` (external) function delegateBySig( address delegatee, uint nonce, uint 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), "SOUL::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "SOUL::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "SOUL::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } // returns current votes balance for `account` (external view) function getCurrentVotes(address account) external view returns (uint) { uint nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } // returns an account's prior vote count as of a given timestamp (external view) function getPriorVotes(address account, uint blockTimestamp) external view returns (uint256) { require(blockTimestamp < block.timestamp, "SOUL::getPriorVotes: not yet determined"); uint256 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // checks most recent balance if (checkpoints[account][nCheckpoints - 1].fromTime <= blockTimestamp) { return checkpoints[account][nCheckpoints - 1].votes; } // checks implicit zero balance if (checkpoints[account][0].fromTime > blockTimestamp) { return 0; } uint256 lower = 0; uint256 upper = nCheckpoints - 1; while (upper > lower) { uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromTime == blockTimestamp) { return cp.votes; } else if (cp.fromTime < blockTimestamp) { 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 SOUL (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 uint256 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld - amount; _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint256 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld + amount; _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint256 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint256 blockTimestamp = safe256(block.timestamp, "SOUL::_writeCheckpoint: block timestamp exceeds 256 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromTime == blockTimestamp) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockTimestamp, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe256(uint n, string memory errorMessage) internal pure returns (uint256) { require(n < type(uint256).max, errorMessage); return uint256(n); } function getChainId() internal view returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } function newSoul(SoulPower _soul) external onlyOperator { require(soul != _soul, 'must be a new address'); soul = _soul; } } // File: contracts/interfaces/IMigrator.sol interface IMigrator { function migrate(IERC20 token) external returns (IERC20); } // File: contracts/SoulSummoner.sol // the summoner of souls | ownership transferred to a governance smart contract // upon sufficient distribution + the community's desire to self-govern. contract SoulSummoner is AccessControl, Pausable, ReentrancyGuard { // user info struct Users { uint amount; // total tokens user has provided. uint rewardDebt; // reward debt (see below). uint rewardDebtAtTime; // the last time user stake. uint lastWithdrawTime; // the last time a user withdrew at. uint firstDepositTime; // the last time a user deposited at. uint timeDelta; // time passed since withdrawals. uint lastDepositTime; // most recent deposit time. // pending reward = (user.amount * pool.accSoulPerShare) - user.rewardDebt // the following occurs when a user +/- tokens to a pool: // 1. pool: `accSoulPerShare` and `lastRewardTime` update. // 2. user: receives pending reward. // 3. user: `amount` updates(+/-). // 4. user: `rewardDebt` updates (+/-). } // pool info struct Pools { IERC20 lpToken; // lp token ierc20 contract. uint allocPoint; // allocation points assigned to this pool | SOULs to distribute per second. uint lastRewardTime; // most recent UNIX timestamp during which SOULs distribution occurred in the pool. uint accSoulPerShare; // accumulated SOULs per share, times 1e12. } // soul power: our native utility token address private soulAddress; SoulPower public soul; // seance circle: our governance token address private seanceAddress; SeanceCircle public seance; address public team; // receives 1/8 soul supply address public dao; // recieves 1/8 soul supply address public supreme; // has supreme role // migrator contract | has lotsa power IMigrator public migrator; // blockchain variables accounting for share of overall emissions uint public totalWeight; uint public weight; // soul x day x this.chain uint public dailySoul; // = weight * 250K * 1e18; // soul x second x this.chain uint public soulPerSecond; // = dailySoul / 86400; // bonus muliplier for early soul summoners uint public bonusMultiplier = 1; // timestamp when soul rewards began (initialized) uint public startTime; // ttl allocation points | must be the sum of all allocation points uint public totalAllocPoint; // summoner initialized state. bool public isInitialized; // decay rate on withdrawal fee of 1%. uint public immutable dailyDecay = enWei(1); // start rate for the withdrawal fee. uint public startRate; Pools[] public poolInfo; // pool info mapping (uint => mapping (address => Users)) public userInfo; // staker data // divinated roles bytes32 public isis; // soul summoning goddess of magic bytes32 public maat; // goddess of cosmic order event RoleDivinated(bytes32 role, bytes32 supreme); // restricted to the council of the role passed as an object to obey (role) modifier obey(bytes32 role) { _checkRole(role, _msgSender()); _; } // prevents: early reward distribution modifier isSummoned { require(isInitialized, 'rewards have not yet begun'); _; } event Deposit(address indexed user, uint indexed pid, uint amount); event Withdraw(address indexed user, uint indexed pid, uint amount, uint timeStamp); event Initialized(address team, address dao, address soul, address seance, uint totalAllocPoint, uint weight); event PoolAdded(uint pid, uint allocPoint, IERC20 lpToken, uint totalAllocPoint); event PoolSet(uint pid, uint allocPoint); event WeightUpdated(uint weight, uint totalWeight); event RewardsUpdated(uint dailySoul, uint soulPerSecond); event StartRateUpdated(uint startRate); event AccountsUpdated(address dao, address team, address admin); event TokensUpdated(address soul, address seance); event DepositRevised(uint _pid, address _user, uint _time); // validates: pool exists modifier validatePoolByPid(uint pid) { require(pid < poolInfo.length, 'pool does not exist'); _; } // channels the power of the isis and ma'at to the deployer (deployer) constructor() { supreme = msg.sender; // 0x81Dd37687c74Df8F957a370A9A4435D873F5e5A9; // multi-sig safe team = msg.sender; // 0x36d0164e87B58427c4153c089aeDDa8Ec0B80B9D; // team wallet dao = msg.sender; // 0x1C63C726926197BD3CB75d86bCFB1DaeBcD87250; // dao treasury (multi-sig) isis = keccak256("isis"); // goddess of magic who creates pools maat = keccak256("maat"); // goddess of cosmic order who allocates emissions _divinationCeremony(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE, supreme); _divinationCeremony(isis, isis, supreme); // isis role created -- supreme divined admin _divinationCeremony(maat, isis, dao); // maat role created -- isis divined admin } function _divinationCeremony(bytes32 _role, bytes32 _adminRole, address _account) internal returns (bool) { _setupRole(_role, _account); _setRoleAdmin(_role, _adminRole); return true; } // validate: pool uniqueness to eliminate duplication risk (internal view) function checkPoolDuplicate(IERC20 _token) internal view { uint length = poolInfo.length; for (uint pid = 0; pid < length; ++pid) { require(poolInfo[pid].lpToken != _token, 'duplicated pool'); } } // activates: rewards (owner) function initialize() external obey(isis) { require(!isInitialized, 'already initialized'); soulAddress = 0xCF174A6793FA36A73e8fF18A71bd81C985ef5aB5; seanceAddress = 0xD54Cf31D5653F4a062f5DA4C83170A5867d04442; // [required]: update global constants startTime = block.timestamp; totalWeight = 1000; weight = 1000; startRate = enWei(14); uint allocPoint = 1000; soul = SoulPower(soulAddress); seance = SeanceCircle(seanceAddress); // updates: dailySoul and soulPerSecond updateRewards(weight, totalWeight); // adds: staking pool poolInfo.push(Pools({ lpToken: soul, allocPoint: allocPoint, lastRewardTime: startTime, accSoulPerShare: 0 })); isInitialized = true; // triggers: initialize state totalAllocPoint += allocPoint; // kickstarts: total allocation emit Initialized(team, dao, soulAddress, seanceAddress, totalAllocPoint, weight); } // returns: amount of pools function poolLength() external view returns (uint) { return poolInfo.length; } // add: new pool (isis) function addPool(uint _allocPoint, IERC20 _lpToken, bool _withUpdate) public isSummoned obey(isis) { // isis: the soul summoning goddess whose power transcends them all checkPoolDuplicate(_lpToken); _addPool(_allocPoint, _lpToken, _withUpdate); } // add: new pool (internal) function _addPool(uint _allocPoint, IERC20 _lpToken, bool _withUpdate) internal { if (_withUpdate) { massUpdatePools(); } totalAllocPoint += _allocPoint; poolInfo.push( Pools({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardTime: block.timestamp > startTime ? block.timestamp : startTime, accSoulPerShare: 0 })); updateStakingPool(); uint pid = poolInfo.length; emit PoolAdded(pid, _allocPoint, _lpToken, totalAllocPoint); } // set: allocation points (maat) function set(uint pid, uint allocPoint, bool withUpdate) external isSummoned validatePoolByPid(pid) obey(maat) { if (withUpdate) { massUpdatePools(); } // updates all pools uint prevAllocPoint = poolInfo[pid].allocPoint; poolInfo[pid].allocPoint = allocPoint; if (prevAllocPoint != allocPoint) { totalAllocPoint = totalAllocPoint - prevAllocPoint + allocPoint; updateStakingPool(); // updates only selected pool } emit PoolSet(pid, allocPoint); } // set: migrator contract (isis) function setMigrator(IMigrator _migrator) external isSummoned obey(isis) { migrator = _migrator; } // view: user delta function userDelta(uint256 _pid, address _user) public view returns (uint256 delta) { Users memory user = userInfo[_pid][_user]; return user.lastWithdrawTime > 0 ? block.timestamp - user.lastWithdrawTime : block.timestamp - user.firstDepositTime; } // migrate: lp tokens to another contract (migrator) function migrate(uint pid) external isSummoned validatePoolByPid(pid) { require(address(migrator) != address(0), 'no migrator set'); Pools storage pool = poolInfo[pid]; IERC20 lpToken = pool.lpToken; uint bal = lpToken.balanceOf(address(this)); lpToken.approve(address(migrator), bal); IERC20 _lpToken = migrator.migrate(lpToken); require(bal == _lpToken.balanceOf(address(this)), "migrate: insufficient balance"); pool.lpToken = _lpToken; } // view: bonus multiplier (public view) function getMultiplier(uint from, uint to) public view returns (uint) { return (to - from) * bonusMultiplier; // todo: minus parens } // returns: decay rate for a pid (public view) function getFeeRate(uint pid, uint timeDelta) public view returns (uint feeRate) { uint daysPassed = timeDelta < 1 days ? 0 : timeDelta / 1 days; uint rateDecayed = enWei(daysPassed); uint _rate = rateDecayed >= startRate ? 0 : startRate - rateDecayed; // returns 0 for SAS return pid == 0 ? 0 : _rate; } // returns: feeAmount and with withdrawableAmount for a given pid and amount function getWithdrawable(uint pid, uint timeDelta, uint amount) public view returns (uint _feeAmount, uint _withdrawable) { uint feeRate = fromWei(getFeeRate(pid, timeDelta)); uint feeAmount = (amount * feeRate) / 100; uint withdrawable = amount - feeAmount; return (feeAmount, withdrawable); } // view: pending soul rewards (external) function pendingSoul(uint pid, address _user) external view returns (uint pendingAmount) { Pools storage pool = poolInfo[pid]; Users storage user = userInfo[pid][_user]; uint accSoulPerShare = pool.accSoulPerShare; uint lpSupply = pool.lpToken.balanceOf(address(this)); if (block.timestamp > pool.lastRewardTime && lpSupply != 0) { uint multiplier = getMultiplier(pool.lastRewardTime, block.timestamp); uint soulReward = multiplier * soulPerSecond * pool.allocPoint / totalAllocPoint; accSoulPerShare = accSoulPerShare + soulReward * 1e12 / lpSupply; } return user.amount * accSoulPerShare / 1e12 - user.rewardDebt; } // update: rewards for all pools (public) function massUpdatePools() public { uint length = poolInfo.length; for (uint pid = 0; pid < length; ++pid) { updatePool(pid); } } // update: rewards for a given pool id (public) function updatePool(uint pid) public validatePoolByPid(pid) { Pools storage pool = poolInfo[pid]; if (block.timestamp <= pool.lastRewardTime) { return; } uint lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardTime = block.timestamp; return; } // first staker in pool uint multiplier = getMultiplier(pool.lastRewardTime, block.timestamp); uint soulReward = multiplier * soulPerSecond * pool.allocPoint / totalAllocPoint; uint divi = soulReward * 1e12 / 8e12; // 12.5% rewards uint divis = divi * 2; // total divis uint shares = soulReward - divis; // net shares soul.mint(team, divi); soul.mint(dao, divi); soul.mint(address(seance), shares); pool.accSoulPerShare = pool.accSoulPerShare + (soulReward * 1e12 / lpSupply); pool.lastRewardTime = block.timestamp; } // deposit: lp tokens (lp owner) function deposit(uint pid, uint amount) external nonReentrant validatePoolByPid(pid) whenNotPaused { require (pid != 0, 'deposit SOUL by staking'); Pools storage pool = poolInfo[pid]; Users storage user = userInfo[pid][msg.sender]; updatePool(pid); if (user.amount > 0) { // already deposited assets uint pending = (user.amount * pool.accSoulPerShare) / 1e12 - user.rewardDebt; if(pending > 0) { // sends pending rewards, if applicable safeSoulTransfer(msg.sender, pending); } } if (amount > 0) { // if adding more pool.lpToken.transferFrom(address(msg.sender), address(this), amount); user.amount += amount; } user.rewardDebt = user.amount * pool.accSoulPerShare / 1e12; // marks timestamp for first deposit user.firstDepositTime = user.firstDepositTime > 0 ? user.firstDepositTime : block.timestamp; emit Deposit(msg.sender, pid, amount); } // withdraw: lp tokens (external farmers) function withdraw(uint pid, uint amount) external nonReentrant validatePoolByPid(pid) { require (pid != 0, 'withdraw SOUL by unstaking'); Pools storage pool = poolInfo[pid]; Users storage user = userInfo[pid][msg.sender]; require(user.amount >= amount, 'withdraw not good'); updatePool(pid); uint pending = user.amount * pool.accSoulPerShare / 1e12 - user.rewardDebt; if(pending > 0) { safeSoulTransfer(msg.sender, pending); } if(amount > 0) { if(user.lastDepositTime > 0){ user.timeDelta = block.timestamp - user.lastDepositTime; } else { user.timeDelta = block.timestamp - user.firstDepositTime; } user.amount = user.amount - amount; } uint timeDelta = userInfo[pid][msg.sender].timeDelta; (, uint withdrawable) = getWithdrawable(pid, timeDelta, amount); // removes feeAmount from amount uint feeAmount = amount - withdrawable; pool.lpToken.transfer(address(dao), feeAmount); pool.lpToken.transfer(address(msg.sender), withdrawable); user.rewardDebt = user.amount * pool.accSoulPerShare / 1e12; user.lastWithdrawTime = block.timestamp; emit Withdraw(msg.sender, pid, amount, block.timestamp); } // stake: soul into summoner (external) function enterStaking(uint amount) external nonReentrant whenNotPaused { Pools storage pool = poolInfo[0]; Users storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint pending = user.amount * pool.accSoulPerShare / 1e12 - user.rewardDebt; if(pending > 0) { safeSoulTransfer(msg.sender, pending); } } if(amount > 0) { pool.lpToken.transferFrom(address(msg.sender), address(this), amount); user.amount = user.amount + amount; } // marks timestamp for first deposit user.firstDepositTime = user.firstDepositTime > 0 ? user.firstDepositTime : block.timestamp; user.rewardDebt = user.amount * pool.accSoulPerShare / 1e12; seance.mint(msg.sender, amount); emit Deposit(msg.sender, 0, amount); } // unstake: your soul (external staker) function leaveStaking(uint amount) external nonReentrant { Pools storage pool = poolInfo[0]; Users storage user = userInfo[0][msg.sender]; require(user.amount >= amount, "withdraw: not good"); updatePool(0); uint pending = user.amount * pool.accSoulPerShare / 1e12 - user.rewardDebt; if(pending > 0) { safeSoulTransfer(msg.sender, pending); } if(amount > 0) { user.amount = user.amount - amount; pool.lpToken.transfer(address(msg.sender), amount); } user.rewardDebt = user.amount * pool.accSoulPerShare / 1e12; user.lastWithdrawTime = block.timestamp; seance.burn(msg.sender, amount); emit Withdraw(msg.sender, 0, amount, block.timestamp); } // transfer: seance (internal) function safeSoulTransfer(address account, uint amount) internal { seance.safeSoulTransfer(account, amount); } // ** UPDATE FUNCTIONS ** // // update: weight (maat) function updateWeights(uint _weight, uint _totalWeight) external obey(maat) { require(weight != _weight || totalWeight != _totalWeight, 'must be at least one new value'); require(_totalWeight >= _weight, 'weight cannot exceed totalWeight'); weight = _weight; totalWeight = _totalWeight; updateRewards(weight, totalWeight); emit WeightUpdated(weight, totalWeight); } // update: staking pool (internal) function updateStakingPool() internal { uint length = poolInfo.length; uint points; for (uint pid = 1; pid < length; ++pid) { points = points + poolInfo[pid].allocPoint; } if (points != 0) { points = points / 3; totalAllocPoint = totalAllocPoint - poolInfo[0].allocPoint + points; poolInfo[0].allocPoint = points; } } // update: multiplier (maat) function updateMultiplier(uint _bonusMultiplier) external obey(maat) { bonusMultiplier = _bonusMultiplier; } // update: rewards (internal) function updateRewards(uint _weight, uint _totalWeight) internal { uint share = enWei(_weight) / _totalWeight; // share of ttl emissions for chain (chain % ttl emissions) dailySoul = share * (250_000); // dailySoul (for this.chain) = share (%) x 250K (soul emissions constant) soulPerSecond = dailySoul / 1 days; // updates: daily rewards expressed in seconds (1 days = 86,400 secs) emit RewardsUpdated(dailySoul, soulPerSecond); } // update: startRate (maat) function updateStartRate(uint _startRate) public obey(maat) { require(startRate != enWei(_startRate)); startRate = enWei(_startRate); emit StartRateUpdated(startRate); } // update accounts: dao, team, and supreme addresses (isis) function updateAccounts(address _dao, address _team, address _supreme) external obey(isis) { require(dao != _dao || team != _team || supreme != _supreme, 'must be a new account'); dao = _dao; team = _team; supreme = _supreme; emit AccountsUpdated(dao, team, supreme); } // update tokens: soul and seance addresses (isis) function updateTokens(address _soul, address _seance) external obey(isis) { require(soul != IERC20(_soul) || seance != IERC20(_seance), 'must be a new token address'); soul = SoulPower(_soul); seance = SeanceCircle(_seance); emit TokensUpdated(_soul, _seance); } // manual override to reassign the first deposit time for a given (pid, account) function reviseDeposit(uint _pid, address _user, uint256 _time) public obey(maat) { Users storage user = userInfo[_pid][_user]; user.firstDepositTime = _time; emit DepositRevised(_pid, _user, _time); } // ** HELPER FUNCTIONS ** // // helper functions to convert to wei and 1/100th function enWei(uint amount) public pure returns (uint) { return amount * 1e18; } function fromWei(uint amount) public pure returns (uint) { return amount / 1e18; } }
checks whether sender has divine role (public view)
function hasDivineRole(bytes32 role) public view returns (bool) { return hasRole(role, msg.sender); }
957,010
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; /** @notice This contract is extremely simple. It adds an IPFS Multihash (by it's 3 distinct parts) to a contract. * @dev It's dependent on a js file (see ../util/multihash.js or you can use an equiv.) taking the full IPFS hash * string and parsing it into it's respective parts: * bytes32 digest * uint8 hashFunction * uint8 size * Parsing in this way allows the hash to be stored onchain in an efficient manner. Note that this contract could * easily be used for saving any IPFS hash address to a contract that a dApp needs. Here, we're using it for storing * an Agreement file (a signed pdf, for instance) that all parties to an Intellectual Property NFT + an Intellectual * Property RightsHolder ERC20 Token combination have agreed upon. It allows a simple index to be referenced in * other contracts. */ contract IntelPropertyAgreement is Ownable { struct Multihash { bytes32 digest; uint8 hashFunction; uint8 size; } mapping (uint => Multihash) agreements; uint totalAgreements; event ipfsHashSetToNFT (uint indexed agreementID, bytes32 digest, uint8 hashFunction, uint8 size); /** @notice adds a parsed IPFS hash file to the contract */ function addAgreement(bytes32 _digest, uint8 _hashFunction, uint8 _size) external onlyOwner { (Multihash storage entry) = (agreements[totalAgreements]); entry.digest = _digest; entry.hashFunction = _hashFunction; entry.size = _size; emit ipfsHashSetToNFT(totalAgreements, _digest, _hashFunction, _size); totalAgreements++; // increment to reset index for the next incoming agreement } /** @notice returns an IPFS hash by it's ID number. Note that the Multihash will need to be re-combined, * (see ../util/multihash.js). */ function retrieveAgreement(uint _agreementID) public view returns(Multihash memory _agreement) { (Multihash storage agreement) = (agreements[_agreementID]); return agreement; } /** @notice returns the total number of agreements present in the contract */ function getTotalAgreements() public view returns(uint _totalAgreements) { return totalAgreements; } }
adds a parsed IPFS hash file to the contract /
function addAgreement(bytes32 _digest, uint8 _hashFunction, uint8 _size) external onlyOwner { (Multihash storage entry) = (agreements[totalAgreements]); entry.digest = _digest; entry.hashFunction = _hashFunction; entry.size = _size; emit ipfsHashSetToNFT(totalAgreements, _digest, _hashFunction, _size); }
7,312,833
pragma solidity ^0.4.4; import 'common/Mortal.sol'; contract Comission is Mortal { address public ledger; bytes32 public taxman; uint public taxPerc; /** * @dev Comission contract constructor * @param _ledger Processing ledger contract * @param _taxman Tax receiver account * @param _taxPerc Processing tax in percent */ function Comission(address _ledger, bytes32 _taxman, uint _taxPerc) { ledger = _ledger; taxman = _taxman; taxPerc = _taxPerc; } /** * @dev Refill ledger with comission * @param _destination Destination account */ function process(bytes32 _destination) payable returns (bool) { // Handle value below 100 isn't possible if (msg.value < 100) throw; var tax = msg.value * taxPerc / 100; var refill = bytes4(sha3("refill(bytes32)")); if ( !ledger.call.value(tax)(refill, taxman) || !ledger.call.value(msg.value - tax)(refill, _destination) ) throw; return true; } }
Comission contract constructor _ledger Processing ledger contract _taxman Tax receiver account _taxPerc Processing tax in percent/
function Comission(address _ledger, bytes32 _taxman, uint _taxPerc) { ledger = _ledger; taxman = _taxman; taxPerc = _taxPerc; }
1,806,657
pragma solidity >0.4.25; import 'openzeppelin-solidity/contracts/ownership/Ownable.sol'; import '../diamondaccesscontrol/MinerRole.sol'; import '../diamondaccesscontrol/ManufacturerRole.sol'; import '../diamondaccesscontrol/MasterjewelerRole.sol'; import '../diamondaccesscontrol/RetailerRole.sol'; import '../diamondaccesscontrol/CustomerRole.sol'; /** * @title Supply chain main contract * @author Stefanel Stan https://github.com/StefanelStan */ contract SupplyChain is Ownable, MinerRole, ManufacturerRole, MasterjewelerRole, RetailerRole, CustomerRole { /** * @dev As this is a supply chain for diamond jewelry, there is a subtle difference on the * state and processes of the item. When the raw diamond is mined, this is an item whose * itemPrice is to be determined by Miner. A manufacturer can BUY the item * After the item gets cut by a master jeweler, the item is seen as a product, which has a * productPrice determined by manufacturer. * A customer can then purchase the product after paying the productPrice. */ struct Item { uint sku; // Stock Keeping Unit (SKU) uint upc; // Universal Product Code (UPC), generated by the Miner, goes on the package, can be verified by the Customer uint productID; // Product ID potentially a combination of upc + sku uint itemPrice; //item price uint productPrice; // product Price string minerName; // Miner Name string mineInformation; // Mine Information string mineLatitude; // Mine Latitude string mineLongitude; // Mine Longitude string itemNotes; // Item Notes string ipfsHash; // ipfs hash of the picture of the item State itemState; // Item State as represented in the enum above address owner; // Metamask-Ethereum address of the current owner as the product moves through stages address miner; // Metamask-Ethereum address of the Farmer address manufacturer; // Metamask-Ethereum address of the Manufacturer address masterjeweler; // Metamask-Ethereum address of the Masterjeweler address retailer; // Metamask-Ethereum address of the Retailer address customer; // Metamask-Ethereum address of the Customer } /** @dev Please see the notes from struct Item that clarifies the difference between * ForSale/Sold and ForPurchasing/Purchased */ enum State { Mined, // 0 ForSale, // 1 Sold, // 2 Sent, // 3 Received, // 4 SentToCut, // 5 ReceivedForCutting, // 6 Cut, // 7 SentFromCutting, // 8 ReceivedFromCutting, // 9 MarkedForPurchasing, // 10 SentForPurchasing, // 11 ReceivedForPurchasing, // 12 ForPurchasing, // 13 Purchased, // 14 Fetched // 15 } // for Stock Keeping Unit (SKU) uint _sku; // maps the UPC to an Item. mapping (uint => Item) private items; // maps the UPC/item to an array of TxHash & tracks its journey through the supply chain -- to be sent from DApp. mapping (uint => string[]) private itemsHistory; // Define 16 events with the same 16 state values and accept 'upc' as input argument event Mined(uint upc); event ForSale(uint upc); event Sold(uint upc); event Sent(uint upc); event Received(uint upc); event SentToCut(uint upc); event ReceivedForCutting(uint upc); event Cut(uint upc); event SentFromCutting(uint upc); event ReceivedFromCutting(uint upc); event MarkedForPurchasing(uint upc); event SentForPurchasing(uint upc); event ReceivedForPurchasing(uint upc); event ForPurchasing(uint upc); event Purchased(uint upc); event Fetched(uint upc); // Define a modifer that verifies the Caller modifier verifyCaller(address _address) { require(msg.sender == _address, "Only the authorized user/address can perform this"); _; } // Define a modifier that checks if the paid amount is sufficient to cover the price modifier paidEnough(uint _price) { require(msg.value >= _price, "Not enough payment sent"); _; } // Define a modifier that checks the price and refunds the remaining balance modifier checkValueForSelling(uint _upc) { _; uint _price = items[_upc].itemPrice; uint amountToReturn = msg.value - _price; address payable manufacturerAddres = address(uint160(items[_upc].manufacturer)); manufacturerAddres.transfer(amountToReturn); } // Define a modifier that checks the price and refunds the remaining balance modifier checkValueForPurchasing(uint _upc) { _; uint _price = items[_upc].productPrice; uint amountToReturn = msg.value - _price; address payable customerAddress = address(uint160(items[_upc].customer)); customerAddress.transfer(amountToReturn); } // Define a modifier that checks if an item.state of a upc is Mined modifier mined(uint _upc) { //If the doesn't exist, its State.mined == 0. So there is need for a stronger verification eg: has an owner require(items[_upc].itemState == State.Mined && items[_upc].owner != address(0), "Item state is not Mined"); _; } // Define a modifier that checks if an item.state of a upc is ForSale modifier forSale(uint _upc) { require(items[_upc].itemState == State.ForSale, "Item state is not ForSale"); _; } // Define a modifier that checks if an item.state of a upc is Sold modifier sold(uint _upc) { require(items[_upc].itemState == State.Sold, "Item state is not Sold"); _; } // Define a modifier that checks if an item.state of a upc is Sent modifier sent(uint _upc) { require(items[_upc].itemState == State.Sent, "Item state is not Sent"); _; } // Define a modifier that checks if an item.state of a upc is Received modifier received(uint _upc) { require(items[_upc].itemState == State.Received, "Item state is not Received"); _; } // Define a modifier that checks if an item.state of a upc is SentToCut modifier sentToCut(uint _upc) { require(items[_upc].itemState == State.SentToCut, "Item state is not SentToCut"); _; } // Define a modifier that checks if an item.state of a upc is ReceivedForCutting modifier receivedForCutting(uint _upc) { require(items[_upc].itemState == State.ReceivedForCutting, "Item state is not ReceivedForCutting"); _; } // Define a modifier that checks if an item.state of a upc is Cut modifier cut(uint _upc) { require(items[_upc].itemState == State.Cut, "Item state is not Cut"); _; } // Define a modifier that checks if an item.state of a upc is SentFromCutting modifier sentFromCutting(uint _upc) { require(items[_upc].itemState == State.SentFromCutting, "Item state is not SentFromCutting"); _; } // Define a modifier that checks if an item.state of a upc is ReceivedFromCutting modifier receivedFromCutting(uint _upc) { require(items[_upc].itemState == State.ReceivedFromCutting, "Item state is not ReceivedFromCutting"); _; } // Define a modifier that checks if an item.state of a upc is MarkedForPurchasing modifier markedForPurchasing(uint _upc) { require(items[_upc].itemState == State.MarkedForPurchasing, "Item state is not MarkedForPurchasing"); _; } // Define a modifier that checks if an item.state of a upc is SentForPurchasing modifier sentForPurchasing(uint _upc) { require(items[_upc].itemState == State.SentForPurchasing, "Item state is not SentForPurchasing"); _; } // Define a modifier that checks if an item.state of a upc is ReceivedForPurchasing modifier receivedForPurchasing(uint _upc) { require(items[_upc].itemState == State.ReceivedForPurchasing, "Item state is not ReceivedForPurchasing"); _; } // Define a modifier that checks if an item.state of a upc is ForPurchasing modifier forPurchasing(uint _upc) { require(items[_upc].itemState == State.ForPurchasing, "Item state is not ForPurchasing"); _; } // Define a modifier that checks if an item.state of a upc is Purchased modifier purchased(uint _upc) { require(items[_upc].itemState == State.Purchased, "Item state is not Purchased"); _; } // Define a modifier that checks if an item.state of a upc is Fetched modifier fetched(uint _upc) { require(items[_upc].itemState == State.Fetched, "Item state is not Fetched"); _; } constructor() public payable { _sku = 0; } // Define a function 'kill' if required function kill() external onlyOwner { require(isOwner(), "Only owner can kill this contract"); selfdestruct(address(uint160(owner()))); } /** * @dev Mines an item. * @param _upc the identifier of the item; Generated by the miner. Reverts if not unique * @param _minerName miner's name * @param _mineInformation mine's information * @param _mineLatitude mine's LAtitude * @param _mineLongitude mine's Lontitude * @param _itemNotes notes about the item */ function mineItem( uint _upc, string memory _minerName, string memory _mineInformation, string memory _mineLatitude, string memory _mineLongitude, string memory _itemNotes ) public onlyMiner { require(items[_upc].owner == address(0), 'Item already exists'); items[_upc] = Item(_sku, _upc, _upc + _sku, 0, 0, _minerName, _mineInformation, _mineLatitude, _mineLongitude, _itemNotes, "No Image Hash exists", State.Mined, msg.sender, msg.sender, address(0), address(0), address(0), address(0)); _sku++; emit Mined(_upc); } /** * @dev Marks an item as For Sale * @param _upc the upc of the item * @param _price the price demanded for the item */ function sellItem(uint _upc, uint _price) public onlyMiner mined(_upc) verifyCaller(items[_upc].owner) { Item storage item = items[_upc]; item.itemPrice = _price; item.itemState = State.ForSale; emit ForSale(_upc); } /** * @dev Buys an item. Caller should be a manufacturer * @param _upc the desired _upc item to buy */ function buyItem(uint _upc) public payable onlyManufacturer forSale(_upc) paidEnough(items[_upc].itemPrice) checkValueForSelling(_upc) { Item storage item = items[_upc]; address(uint160(item.miner)).transfer(item.itemPrice); item.owner = msg.sender; item.manufacturer = msg.sender; item.itemState = State.Sold; emit Sold(_upc); } /** * @dev The Miner marks/sends a bought item to the buyer (manufacturer) * @param _upc the item's id to be send to the manufacturer/buyer */ function sendItem(uint _upc) public sold(_upc) verifyCaller(items[_upc].miner) { items[_upc].itemState = State.Sent; emit Sent(_upc); } /** * @dev The rightful buyer (manufacturer) receives the item and marks it as received * @param _upc the item to mark as received */ function receiveItem(uint _upc) public sent(_upc) verifyCaller(items[_upc].manufacturer) { items[_upc].itemState = State.Received; emit Received(_upc); } /** * @dev Send the item to cut * @param _upc the item's id * @param masterjeweler the Masterjeweler's address. The given address has to have Masterjeweler Role */ function sendItemToCut(uint _upc, address masterjeweler) public received(_upc) verifyCaller(items[_upc].manufacturer) { require(isMasterjeweler(masterjeweler), "The given address is not a Masterjeweler Role"); items[_upc].itemState = State.SentToCut; items[_upc].masterjeweler = masterjeweler; emit SentToCut(_upc); } /** * @dev Masterjeweler receives the item to cut * @param _upc the item's id that has been received */ function receiveItemToCut(uint _upc) public sentToCut(_upc) verifyCaller(items[_upc].masterjeweler) onlyMasterjeweler { items[_upc].itemState = State.ReceivedForCutting; emit ReceivedForCutting(_upc); } /** * @dev Masterjeweler cuts the item * @param _upc the item's upc to cut */ function cutItem(uint _upc) public receivedForCutting(_upc) verifyCaller(items[_upc].masterjeweler) onlyMasterjeweler { items[_upc].itemState = State.Cut; emit Cut(_upc); } /** * @dev Masterjeweler returns the cut item * @param _upc the item to return */ function returnCutItem(uint _upc) public cut(_upc) verifyCaller(items[_upc].masterjeweler) { items[_upc].itemState = State.SentFromCutting; emit SentFromCutting(_upc); } /** * @dev Receive the cut item back from the masterjeweler * @param _upc the item's upc */ function receiveCutItem(uint _upc) public sentFromCutting(_upc) verifyCaller(items[_upc].manufacturer) { items[_upc].itemState = State.ReceivedFromCutting; emit ReceivedFromCutting(_upc); } /** * @dev Manufacturer marks the item for Purchasing for the given price * @param _upc the item's upc to mark for purchasing * @param _price the price for the disired product. * @notice The item is to treated as product now. */ function markForPurchasing(uint _upc, uint _price) public receivedFromCutting(_upc) verifyCaller(items[_upc].manufacturer) { items[_upc].itemState = State.MarkedForPurchasing; items[_upc].productPrice = _price; emit MarkedForPurchasing(_upc); } /** * @dev Send the marked item to the retailer to be displayed and purchased * @param _upc the item's upc * @param retailer The address of the retailer. Reverts if the given address is NOT a RetailerRole */ function sendItemForPurchasing(uint _upc, address retailer) public markedForPurchasing(_upc) verifyCaller(items[_upc].manufacturer) { require(isRetailer(retailer), "The given address is not a Retailer Role"); items[_upc].itemState = State.SentForPurchasing; items[_upc].retailer = retailer; emit SentForPurchasing(_upc); } /** * @dev Allows the retailer to receive the item (product) * @param _upc the item to receive */ function receiveItemForPurchasing(uint _upc) public sentForPurchasing(_upc) verifyCaller(items[_upc].retailer) { items[_upc].itemState = State.ReceivedForPurchasing; emit ReceivedForPurchasing(_upc); } function putUpForPurchasing(uint _upc) public receivedForPurchasing(_upc) verifyCaller(items[_upc].retailer) onlyRetailer { items[_upc].itemState = State.ForPurchasing; emit ForPurchasing(_upc); } /** * @dev Allows a customer to purchase the final product * @param _upc the item's upc that is being purchased */ function purchaseItem(uint _upc) public payable forPurchasing(_upc) paidEnough(items[_upc].productPrice) onlyCustomer checkValueForPurchasing(_upc) { Item storage item = items[_upc]; address(uint160(item.retailer)).transfer(item.productPrice); item.owner = msg.sender; item.customer = msg.sender; item.itemState = State.Purchased; emit Purchased(_upc); } /** * @dev Allows the rightful customer to take the product out of the shop * @param _upc the item's upc to fetch/get out of shop */ function fetchItem(uint _upc) public purchased(_upc) verifyCaller(items[_upc].customer) { items[_upc].itemState = State.Fetched; emit Fetched(_upc); } /** * @dev Allows the original miner to upload a image Hash of the item freshly mined. * @param _upc the item's upc to which the image hash belongs * @param _ipfsHash the image's ipfs hash */ function uploadHash(uint _upc, string calldata _ipfsHash) external verifyCaller(items[_upc].miner) { items[_upc].ipfsHash = _ipfsHash; } /** * @dev Read the ipfs image hash of the given upc item * @param _upc the item's upc * @return the image hash */ function readHash(uint _upc) external view returns (string memory){ return items[_upc].ipfsHash; } /** * @dev Method created specially for the purpose easy testing for Udacity Reviewers * This way, any reviewer can promote his/her selected account to be all 5 roles * This method is critical as accounts have to have the X/Y/Z Role to perform specific actions */ function giveMeAllRoles() external { _addMiner(msg.sender); _addManufacturer(msg.sender); _addMasterjeweler(msg.sender); _addRetailer(msg.sender); _addCustomer(msg.sender); } /** * @dev fetch data/info about the given item * @param _upc the item's upc */ function fetchItemBufferOne(uint _upc) public view returns ( uint sku, uint upc, address owner, address miner, string memory minerName, string memory mineInformation, string memory mineLatitude, string memory mineLongitude ) { Item memory item = items[_upc]; return ( item.sku, item.upc, item.owner, item.miner, item.minerName, item.mineInformation, item.mineLatitude, item.mineLongitude ); } /** * @dev fetch data/info about the given item * @param _upc the item's upc */ function fetchItemBufferTwo(uint _upc) public view returns ( uint sku, uint upc, uint productID, string memory itemNotes, uint itemPrice, uint productPrice, State itemState, address manufacturer, address masterjeweler, address retailer, address customer ) { Item memory item = items[_upc]; return ( item.sku, item.upc, item.productID, item.itemNotes, item.itemPrice, item.productPrice, item.itemState, item.manufacturer, item.masterjeweler, item.retailer, item.customer ); } }
Read the ipfs image hash of the given upc item _upc the item's upc return the image hash/
function readHash(uint _upc) external view returns (string memory){ return items[_upc].ipfsHash; }
7,235,454
/// https://etherscan.io/address/0x06012c8cf97bead5deae237070f9587f8e7a266d#code /// Submitted for verification at Etherscan.io on 2017-11-28 pragma solidity ^0.4.11; /// 所有者合约拥有一个所有者,提供基本的授权控制函数,简化的用户权限的实现 contract Ownable { address public owner; // 所有者地址 /// 构造函数设置所有者 function Ownable() { owner = msg.sender; } /// 修改器前置验证所有权 modifier onlyOwner() { require(msg.sender == owner); _; } /// 转移所有权函数,要求当前所有者调用 /// 传入新的所有者地址 非 0 地址 function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /// ERC721 NFT 代币接口 Non-Fungible Tokens contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom( address _from, address _to, uint256 _tokenId ) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); /// ERC165 提供函数检查是否实现了某函数 // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } // // Auction wrapper functions // Auction wrapper functions /// what? 基因科学接口 contract GeneScienceInterface { /// 是否实现了基因科学? function isGeneScience() public pure returns (bool); /// 混合基因 母猫基因 公猫基因 目标块? -> 下一代基因 function mixGenes( uint256 genes1, uint256 genes2, uint256 targetBlock ) public returns (uint256); } /// 管理特殊访问权限的门面 contract KittyAccessControl { // 4 个角色 // CEO 角色 任命其他角色 改变依赖的合约的地址 唯一可以停止加密猫的角色 在合约初始化时设置 // CFO 角色 可以从机密猫和它的拍卖合约中提出资金 // COO 角色 可以释放第 0 代加密猫 创建推广猫咪 // 这些权限被详细的分开。虽然 CEO 可以给指派任何角色,但 CEO 并不能够直接做这些角色的工作。 // 并非有意限制,而是尽量少使用 CEO 地址。使用的越少,账户被破坏的可能性就越小。 /// 合约升级事件 event ContractUpgrade(address newContract); // 每种角色的地址,也有可能是合约的地址. address public ceoAddress; address public cfoAddress; address public cooAddress; // 保持关注变量 paused 是否为真,一旦为真,大部分操作是不能够实行的 bool public paused = false; /// 修改器仅限 CEO modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// 修改器仅限 CFO modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// 修改器仅限 COO modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// 修改器仅限管理层(CEO 或 CFO 或 COO) modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// 设置新的 CEO 地址 仅限 CEO 操作 function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// 设置新的 CFO 地址 仅限 CEO 操作 function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// 设置新的 COO 地址 仅限 CEO 操作 function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } // OpenZeppelin 提供了很多合约方便使用,每个都应该研究一下 /*** Pausable functionality adapted from OpenZeppelin ***/ /// 修改器仅限没有停止合约 modifier whenNotPaused() { require(!paused); _; } /// 修改器仅限已经停止合约 modifier whenPaused() { require(paused); _; } /// 停止函数 仅限管理层 未停止时 调用 /// 在遇到 bug 或者 检测到非法牟利 这时需要限制损失 /// 仅可外部调用 function pause() external onlyCLevel whenNotPaused { paused = true; } /// 开始合约 仅限 CEO 已经停止时 调用 /// 不能给 CFO 或 COO 权限,因为万一他们账户被盗。 /// 注意这个方法不是外部的,公开表明可以被子合约调用 function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded // what? 如果合约升级了,不能被停止?? paused = false; } } /// 加密猫的基合约 包含所有普通结构体 事件 和 基本变量 contract KittyBase is KittyAccessControl { /*** EVENTS ***/ /// 出生事件 /// giveBirth 方法触发 /// 第 0 代猫咪被创建也会被触发 event Birth( address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes ); /// 转账事件是 ERC721 定义的标准时间,这里猫咪第一次被赋予所有者也会触发 event Transfer(address from, address to, uint256 tokenId); /*** DATA TYPES ***/ /// 猫咪的主要结构体,加密猫里的每个猫都要用这个结构体表示。务必确保这个结构体使用 2 个 256 位的字数。 /// 由于以太坊自己包装跪着,这个结构体中顺序很重要(改动就不满足 2 个 256 要求了) struct Kitty { // 猫咪的基因是 256 位,格式是 sooper-sekret 不知道这是什么格式?? uint256 genes; // 出生的时间戳 uint64 birthTime; // 这只猫可以再次进行繁育活动的最小时间戳 公猫和母猫都用这个时间戳 冷却时间?! uint64 cooldownEndBlock; // 下面 ID 用于记录猫咪的父母,对于第 0 代猫咪,设置为 0 // 采用 32 位数字,最大仅有 4 亿多点,目前够用了 截止目前 2021-09-26 有 200 万个猫咪了 uint32 matronId; uint32 sireId; // 母猫怀孕的话,设置为公猫的 id,否则是 0。非 0 表明猫咪怀孕了。 // 当新的猫出生时需要基因物质。 uint32 siringWithId; // 当前猫咪的冷却时间,是冷却时间数组的序号。第 0 代猫咪开始为 0,其他的猫咪是代数除以 2,每次成功繁育后都要自增 1 uint16 cooldownIndex; // 代数 直接由合约创建出来的是第 0 代,其他出生的猫咪由父母最大代数加 1 uint16 generation; } /*** 常量 ***/ /// 冷却时间查询表 /// 设计目的是鼓励玩家不要老拿一只猫进行繁育 /// 最大冷却时间是一周 uint32[14] public cooldowns = [ uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(10 minutes), uint32(30 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; // 目前每个块之间的时间间隔估计 uint256 public secondsPerBlock = 15; /*** 存储 ***/ /// 所有猫咪数据的列表 ID 就是猫咪在这个列表的序号 /// id 为 0 的猫咪是神秘生物,生育了第 0 代猫咪 Kitty[] kitties; /// 猫咪 ID 对应所有者的映射,第 0 代猫咪也有 mapping(uint256 => address) public kittyIndexToOwner; //// 所有者对拥有猫咪数量的映射 是 ERC721 接口 balanceOf 的底层数据支持 mapping(address => uint256) ownershipTokenCount; /// 猫咪对应的授权地址,授权地址可以取得猫咪的所有权 对应 ERC721 接口 transferFrom 方法 mapping(uint256 => address) public kittyIndexToApproved; /// 猫咪对应授权对方可以进行繁育的数据结构 对方可以通过 breedWith 方法进行猫咪繁育 mapping(uint256 => address) public sireAllowedToAddress; /// 定时拍卖合约的地址 点对点销售的合约 也是第 0 代猫咪每 15 分钟初始化的地方 SaleClockAuction public saleAuction; /// 繁育拍卖合约地址 需要和销售拍卖分开 二者有很大区别,分开为好 SiringClockAuction public siringAuction; /// 内部给予猫咪所有者的方法 仅本合约可用 what?感觉这个方法子类应该也可以调用啊??? function _transfer( address _from, address _to, uint256 _tokenId ) internal { // Since the number of kittens is capped to 2^32 we can't overflow this // 对应地址所拥有的数量加 1 ownershipTokenCount[_to]++; // 设置所有权 kittyIndexToOwner[_tokenId] = _to; // 第 0 代猫咪最开始没有 from,后面才会有 if (_from != address(0)) { // 如果有所有者 // 所有者猫咪数量减 1 ownershipTokenCount[_from]--; // 该猫咪设置过的允许繁育的地址删除 不能被上一个所有者设置的别人可以繁育继续有效 delete sireAllowedToAddress[_tokenId]; // 该猫咪设置过的允许授权的地址删除 不能被上一个所有者设置的别人可以拿走继续有效 delete kittyIndexToApproved[_tokenId]; } // 触发所有权变更事件,第 0 代猫咪创建之后,也会触发事件 Transfer(_from, _to, _tokenId); } /// 创建猫咪并存储的内部方法 不做权限参数检查,必须保证传入参数是正确的 会触发出生和转移事件 /// @param _matronId 母猫 id 第 0 代的话是 0 /// @param _sireId 公猫 id 第 0 代的话是 0 /// @param _generation 代数,必须先计算好 /// @param _genes 基因 /// @param _owner 初始所有者 (except for the unKitty, ID 0) function _createKitty( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _genes, address _owner ) internal returns (uint256) { // 这些检查是非严格检查,调用这应当确保参数是有效的,本方法依据是个非常昂贵的调用,不要再耗费 gas 检查参数了 require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint16(_generation))); // 新猫咪的冷却序号是代数除以 2 uint16 cooldownIndex = uint16(_generation / 2); if (cooldownIndex > 13) { cooldownIndex = 13; } Kitty memory _kitty = Kitty({ genes: _genes, birthTime: uint64(now), cooldownEndBlock: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), siringWithId: 0, cooldownIndex: cooldownIndex, generation: uint16(_generation) }); uint256 newKittenId = kitties.push(_kitty) - 1; // 确保是 32 位id require(newKittenId == uint256(uint32(newKittenId))); // 触发出生事件 Birth( _owner, newKittenId, uint256(_kitty.matronId), uint256(_kitty.sireId), _kitty.genes ); // 触发所有权转移事件 _transfer(0, _owner, newKittenId); return newKittenId; } /// 设置估计的每个块间隔,这里检查必须小于 1 分钟了 /// 必须管理层调用 外部函数 function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < cooldowns[0]); secondsPerBlock = secs; } } /// 外部合约 返回猫咪的元数据 只有一个方法返回字节数组数据 contract ERC721Metadata { /// 给 id 返回字节数组数据,能转化为字符串 /// what? 这都是写死的数据,不知道有什么用 function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) { if (_tokenId == 1) { buffer[0] = "Hello World! :D"; count = 15; } else if (_tokenId == 2) { buffer[0] = "I would definitely choose a medi"; buffer[1] = "um length string."; count = 49; } else if (_tokenId == 3) { buffer[0] = "Lorem ipsum dolor sit amet, mi e"; buffer[1] = "st accumsan dapibus augue lorem,"; buffer[2] = " tristique vestibulum id, libero"; buffer[3] = " suscipit varius sapien aliquam."; count = 128; } } } /// 加密猫核心合约的门面 管理权限 contract KittyOwnership is KittyBase, ERC721 { /// ERC721 接口 string public constant name = "CryptoKitties"; string public constant symbol = "CK"; // 元数据合约 ERC721Metadata public erc721Metadata; /// 方法签名常量,ERC165 要求的方法 bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); /// ERC721 要求的方法签名 /// 字节数组的 ^ 运算时什么意思?? /// 我明白了,ERC721 是一堆方法,不用一各一个验证,这么多方法一起合成一个值,这个值有就行了 bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("totalSupply()")) ^ bytes4(keccak256("balanceOf(address)")) ^ bytes4(keccak256("ownerOf(uint256)")) ^ bytes4(keccak256("approve(address,uint256)")) ^ bytes4(keccak256("transfer(address,uint256)")) ^ bytes4(keccak256("transferFrom(address,address,uint256)")) ^ bytes4(keccak256("tokensOfOwner(address)")) ^ bytes4(keccak256("tokenMetadata(uint256,string)")); /// 实现 ERC165 的方法 function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } /// 设置元数据合约地址,原来这个地址是可以修改的,那么就可以更新了 仅限 CEO 修改 function setMetadataAddress(address _contractAddress) public onlyCEO { erc721Metadata = ERC721Metadata(_contractAddress); } /// 内部工具函数,这些函数被假定输入参数是有效的。 参数校验留给公开方法处理。 /// 检查指定地址是否拥有某只猫咪 内部函数 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return kittyIndexToOwner[_tokenId] == _claimant; } /// 检查某只猫咪收被授权给某地址 内部函数 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return kittyIndexToApproved[_tokenId] == _claimant; } /// 猫咪收被授权给地址 这样该地址就能够通过 transferFrom 方法取得所有权 内部函数 /// 同一时间只允许有一个授权地址,如果地址是 0 的话,表示清除授权 /// 该方法不触发事件,故意不触发事件。当前方法和transferFrom方法一起在拍卖中使用,拍卖触发授权事件没有意义。 function _approve(uint256 _tokenId, address _approved) internal { kittyIndexToApproved[_tokenId] = _approved; } /// 返回某地址拥有的数量 这也是 ERC721 的方法 function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// 转移猫咪给其他地址 修改器检查只在非停止状态下允许转移 外部函数 /// 如果是转移给其他合约的地址,请清楚行为的后果,否则有可能永久失去这只猫咪 function transfer(address _to, uint256 _tokenId) external whenNotPaused { // 要求地址不为 0 require(_to != address(0)); /// 禁止转移给加密猫合约地址 本合约地址不应该拥有任何一只猫咪 除了再创建第 0 代并且还没进入拍卖的时候 require(_to != address(this)); /// 禁止转移给销售拍卖和繁育拍卖地址,销售拍卖对加密猫的所有权仅限于通过 授权 和 transferFrom 的方式 require(_to != address(saleAuction)); require(_to != address(siringAuction)); // 要求调用方拥有这只猫咪 require(_owns(msg.sender, _tokenId)); // 更改所有权 清空授权 触发转移事件 _transfer(msg.sender, _to, _tokenId); } /// 授权给其他地址 修改器检查只在非停止状态下允许 外部函数 /// 其他合约可以通过transferFrom取得所有权。这个方法被期望在授权给合约地址,参入地址为 0 的话就表明清除授权 /// ERC721 要求方法 function approve(address _to, uint256 _tokenId) external whenNotPaused { // 要求调用方拥有这只猫咪 require(_owns(msg.sender, _tokenId)); // 进行授权 _approve(_tokenId, _to); // 触发授权事件 Approval(msg.sender, _to, _tokenId); } /// 取得猫咪所有权 修改器检查只在非停止状态下允许 外部函数 /// ERC721 要求方法 function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { // 检查目标地址不是 0 require(_to != address(0)); // 禁止转移给当前合约 require(_to != address(this)); // 检查调用者是否有被授权,猫咪所有者地址是否正确 require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // 更改所有权 清空授权 触发转移事件 _transfer(_from, _to, _tokenId); } /// 目前所有猫咪数量 公开方法 只读 /// ERC721 要求方法 function totalSupply() public view returns (uint256) { return kitties.length - 1; } /// 查询某只猫咪的所有者 外部函数 只读 /// ERC721 要求方法 function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = kittyIndexToOwner[_tokenId]; require(owner != address(0)); } /// 返回某地址拥有的所有猫咪 id 列表 外部函数 只读 /// 这个方法不应该被合约调用,因为太消耗 gas /// 这方法返回一个动态数组,仅支持 web3 调用,不支持合约对合约的调用 function tokensOfOwner(address _owner) external view returns (uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // 返回空数组 return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalCats = totalSupply(); uint256 resultIndex = 0; // 遍历所有的猫咪如果地址相符就记录 uint256 catId; for (catId = 1; catId <= totalCats; catId++) { if (kittyIndexToOwner[catId] == _owner) { result[resultIndex] = catId; resultIndex++; } } return result; } } /// 内存拷贝方法 function _memcpy( uint256 _dest, uint256 _src, uint256 _len ) private view { // Copy word-length chunks while possible // 32 位一块一块复制 for (; _len >= 32; _len -= 32) { assembly { // 取出原地址 放到目标地址 mstore(_dest, mload(_src)) } _dest += 32; _src += 32; } // Copy remaining bytes // what? 剩下的部分看不明白了 这个指数运算啥意思啊 uint256 mask = 256**(32 - _len) - 1; assembly { let srcpart := and(mload(_src), not(mask)) let destpart := and(mload(_dest), mask) mstore(_dest, or(destpart, srcpart)) } } /// 转换成字符串 function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) { // 先得到指定长度的字符串 var outputString = new string(_stringLength); uint256 outputPtr; uint256 bytesPtr; assembly { // what? 这是取出指定变量的地址?? outputPtr := add(outputString, 32) // 为啥这个就直接当地址用了?? bytesPtr := _rawBytes } _memcpy(outputPtr, bytesPtr, _stringLength); return outputString; } /// 返回指定猫咪的元数据 包含 URI 信息 function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) { // 要求元数据合约地址指定 require(erc721Metadata != address(0)); bytes32[4] memory buffer; uint256 count; (buffer, count) = erc721Metadata.getMetadata( _tokenId, _preferredTransport ); return _toString(buffer, count); } } /// 加密猫核心合约的门面 管理猫咪生育 妊娠 和 出生 contract KittyBreeding is KittyOwnership { /// 怀孕事件 当 2 只猫咪成功的饲养并怀孕 event Pregnant( address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock ); /// 自动出生费? breedWithAuto方法使用,这个费用会在 giveBirth 方法中转变成 gas 消耗 /// 可以被 COO 动态更新 uint256 public autoBirthFee = 2 finney; // 怀孕的猫咪计数 uint256 public pregnantKitties; /// 基于科学 兄弟合约 实现基因混合算法,, GeneScienceInterface public geneScience; /// 设置基因合约 仅限 CEO 调用 function setGeneScienceAddress(address _address) external onlyCEO { GeneScienceInterface candidateContract = GeneScienceInterface(_address); require(candidateContract.isGeneScience()); // 要求是基因科学合约 geneScience = candidateContract; } /// 检查猫咪是否准备好繁育了 内部函数 只读 要求冷却时间结束 function _isReadyToBreed(Kitty _kit) internal view returns (bool) { // 额外检查冷却结束的块 我们同样需要建擦猫咪是否有等待出生?? 在猫咪怀孕结束和出生事件之间存在一些时间周期??莫名其妙 // In addition to checking the cooldownEndBlock, we also need to check to see if // the cat has a pending birth; there can be some period of time between the end // of the pregnacy timer and the birth event. return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); } /// 检查公猫是否授权和这个母猫繁育 内部函数 只读 如果是同一个所有者,或者公猫已经授权给母猫的地址,返回 true function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { address matronOwner = kittyIndexToOwner[_matronId]; address sireOwner = kittyIndexToOwner[_sireId]; return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); } /// 设置猫咪的冷却时间 基于当前冷却时间序号 同时增加冷却时间序号除非达到最大序号 内部函数 function _triggerCooldown(Kitty storage _kitten) internal { // 计算估计冷却的块 _kitten.cooldownEndBlock = uint64( (cooldowns[_kitten.cooldownIndex] / secondsPerBlock) + block.number ); // 繁育序号加一 最大是 13,冷却时间数组的最大长度,本来也可以数组的长度,但是这里硬编码进常量,为了节省 gas 费 if (_kitten.cooldownIndex < 13) { _kitten.cooldownIndex += 1; } } /// 授权繁育 外部函数 仅限非停止状态 /// 地址是将要和猫咪繁育的猫咪的所有者 设置 0 地址表明取消繁育授权 function approveSiring(address _addr, uint256 _sireId) external whenNotPaused { require(_owns(msg.sender, _sireId)); // 检查猫咪所有权 sireAllowedToAddress[_sireId] = _addr; // 记录允许地址 } /// 设置自动出生费 外部函数 仅限 COO function setAutoBirthFee(uint256 val) external onlyCOO { autoBirthFee = val; } /// 是否准备好出生 私有 只读 function _isReadyToGiveBirth(Kitty _matron) private view returns (bool) { return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); } /// 检查猫咪是否准备好繁育 公开 只读 function isReadyToBreed(uint256 _kittyId) public view returns (bool) { require(_kittyId > 0); Kitty storage kit = kitties[_kittyId]; return _isReadyToBreed(kit); } /// 是否猫咪怀孕了 公开 只读 function isPregnant(uint256 _kittyId) public view returns (bool) { require(_kittyId > 0); // 如果 siringWithId 被设置了表明就是怀孕了 return kitties[_kittyId].siringWithId != 0; } /// 内部检查公猫和母猫是不是个有效对 不检查所有权 function _isValidMatingPair( Kitty storage _matron, uint256 _matronId, Kitty storage _sire, uint256 _sireId ) private view returns (bool) { // 不能是自己 if (_matronId == _sireId) { return false; } // 母猫的妈妈不能是公猫 母猫的爸爸不能是公猫 if (_matron.matronId == _sireId || _matron.sireId == _sireId) { return false; } // 公猫的妈妈不能是母猫 公猫的爸爸不能是母猫 if (_sire.matronId == _matronId || _sire.sireId == _matronId) { return false; } // 如果公猫或母猫的妈妈是第 0 代猫咪,允许繁育 // We can short circuit the sibling check (below) if either cat is // gen zero (has a matron ID of zero). if (_sire.matronId == 0 || _matron.matronId == 0) { return true; } // 讲真我对加密猫的血缘检查无语了,什么乱七八糟的 // 猫咪不能与带血缘关系的繁育,同妈妈 或 公猫的妈妈和母猫的爸爸是同一个 if ( _sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId ) { return false; } // 同爸爸 或 公猫的爸爸和母猫的妈妈是同一个 if ( _sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId ) { return false; } // Everything seems cool! Let's get DTF. return true; } /// 内部检查是否可以通过拍卖进行繁育 function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) internal view returns (bool) { Kitty storage matron = kitties[_matronId]; Kitty storage sire = kitties[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId); } /// 检查 2 只猫咪是否可以繁育 外部函数 只读 检查所有权授权 不检查猫咪是否准备好繁育 在冷却时间期间是不能繁育成功的 function canBreedWith(uint256 _matronId, uint256 _sireId) external view returns (bool) { require(_matronId > 0); require(_sireId > 0); Kitty storage matron = kitties[_matronId]; Kitty storage sire = kitties[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId) && _isSiringPermitted(_sireId, _matronId); } /// 内部工具函数初始化繁育 假定所有的繁育要求已经满足 内部函数 function _breedWith(uint256 _matronId, uint256 _sireId) internal { // 获取猫咪信息 Kitty storage sire = kitties[_sireId]; Kitty storage matron = kitties[_matronId]; // 标记母猫怀孕 指向公猫 matron.siringWithId = uint32(_sireId); // 设置冷却时间 _triggerCooldown(sire); _triggerCooldown(matron); // 情况授权繁育地址,似乎多次一句,这里可以避免困惑 // tips 如果别人指向授权给某个人。每次繁育后还要继续设置,岂不是很烦躁 delete sireAllowedToAddress[_matronId]; delete sireAllowedToAddress[_sireId]; // 怀孕的猫咪计数加 1 pregnantKitties++; // 触发怀孕事件 Pregnant( kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock ); } /// 自动哺育一个猫咪 外部函数 可支付 仅限非停止状态 /// 哺育一个猫咪 作为母猫提供者,和公猫提供者 或 被授权的公猫 /// 猫咪是否会怀孕 或 完全失败 要看 giveBirth 函数给与的预支付的费用 function breedWithAuto(uint256 _matronId, uint256 _sireId) external payable whenNotPaused { require(msg.value >= autoBirthFee); // 要求大于自动出生费 require(_owns(msg.sender, _matronId)); // 要求是母猫所有者 // 哺育操作期间 允许猫咪被拍卖 拍卖的事情这里不关心 // 对于母猫:这个方法的调用者不会是母猫的所有者,因为猫咪的所有者是拍卖合约 拍卖合约不会调用繁育方法 // 对于公猫:统一,公猫也属于拍卖合约,转移猫咪会清除繁育授权 // 因此我们不花费 gas 费检查猫咪是否属于拍卖合约 // 检查猫咪是否都属于调用者 或 公猫是给与授权的 require(_isSiringPermitted(_sireId, _matronId)); Kitty storage matron = kitties[_matronId]; // 获取母猫信息 require(_isReadyToBreed(matron)); // 确保母猫不是怀孕状态 或者 哺育冷却期 Kitty storage sire = kitties[_sireId]; // 获取公猫信息 require(_isReadyToBreed(sire)); // 确保公猫不是怀孕状态 或者 哺育冷却期 require(_isValidMatingPair(matron, _matronId, sire, _sireId)); // 确保猫咪是有效的匹配 _breedWith(_matronId, _sireId); // 进行繁育任务 } /// 已经有怀孕的猫咪 才能 出生 外部函数 仅限非暂停状态 /// 如果怀孕并且妊娠时间已经过了 联合基因创建一个新的猫咪 /// 新的猫咪所有者是母猫的所有者 /// 知道成功的结束繁育,公猫和母猫才会进入下个准备阶段 /// 注意任何人可以调用这个方法 只要他们愿意支付 gas 费用 但是新猫咪仍然属于母猫的所有者 function giveBirth(uint256 _matronId) external whenNotPaused returns (uint256) { Kitty storage matron = kitties[_matronId]; // 获取母猫信息 require(matron.birthTime != 0); // 要求母猫是有效的猫咪 // Check that the matron is pregnant, and that its time has come! require(_isReadyToGiveBirth(matron)); // 要求母猫准备好生猫咪 是怀孕状态并且时间已经到了 uint256 sireId = matron.siringWithId; // 公猫 id Kitty storage sire = kitties[sireId]; // 公猫信息 uint16 parentGen = matron.generation; // 母猫代数 if (sire.generation > matron.generation) { parentGen = sire.generation; // 如果公猫代数高,则用公猫代数 } // 调用混合基因的方法 uint256 childGenes = geneScience.mixGenes( matron.genes, sire.genes, matron.cooldownEndBlock - 1 ); // 制作新猫咪 address owner = kittyIndexToOwner[_matronId]; uint256 kittenId = _createKitty( _matronId, matron.siringWithId, parentGen + 1, childGenes, owner ); delete matron.siringWithId; // 清空母猫的配对公猫 id pregnantKitties--; // 每次猫咪出生,计数器减 1 msg.sender.send(autoBirthFee); // 支付给调用方自动出生费用 return kittenId; // 返回猫咪 id } } /// 定时拍卖核心 包含 结构 变量 内置方法 contract ClockAuctionBase { // 一个 NFT 拍卖的表示 struct Auction { // NFT 当前所有者 address seller; // 开始拍卖的价格 单位 wei uint128 startingPrice; // 结束买卖的价格 单位 wei uint128 endingPrice; // 拍卖持续时间 单位秒 uint64 duration; // 拍卖开始时间 如果是 0 表示拍卖已经结束 uint64 startedAt; } // 关联的 NFT 合约 ERC721 public nonFungibleContract; // 每次拍卖收税 0-10000 对应这 0%-100% uint256 public ownerCut; // 每只猫对应的拍卖信息 mapping(uint256 => Auction) tokenIdToAuction; /// 拍卖创建事件 event AuctionCreated( uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration ); /// 拍卖成功事件 event AuctionSuccessful( uint256 tokenId, uint256 totalPrice, address winner ); /// 拍卖取消事件 event AuctionCancelled(uint256 tokenId); /// 某地址是否拥有某只猫咪 内部函数 只读 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// 托管猫咪 将猫咪托管给当前拍卖合约 function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// NFT 转账 内部函数 function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// 增加拍卖 触发拍卖事件 内部函数 function _addAuction(uint256 _tokenId, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; // 触发拍卖创建事件 AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) ); } /// 取消拍卖 触发取消事件 内部函数 function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); AuctionCancelled(_tokenId); } /// 计算价格并转移 NFT 给胜者 内部函数 function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // 获取拍卖数据 Auction storage auction = tokenIdToAuction[_tokenId]; // 要求拍卖属于激活状态 require(_isOnAuction(auction)); // 要求出价不低于当前价格 uint256 price = _currentPrice(auction); require(_bidAmount >= price); // 获取卖家地址 address seller = auction.seller; // 移除这个猫咪的拍卖 _removeAuction(_tokenId); // 转账给卖家 if (price > 0) { // 计算拍卖费用 uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; // 进行转账 // 在一个复杂的方法中惊调用转账方法是不被鼓励的,因为可能遇到可重入个攻击或者拒绝服务攻击. // 我们明确的通过移除拍卖来防止充入攻击,卖价用 DOS 操作只能攻击他自己的资产 // 如果真有意外发生,可以通过调用取消拍卖 seller.transfer(sellerProceeds); } // 计算超出的额度 uint256 bidExcess = _bidAmount - price; // 返还超出的费用 msg.sender.transfer(bidExcess); // 触发拍卖成功事件 AuctionSuccessful(_tokenId, price, msg.sender); return price; } /// 删除拍卖 内部函数 function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// 判断拍卖是否为激活状态 内部函数 只读 function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// 计算当前价格 内部函数 只读 /// 需要 2 个函数 /// 当前函数 计算事件 另一个 计算价格 function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; // 确保正值 if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } /// 计算拍卖的当前价格 内部函数 纯计算 function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { // 没有是有 SafeMath 或类似的函数,是因为所有公开方法 时间最大值是 64 位 货币最大只是 128 位 if (_secondsPassed >= _duration) { // 超出时间就是最后的价格 return _endingPrice; } else { // 线性插值?? 讲真我觉得不算拍卖,明明是插值价格 int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); int256 currentPriceChange = (totalPriceChange * int256(_secondsPassed)) / int256(_duration); int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /// 收取拍卖费用 内部函数 只读 function _computeCut(uint256 _price) internal view returns (uint256) { return (_price * ownerCut) / 10000; } } /// 可停止的合约 contract Pausable is Ownable { event Pause(); // 停止事件 event Unpause(); // 继续事件 bool public paused = false; // what? 不是已经有一个 paused 了吗?? 上面的是管理层控制的中止 这个是所有者控制的中止 合约很多 modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } /// 定时拍卖 contract ClockAuction is Pausable, ClockAuctionBase { /// ERC721 接口的方法常量 ERC165 接口返回 bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); /// 构造器函数 传入 nft 合约地址和手续费率 function ClockAuction(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nonFungibleContract = candidateContract; } /// 提出余额 外部方法 function withdrawBalance() external { address nftAddress = address(nonFungibleContract); // 要求是所有者或 nft 合约 require(msg.sender == owner || msg.sender == nftAddress); // 使用 send 确保就算转账失败也能继续运行 bool res = nftAddress.send(this.balance); } /// 创建一个新的拍卖 外部方法 仅限非停止状态 function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external whenNotPaused { require(_startingPrice == uint256(uint128(_startingPrice))); // 检查开始价格 require(_endingPrice == uint256(uint128(_endingPrice))); // 检查结束价格 require(_duration == uint256(uint64(_duration))); // 检查拍卖持续时间 require(_owns(msg.sender, _tokenId)); // 检查所有者权限 _escrow(msg.sender, _tokenId); // 托管猫咪给合约 Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); // 保存拍卖信息 } /// 购买一个拍卖 完成拍卖和转移所有权 外部函数 可支付 仅限非停止状态 function bid(uint256 _tokenId) external payable whenNotPaused { _bid(_tokenId, msg.value); // 入股购买资金转移失败,会报异常 _transfer(msg.sender, _tokenId); } /// 取消没有胜者的拍卖 外部函数 /// 注意这个方法可以再合约被停止的情况下调用 function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; // 找到拍卖信息 require(_isOnAuction(auction)); // 检查拍卖是否激活状态 讲真的,从某种设计的角度来说,我觉得这种检查放到拍卖合约里面检查比较好,额,当前合约就是拍卖合约。。。 address seller = auction.seller; // 卖家地址 require(msg.sender == seller); // 检查调用者是不是卖家地址 _cancelAuction(_tokenId, seller); // 取消拍卖 } /// 取消拍卖 外部函数 仅限停止状态 仅限合约拥有者调用 /// 紧急情况下使用的方法 function cancelAuctionWhenPaused(uint256 _tokenId) external whenPaused onlyOwner { Auction storage auction = tokenIdToAuction[_tokenId]; // 找到拍卖信息 require(_isOnAuction(auction)); // 检查是否激活状态 _cancelAuction(_tokenId, auction.seller); // 取消拍卖 } /// 返回拍卖信息 外部函数 只读 function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; // 找到拍卖信息 require(_isOnAuction(auction)); // 检查拍卖是激活状态 return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } /// 获取拍卖当前价格 外部函数 只读 function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; // 找到拍卖信息 require(_isOnAuction(auction)); // 检查拍卖是激活状态 return _currentPrice(auction); // 计算当前价格 } } /// 繁育拍卖合约 contract SiringClockAuction is ClockAuction { // 在setSiringAuctionAddress方法调用中,合约检查确保我们在操作正确的拍卖 bool public isSiringClockAuction = true; // 委托父合约构造函数 function SiringClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// 创建一个拍卖 外部函数 /// 包装函数 要求调用方必须是 KittyCore 核心 function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { require(_startingPrice == uint256(uint128(_startingPrice))); // 检查开始价格 require(_endingPrice == uint256(uint128(_endingPrice))); // 检查结束价格 require(_duration == uint256(uint64(_duration))); // 检查拍卖持续时间 require(msg.sender == address(nonFungibleContract)); // 要求调用者是 nft 合约地址 _escrow(_seller, _tokenId); // 授权拍卖 Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); // 添加拍卖信息 } /// 发起一个出价 外部函数 可支付 /// 要求调用方是 KittyCore 合约 因为所有的出价方法都被包装 /// 同样退回猫咪给卖家 看不懂说的啥 Also returns the kitty to the seller rather than the winner. function bid(uint256 _tokenId) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; _bid(_tokenId, msg.value); _transfer(seller, _tokenId); } } /// 销售拍卖合约 contract SaleClockAuction is ClockAuction { // 在setSaleAuctionAddress方法调用中,合约检查确保我们在操作正确的拍卖 bool public isSaleClockAuction = true; uint256 public gen0SaleCount; // 第 0 代猫咪售出计数 uint256[5] public lastGen0SalePrices; // 记录最近 5 只第 0 代卖出价格 // 委托父合约构造函数 function SaleClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// 创建新的拍卖 function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// 如果卖家是 NFT合约 更新价格 function bid(uint256 _tokenId) external payable { // _bid verifies token ID size address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); // If not a gen0 auction, exit if (seller == address(nonFungibleContract)) { // Track gen0 sale prices lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } } /// 平均第 0 代售价 外部函数 只读 function averageGen0SalePrice() external view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastGen0SalePrices[i]; } return sum / 5; } } /// 猫咪拍卖合约 创建销售和繁育的拍卖 /// This wrapper of ReverseAuction exists only so that users can create /// auctions with only one transaction. contract KittyAuction is KittyBreeding { // 当前拍卖合约变量定义在 KittyBase 中,KittyOwnership中有对变量的检查 // 销售拍卖参考第 0 代拍卖和 p2p 销售 // 繁育拍卖参考猫咪的繁育权拍卖 /// 设置销售拍卖合约 外部函数 仅限 CEO 调用 function setSaleAuctionAddress(address _address) external onlyCEO { SaleClockAuction candidateContract = SaleClockAuction(_address); require(candidateContract.isSaleClockAuction()); saleAuction = candidateContract; } /// 设置繁育排满合约 外部函数 仅限 CEO 调用 function setSiringAuctionAddress(address _address) external onlyCEO { SiringClockAuction candidateContract = SiringClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSiringClockAuction()); // Set the new contract address siringAuction = candidateContract; } /// 将一只猫咪放入销售拍卖 外部函数 仅限非停止状态调用 function createSaleAuction( uint256 _kittyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // 拍卖合约检查输入参数大小 // 如果猫咪已经在拍卖中了,会报异常,因为所有权在拍卖合约那里 require(_owns(msg.sender, _kittyId)); // 确保猫咪不在怀孕状态 防止买到猫咪的人收到小猫咪的所有权 require(!isPregnant(_kittyId)); _approve(_kittyId, saleAuction); // 授权猫咪所有权给拍卖合约 // 如果参数有误拍卖合约会报异常。 调用成功会清除转移和繁育授权 saleAuction.createAuction( _kittyId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// 将一只猫咪放入繁育拍卖 外部函数 仅限非停止状态调用 function createSiringAuction( uint256 _kittyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // 拍卖合约检查输入参数大小 // 如果猫咪已经在拍卖中了,会报异常,因为所有权在拍卖合约那里 require(_owns(msg.sender, _kittyId)); require(isReadyToBreed(_kittyId)); // 检查猫咪是否在哺育状态 _approve(_kittyId, siringAuction); // 授权猫咪所有权给拍卖合约 // 如果参数有误拍卖合约会报异常。 调用成功会清除转移和繁育授权 siringAuction.createAuction( _kittyId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// 出价完成一个繁育合约 猫咪会立即进入哺育状态 外部函数 可以支付 仅当非停止状态 function bidOnSiringAuction(uint256 _sireId, uint256 _matronId) external payable whenNotPaused { // 拍卖合约检查输入大小 require(_owns(msg.sender, _matronId)); require(isReadyToBreed(_matronId)); require(_canBreedWithViaAuction(_matronId, _sireId)); // 计算当前价格 uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); require(msg.value >= currentPrice + autoBirthFee); // 出价要高于当前价格和自动出生费用 // 如果出价失败,繁育合约会报异常 siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); _breedWith(uint32(_matronId), uint32(_sireId)); } /// 转移拍卖合约的余额到 KittyCore 外部函数仅限管理层调用 function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); siringAuction.withdrawBalance(); } } /// 所有关系到创建猫咪的函数 contract KittyMinting is KittyAuction { // 限制合约创建猫咪的数量 uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant GEN0_CREATION_LIMIT = 45000; // 第 0 代猫咪拍卖的常数 uint256 public constant GEN0_STARTING_PRICE = 10 finney; uint256 public constant GEN0_AUCTION_DURATION = 1 days; // 合约创建猫咪计数 uint256 public promoCreatedCount; uint256 public gen0CreatedCount; /// 创建推广猫咪 外部函数 仅限 COO 调用 function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { address kittyOwner = _owner; if (kittyOwner == address(0)) { kittyOwner = cooAddress; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createKitty(0, 0, 0, _genes, kittyOwner); } /// 创建第 0 代猫咪 外部函数 仅限 COO 调用 /// 为猫咪创建一个拍卖 function createGen0Auction(uint256 _genes) external onlyCOO { require(gen0CreatedCount < GEN0_CREATION_LIMIT); uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); _approve(kittyId, saleAuction); saleAuction.createAuction( kittyId, _computeNextGen0Price(), 0, GEN0_AUCTION_DURATION, address(this) ); gen0CreatedCount++; } /// 计算第 0 代拍卖的价格 最后 5 个价格平均值 + 50% 内部函数 只读 function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); // Sanity check to ensure we don't overflow arithmetic require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; } return nextPrice; } } /// 加密猫核心 收集 哺育 领养? contract KittyCore is KittyMinting { // 这是加密猫的主要合约。为了让代码和逻辑部分分开,我们采用了 2 种方式。 // 第一,我们分开了部分兄弟合约管理拍卖和我们最高秘密的基因混合算法。 // 拍卖分开因为逻辑在某些方面比较复杂,另外也总是存在小 bug 的风险。 // 让这些风险在它们自己的合约里,我们可以升级它们,同时不用干扰记录着猫咪所有权的主合约。 // 基因混合算法分离是因为我们可以开源其他部分的算法,同时防止别人很容易就分叉弄明白基因部分是如何工作的。不用担心,我确定很快就会有人对齐逆向工程。 // 第二,我们分开核心合约产生多个文件是为了使用继承。这让我们保持关联的代码紧紧绑在一起,也避免了所有的东西都在一个巨型文件里。 // 分解如下: // // - KittyBase: 这是我们定义大多数基础代码的地方,这些代码贯穿了核心功能。包括主要数据存储,常量和数据类型,还有管理这些的内部函数。 // // - KittyAccessControl: 这个合约管理多种地址和限制特殊角色操作,像是 CEO CFO COO // // - KittyOwnership: 这个合约提供了基本的 NFT token 交易 请看 ERC721 // // - KittyBreeding: 这个包含了必要的哺育猫咪相关的方法,包括保证对公猫提供者的记录和对外部基因混合合约的依赖 // // - KittyAuctions: 这里我们有许多拍卖、出价和繁育的方法,实际的拍卖功能存储在 2 个兄弟合约(一个管销售 一个管繁育),拍卖创建和出价都要通过这个合约操作。 // // - KittyMinting: 这是包含创建第 0 代猫咪的最终门面合约。我们会制作 5000 个推广猫咪,这样的猫咪可以被分出去,比如当社区建立时。 // 所有的其他猫咪仅仅能够通过创建并立即进入拍卖,价格通过算法计算的方式分发出去。不要关心猫咪是如何被创建的,有一个 5 万的硬性限制。之后的猫咪都只能通过繁育生产。 // 当核心合约被破坏并且有必要升级时,设置这个变量 address public newContractAddress; /// 构造函数 创建主要的加密猫的合约实例 function KittyCore() public { paused = true; // 开始是暂停状态 ceoAddress = msg.sender; // 设置 ceo 地址 cooAddress = msg.sender; // 设置 coo 地址 // 创建神秘之猫,这个猫咪会产生第 0 代猫咪 _createKitty(0, 0, 0, uint256(-1), address(0)); } ///用于标记智能合约升级 防止出现严重 bug,这个方法只是记录新合约地址并触发合约升级事件。在这种情况下,客户端要采用新的合约地址。若升级发生,本合约会处于停止状态。 function setNewAddress(address _v2Address) external onlyCEO whenPaused { // 看 README.md 了解升级计划 newContractAddress = _v2Address; ContractUpgrade(_v2Address); // 触发合约升级事件 } /// fallback 函数 退回所有发送到本合约的以太币 除非是销售拍卖合约和繁育拍卖合约发来的 function() external payable { require( msg.sender == address(saleAuction) || msg.sender == address(siringAuction) ); } /// 获取猫咪信息 function getKitty(uint256 _id) external view returns ( bool isGestating, bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint256 siringWithId, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 generation, uint256 genes ) { Kitty storage kit = kitties[_id]; isGestating = (kit.siringWithId != 0); // 如果 siringWithId 不是 0 表明处于妊娠状态 isReady = (kit.cooldownEndBlock <= block.number); cooldownIndex = uint256(kit.cooldownIndex); nextActionAt = uint256(kit.cooldownEndBlock); siringWithId = uint256(kit.siringWithId); birthTime = uint256(kit.birthTime); matronId = uint256(kit.matronId); sireId = uint256(kit.sireId); generation = uint256(kit.generation); genes = kit.genes; } /// 启动合约 要求所有的外部合约地址都被设置,才能够启动合约。如果升级合约被设置了,那么无法启动合约 公开函数 要求 CEO 才能调用 仅限合约停止状态调用 /// public 我们才能调用父合约的外部方法 function unpause() public onlyCEO whenPaused { require(saleAuction != address(0)); require(siringAuction != address(0)); require(geneScience != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } // 提现方法 外部 仅限 CFO function withdrawBalance() external onlyCFO { uint256 balance = this.balance; // 减去所有怀孕的猫咪数量+1作为余量 uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; if (balance > subtractFees) { cfoAddress.send(balance - subtractFees); } } }
发起一个出价 外部函数 可支付 要求调用方是 KittyCore 合约 因为所有的出价方法都被包装 同样退回猫咪给卖家 看不懂说的啥 Also returns the kitty to the seller rather than the winner.
function bid(uint256 _tokenId) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; _bid(_tokenId, msg.value); _transfer(seller, _tokenId); }
967,979
// SPDX-License-Identifier: MIT // Указываем версию для компилятора pragma solidity ^0.7.6; // Контракт для установки прав contract OwnableWithDAO{ // Переменная для хранения владельца контракта address public owner; // Переменная для хранения адреса DAO address public daoContract; // Конструктор, который при создании инициализирует переменную с владельцем constructor() { owner = msg.sender; } // Модификатор для защиты от вызовов не создателя контракта modifier onlyOwner(){ require(msg.sender == owner); _; } // Модификатор для защиты от вызовов не со стороны DAO modifier onlyDAO(){ require(msg.sender == daoContract); _; } // Функция для замены владельца function transferOwnership(address newOwner) onlyOwner public{ require(newOwner != address(0)); owner = newOwner; } } /* SafeMath Математические операторы с проверками ошибок */ library SafeMath { function mul(uint _a, uint _b) internal pure returns (uint) { uint c = _a * _b; assert(_a == 0 || c / _a == _b); return c; } function div(uint _a, uint _b) internal pure returns (uint) { // assert(b > 0); // Solidity автоматически выбрасывает ошибку при делении на ноль, так что проверка не имеет смысла uint c = _a / _b; // assert(a == b * c + a % b); // Не существует случая, когда эта проверка не была бы пройдена return c; } function sub(uint _a, uint _b) internal pure returns (uint) { assert(_b <= _a); return _a - _b; } function add(uint _a, uint _b) internal pure returns (uint) { uint c = _a + _b; assert(c >= _a); return c; } } // Контракт для остановки некоторых операций contract Stoppable is OwnableWithDAO{ // Функция для установки / замены контракта DAO function setDAOContract(address _newDAO) onlyOwner public { // Нельзя сменить контракт, пока голосование активно // (защита от утечки списков голосующих) require(votersList[1] == address(0)); daoContract = _newDAO; } // Функция для просмотра создателя извне function viewOwner() public onlyDAO view returns (address _owner) { return owner; } // Списки голосующих mapping (uint => address) private votersList; // default: private mapping (address => uint) private votersList1; // Функция для просмотра первого списка извне function viewList(uint _uint) public onlyDAO view returns (address _address) { return votersList[_uint]; } // Функция для просмотра второго списка извне function viewList1(address _address) public onlyDAO view returns (uint _uint) { return votersList1[_address]; } function strToBytes32(string memory _string) internal pure returns(bytes32) { return keccak256(abi.encodePacked(_string)); } // Функция для взаимодействия со списками извне function useList(string memory _name, string memory _func, uint _uint, address _address) public onlyDAO { if (strToBytes32(_name) == strToBytes32("votersList")) { if (strToBytes32(_func) == strToBytes32("change")) { votersList[_uint] = _address; } if (strToBytes32(_func) == strToBytes32("delete")) { delete votersList[_uint]; } } if (strToBytes32(_name) == strToBytes32("votersList1")) { if (strToBytes32(_func) == strToBytes32("change")) { votersList1[_address] = _uint; } if (strToBytes32(_func) == strToBytes32("delete")) { delete votersList1[_address]; } } } // Модификатор для проверки возможности выполнения функции modifier stoppable(address _address) { require(votersList1[_address] == 0); _; } } // Инициализация контракта contract DAOToken is Stoppable { using SafeMath for uint; // Объявляем переменную в которой будет название токена string public name; // Объявляем переменную в которой будет символ токена string public symbol; // Объявляем переменную в которой будет число нулей токена uint8 public decimals; // Объявляем переменную в которой будет храниться общее число токенов uint public totalSupply; // Объявляем маппинг для хранения балансов пользователей mapping (address => uint) internal balances; // Объявляем маппинг для хранения одобренных транзакций mapping (address => mapping (address => uint)) public allowance; // Объявляем эвент для логгирования события перевода токенов event Transfer(address from, address to, uint value); // Объявляем эвент для логгирования события одобрения перевода токенов event Approval(address from, address to, uint value); // Функция инициализации контракта constructor(){ // Указываем число нулей decimals = 0; // Объявляем общее число токенов, которое будет создано при инициализации totalSupply = 1500000 * (10 ** uint(decimals)); // 10000000 * (10^decimals) // "Отправляем" все токены на баланс того, кто инициализировал создание контракта токена balances[msg.sender] = totalSupply; // Указываем название токена name = "DAOCoin"; // Указываем символ токена symbol = "DAO"; } // Внутренняя функция для перевода токенов function transfer(address _to, uint _value) public stoppable(msg.sender) returns (bool success) { require(_to != address(0)); require(balances[msg.sender] >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } // Функция для перевода "одобренных" токенов function transferFrom(address _from, address _to, uint _value) public stoppable(msg.sender) returns (bool success) { require(_to != address(0)); require(_value <= balances[_from]); // Проверка, что токены были выделены аккаунтом _from для аккаунта _to require(_value <= allowance[_from][_to]); // Уменьшаем число "одобренных" токенов allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Отправка токенов transfer(_to, _value); emit Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } // Функция для "одобрения" перевода токенов function approve(address _to, uint _value) public stoppable(msg.sender) returns (bool success) { // Запись в мапппинг число "одобренных" токенов allowance[msg.sender][_to] = _value; // Вызов ивента для логгирования события одобрения перевода токенов emit Approval(msg.sender, _to, _value); return true; } // Функция для смены тикера function changeSymbol(string memory _symbol) public onlyDAO { symbol = _symbol; } // Функция для смены названия токена function changeName(string memory _name) public onlyDAO { name = _name; } } contract BurnableToken is DAOToken { using SafeMath for uint; event Burn(address indexed burner, uint256 value); /* Сжигает определённое количество токенов. */ function burn(uint256 _value) public { require(_value > 0); require(_value <= balances[msg.sender]); // нет необходимости проверять value <= totalSupply, так как это будет подразумевать, что // баланс отправителя больше, чем totalSupply, что должно привести к ошибке address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(burner, _value); } }
Функция для смены тикера
function changeSymbol(string memory _symbol) public onlyDAO { symbol = _symbol; }
1,785,498
/** *Submitted for verification at Etherscan.io on 2022-04-01 */ // SPDX-License-Identifier: MIT // File contracts/autocompounder/common/IMasterChef.sol // File: contracts/BIFI/interfaces/pancake/IMasterChef.sol pragma solidity ^0.8.0; interface IMasterChef { function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function enterStaking(uint256 _amount) external; function leaveStaking(uint256 _amount) external; function userInfo(uint256 _pid, address _user) external view returns (uint256, uint256); function emergencyWithdraw(uint256 _pid) external; // pending* function changes names often (e.g. pendingYEL, pendingReward). // This is only called in the tests, so no need to include it in the contract's interface // function pendingCake(uint256 _pid, address _user) external view returns (uint256); } // File contracts/autocompounder/common/Context.sol // File: @openzeppelin/contracts/GSN/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 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 payable(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/autocompounder/common/IERC20.sol // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/autocompounder/common/Ownable.sol // 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. */ 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/autocompounder/common/Address.sol // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File contracts/autocompounder/common/ERC20.sol // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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 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. * * #ANDREW: arguments name/symbols to nameFoo/SymbolFoo to avoid "This declaration shadows an existing declaration." warning **/ constructor (string memory nameFoo, string memory symbolFoo) { _name = nameFoo; _symbol = symbolFoo; _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()] - 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) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] - 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); _balances[sender] = _balances[sender] - amount; _balances[recipient] = _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 = _totalSupply + amount; _balances[account] = _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); _balances[account] = _balances[account] - amount; _totalSupply = _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 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/autocompounder/common/SafeERC20.sol // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // 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 { uint256 newAllowance = token.allowance(address(this), spender) - 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"); } } } // File contracts/autocompounder/common/Pausable.sol // File: @openzeppelin/contracts/utils/Pausable.sol pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ 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 returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File contracts/autocompounder/common/FullMath.sol // https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol pragma solidity ^0.8.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits 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 = (type(uint256).max - denominator + 1) & denominator; // 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++; } } } // File contracts/autocompounder/common/IUniswapRouterETH.sol // File: contracts/BIFI/interfaces/common/IUniswapRouterETH.sol pragma solidity ^0.8.0; interface IUniswapRouterETH { 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 swapExactTokensForTokens( uint amountIn, uint amountOutMin, 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 swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); // For TraderJoeRouter on AVAX, needed for UnirouterShim.sol function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } // File contracts/autocompounder/common/StratManager.sol pragma solidity ^0.8.0; contract StratManager is Ownable, Pausable { /** * @dev Crack Contracts: * {keeper} - Address to manage a few lower risk features of the strat * {strategist} - Address of the strategy author/deployer where strategist fee will go. * {vault} - Address of the vault that controls the strategy's funds. * {unirouter} - Address of exchange to execute swaps. */ address public keeper; address public strategist; address public unirouter; address public vault; /** * @dev Initializes the base strategy. * @param _keeper address to use as alternative owner. * @param _strategist address where strategist fees go. * @param _unirouter router to use for swaps * @param _vault address of parent vault. */ constructor( address _keeper, address _strategist, address _unirouter, address _vault ) { keeper = _keeper; strategist = _strategist; unirouter = _unirouter; vault = _vault; } // checks that caller is either owner or keeper. modifier onlyManager() { require(msg.sender == owner() || msg.sender == keeper, "!manager"); _; } // verifies that the caller is not a contract. modifier onlyEOA() { require(msg.sender == tx.origin, "!EOA"); _; } /** * @dev Updates address of the strat keeper. * @param _keeper new keeper address. */ function setKeeper(address _keeper) external onlyManager { keeper = _keeper; } /** * @dev Updates address where strategist fee earnings will go. * @param _strategist new strategist address. */ function setStrategist(address _strategist) external { require(msg.sender == strategist, "!strategist"); strategist = _strategist; } /** * @dev Updates router that will be used for swaps. * @param _unirouter new unirouter address. */ function setUnirouter(address _unirouter) external onlyOwner { unirouter = _unirouter; } /** * @dev Updates parent vault. * @param _vault new vault address. */ function setVault(address _vault) external onlyOwner { vault = _vault; } /** * @dev Function to synchronize balances before new user deposit. * Can be overridden in the strategy. */ function beforeDeposit() external virtual {} } // File contracts/autocompounder/common/FeeManager.sol pragma solidity ^0.8.0; abstract contract FeeManager is StratManager { uint constant public MAXFEE = 1000; uint public withdrawalFee = 0; // fee taken out on withdraw uint public strategistFee = 69; // 6.9% stratigest fee uint public sideProfitFee = 0; // amount of rewardToken swapped to stable uint public callFee = 4; // .4% fee paid to caller function setWithdrawalFee(uint256 _fee) external onlyManager { require(_fee <= MAXFEE, "fee too high"); withdrawalFee = _fee; } function setStratFee(uint256 _fee) external onlyManager { require(_fee < MAXFEE, "fee too high"); strategistFee = _fee; } function setProfitFees(uint256 _fee) external onlyManager { require(_fee < MAXFEE, "fee too high"); sideProfitFee = _fee; } function setCallFee(uint256 _fee) external onlyManager { require(_fee < MAXFEE, "fee too high"); callFee = _fee; } } // File contracts/autocompounder/SS-Strategy/StrategySSBase.sol pragma solidity ^0.8.0; //import "hardhat/console.sol"; abstract contract StrategySSBase is StratManager, FeeManager { using SafeERC20 for IERC20; // Tokens IERC20 public swapToken; IERC20 public rewardToken; IERC20 public stakedToken; IERC20 public sideProfitToken; // Routes address[] public rewardToStakedRoute; address[] public rewardToProfitRoute; uint256 MAX_INT = type(uint256).max; uint256 public lastHarvest; // Event that is fired each time someone harvests the strat. event StratHarvest(address indexed harvester); // Virtual functions should be overwritten by derived contracts. function farmAddress() public virtual returns (address) {} function setFarmAddress(address newAddr) internal virtual {} function farmDeposit(uint256 amount) internal virtual {} function farmWithdraw(uint256 amount) internal virtual {} function farmEmergencyWithdraw() internal virtual {} function beforeHarvest() internal virtual {} function balanceOfPool() public view virtual returns (uint256) {} function giveAllowances() internal virtual {} function removeAllowances() internal virtual {} function resetValues(address _swapToken, address _rewardToken, address _farmAddr, address _lpToken, uint256 _poolId, address _sideProfitToken) public virtual {} constructor( address _swapToken, // Should be what rewardToken gets routed through when swapping for profit and LP halves. address _rewardToken, // what the farm emits Token address _stakedToken, // what you put in Token address _vault, // Crack Vault that uses this strategy address _unirouter, // Unirouter on this chain to call for swaps address _keeper, // address to use as alternative owner address _strategist, // address where strategist fees go address _sideProfitToken // address of sideProfitToken token ) StratManager(_keeper, _strategist, _unirouter, _vault) { swapToken = IERC20(_swapToken); rewardToken = IERC20(_rewardToken); stakedToken = IERC20(_stakedToken); sideProfitToken = IERC20(_sideProfitToken); if (swapToken == sideProfitToken) { rewardToProfitRoute = [address(rewardToken), address(sideProfitToken)]; } else { rewardToProfitRoute = [address(rewardToken), address(swapToken), address(sideProfitToken)]; } if (swapToken == stakedToken) { rewardToStakedRoute = [address(rewardToken), address(stakedToken)]; } else { rewardToStakedRoute = [address(rewardToken), address(swapToken), address(stakedToken)]; } } // puts the funds to work function deposit() public whenNotPaused { uint256 stakedBal = stakedToken.balanceOf(address(this)); if (stakedBal > 0) { farmDeposit(stakedBal); } } function beforeDeposit() external override whenNotPaused { //_harvestInternal(); } function withdraw(uint256 _amount) external { require(msg.sender == vault, "!vault"); uint256 stakedBal = stakedToken.balanceOf(address(this)); if (stakedBal < _amount) { farmWithdraw(_amount - stakedBal); stakedBal = stakedToken.balanceOf(address(this)); } if (stakedBal > _amount) { stakedBal = _amount; } if (tx.origin == owner() || paused()) { stakedToken.safeTransfer(vault, stakedBal); } else { uint256 withdrawalFeeAmount = ((stakedBal * withdrawalFee) / MAXFEE); stakedToken.safeTransfer(vault, stakedBal - withdrawalFeeAmount); } } // compounds earnings and charges performance fee function harvest() external whenNotPaused onlyEOA { _harvestInternal(); } function _harvestInternal() internal whenNotPaused { beforeHarvest(); chargeFees(); swap(); deposit(); lastHarvest = block.timestamp; emit StratHarvest(msg.sender); } function chargeFees() internal { uint256 totalFee = (strategistFee + sideProfitFee + callFee); require (totalFee < 1000, "fees too high"); uint256 toProfit = FullMath.mulDiv(rewardToken.balanceOf(address(this)), totalFee, MAXFEE); if (toProfit > 0) { IUniswapRouterETH(unirouter).swapExactTokensForTokens(toProfit, 0, rewardToProfitRoute, address(this), block.timestamp); uint256 sideProfitBalance = sideProfitToken.balanceOf(address(this)); sideProfitToken.safeTransfer(msg.sender, FullMath.mulDiv(sideProfitBalance, callFee, totalFee)); sideProfitToken.safeTransfer(strategist, FullMath.mulDiv(sideProfitBalance, strategistFee, totalFee)); sideProfitToken.safeTransfer(vault, FullMath.mulDiv(sideProfitBalance, sideProfitFee, totalFee)); } } // Adds liquidity to AMM and gets more LP tokens. function swap() internal { uint256 toStaked = IERC20(rewardToken).balanceOf(address(this)); if (toStaked > 0) { IUniswapRouterETH(unirouter).swapExactTokensForTokens(toStaked, 0, rewardToStakedRoute, address(this), block.timestamp); } } // calculate the total underlaying 'lpToken' held by the strat. function totalBalanceOfStaked() public view returns (uint256) { return balanceOfWant() + balanceOfPool(); } // it calculates how much 'lpToken' this contract holds. function balanceOfWant() public view returns (uint256) { return stakedToken.balanceOf(address(this)); } // called as part of strat migration. Sends all the available funds back to the vault. function retireStrat() external { require(msg.sender == vault, "!vault"); farmEmergencyWithdraw(); uint256 lpTokenBal = stakedToken.balanceOf(address(this)); stakedToken.transfer(vault, lpTokenBal); } /** * @dev Rescues random funds stuck that the strat can't handle. * @param _token address of the token to rescue. */ function inCaseTokensGetStuck(address _token) external onlyManager { uint256 amount = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeTransfer(msg.sender, amount); } // pauses deposits and withdraws all funds from third party systems. function panic() public onlyManager { pause(); farmEmergencyWithdraw(); } function pause() public onlyManager { _pause(); removeAllowances(); } function unpause() external onlyManager { _unpause(); giveAllowances(); deposit(); } } // File contracts/autocompounder/SS-Strategy/StrategySSMasterChef.sol pragma solidity ^0.8.0; //import "hardhat/console.sol"; contract StrategySSMasterChef is StrategySSBase { using SafeERC20 for IERC20; uint256 public poolId; IMasterChef farm; constructor( uint256 _poolId, address _farm, address _swapToken, // intermediary swap Token address _rewardToken, // rewardToken Token address _stakedToken, // staked Token address _vault, // Crack Vault that uses this strategy address _unirouter, // Unirouter on this chain to call for swaps address _keeper, // address to use as alternative owner. address _strategist, // address where strategist fees go. address _sideProfit // address of sideProfit token ) StrategySSBase( _swapToken, _rewardToken, _stakedToken, _vault, _unirouter, _keeper, _strategist, _sideProfit ) { poolId = _poolId; farm = IMasterChef(_farm); giveAllowances(); } function farmAddress() public view override(StrategySSBase) returns (address) { return address(farm); } function setFarmAddress(address newAddr) internal override(StrategySSBase) { farm = IMasterChef(newAddr); } function farmWithdraw(uint256 _amount) internal override(StrategySSBase) { farm.withdraw(poolId, _amount); } function balanceOfPool() public view override(StrategySSBase) returns (uint256) { (uint256 _amount, ) = farm.userInfo(poolId, address(this)); return _amount; } function beforeHarvest() internal override(StrategySSBase) { farm.deposit(poolId, 0); } function farmEmergencyWithdraw() internal override(StrategySSBase) { farm.emergencyWithdraw(poolId); } function farmDeposit(uint256 amount) internal whenNotPaused override(StrategySSBase) { farm.deposit(poolId, amount); } function giveAllowances() internal override(StrategySSBase) { stakedToken.safeApprove(farmAddress(), 0); stakedToken.safeApprove(farmAddress(), MAX_INT); stakedToken.safeApprove(address(unirouter), 0); stakedToken.safeApprove(address(unirouter), MAX_INT); rewardToken.safeApprove(address(unirouter), 0); rewardToken.safeApprove(address(unirouter), MAX_INT); sideProfitToken.safeApprove(address(unirouter), 0); sideProfitToken.safeApprove(address(unirouter), MAX_INT); } function removeAllowances() internal override(StrategySSBase) { stakedToken.safeApprove(farmAddress(), 0); stakedToken.safeApprove(address(unirouter), 0); rewardToken.safeApprove(address(unirouter), 0); sideProfitToken.safeApprove(address(unirouter), 0); } function resetValues(address _swapToken, address _rewardToken, address _farmAddr, address _stakedToken, uint256 _poolId, address _sideProfitToken) public onlyOwner override(StrategySSBase) { removeAllowances(); swapToken = IERC20(_swapToken); rewardToken = IERC20(_rewardToken); setFarmAddress(_farmAddr); stakedToken = IERC20(_stakedToken); sideProfitToken = IERC20(_sideProfitToken); poolId = _poolId; if (swapToken == sideProfitToken) { rewardToProfitRoute = [address(rewardToken), address(sideProfitToken)]; } else { rewardToProfitRoute = [address(rewardToken), address(swapToken), address(sideProfitToken)]; } if (swapToken == stakedToken) { rewardToStakedRoute = [address(rewardToken), address(stakedToken)]; } else { rewardToStakedRoute = [address(rewardToken), address(swapToken), address(stakedToken)]; } giveAllowances(); } }
puts the funds to work
function deposit() public whenNotPaused { uint256 stakedBal = stakedToken.balanceOf(address(this)); if (stakedBal > 0) { farmDeposit(stakedBal); } }
10,717,136
./full_match/4/0xB62652A9f4ac3D85F09dA08F31963108Dd2BfD23/sources/contracts/OptionMarketPricer.sol
Calculates vega utilisation to be used as part of the trade fee. If the trade reduces net standard vega, this component is omitted from the fee. trade The Trade. pricing The Pricing. pricingGlobals The PricingGlobals./
function getVegaUtil( IOptionMarket.Trade memory trade, Pricing memory pricing, ILyraGlobals.PricingGlobals memory pricingGlobals ) public pure override returns (uint vegaUtil) { if (abs(pricing.preTradeAmmNetStdVega) >= abs(pricing.postTradeAmmNetStdVega)) { return 0; } uint normVol = (100 * trade.vol).multiplyDecimal(abs(pricing.postTradeAmmNetStdVega)).multiplyDecimal( pricingGlobals.vegaNormFactor ); uint collatLiqPlusTotalCost = trade.isBuy ? (totalCollatLiquidity.add(trade.amount.multiplyDecimal(pricing.optionPrice))) : (totalCollatLiquidity.sub(trade.amount.multiplyDecimal(pricing.optionPrice))); vegaUtil = normVol.divideDecimal(collatLiqPlusTotalCost); }
12,434,396
./full_match/5/0x49d86c7dE01d1E8e209A5c9234A3a3C742066B76/sources/project_/contracts/Airdrop.sol
Sets the airdrop amounts for multiple recipients recipients recipients An array of recipient addresses _amounts _amounts An array of corresponding token amounts for each recipient
function setAirdrop(address[] memory recipients, uint256[] memory _amounts) public { require(msg.sender == owner, "Unauthorized"); require(recipients.length == _amounts.length, "Invalid input"); for (uint i = 0; i < recipients.length; i++) { amounts[recipients[i]] = _amounts[i]; } }
7,079,901
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // import '../Apple-swap-lib/SafeMath.sol'; import '../Apple-swap-lib/IBEP20.sol'; import '../Apple-swap-lib/BEP20.sol'; interface IWBNB { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; } contract AppleFinance is Ownable, BEP20('Apple-finance Token', 'APP'){ using SafeMath for uint256; // using SafeBEP20 for IBEP20; uint256 constant p1 = 7 days * 2 + ( 1 days); uint256 constant moonnyx = 7 days * 4 + (2 days); uint256 constant moonnyx2 = moonnyx * 2; uint256 constant moonnyx3 = moonnyx2 + moonnyx; uint256 constant moonnyx6 = moonnyx * 6; uint256 constant perennial = moonnyx * 12; // uint256 constant priceBase = 1 gwei; uint256 internal _price = 1 gwei; uint256 public investorsMapCounter; // uint256 public currentSupply; // event TokenTransfer(address from); event SeedPurchased(address indexed _buyer, uint256 _amount, uint _time); event SownSeed(address indexed _user, uint256 _amount, uint _time); event Harvest(address indexed _harvester, uint256 _amount, uint256 _date); struct Investor{ address _addr; bool isPaid; uint8 rewardBase; uint256 _token; uint harvest; bool lockGerminator; uint256 _duration; uint256 _depositDate; bool isWhiteListed; } address[] realInvestors; mapping(address => Investor) public investorsMap; mapping(uint8 => uint256) duration; mapping(uint256 => uint8) yield; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. bool inBlackList; } // Info of each pool. struct PoolInfo { // IBEP20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. APPs to distribute per block. uint256 lastRewardBlock; // Last block number that APPs distribution occurs. uint256 accAppPerShare; // Accumulated APPs per share, times 1e12. See below. } // The REWARD TOKEN IBEP20 public rewardToken; // adminAddress address public adminAddress; // WBNB address public immutable WBNB; uint256 public holdersCount; // APP tokens created per block. uint256 public rewardPerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (address => UserInfo) public userInfo; mapping(address => uint256) germinator; mapping(address => bool) public isinvestorsMaped; // limit 10 BNB here uint256 public limitAmount = 10000000000000000000; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when APP mining starts. uint256 public startBlock; // The block number when APP mining ends. uint256 public bonusEndBlock; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); event Unstaked(address indexed _addr, uint _amt); constructor( // IBEP20 _lp, IBEP20 _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _bonusEndBlock, address _wbnb, uint256 _amt ) { rewardToken = _rewardToken; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; bonusEndBlock = _bonusEndBlock; adminAddress = _msgSender(); WBNB = _wbnb; // staking pool poolInfo.push(PoolInfo({ // lpToken: _lp, allocPoint: 1000, lastRewardBlock: startBlock, accAppPerShare: 0 })); duration[1] = p1; duration[2] = moonnyx; duration[3] = moonnyx2; duration[4] = moonnyx3; duration[5] = moonnyx6; duration[6] = perennial; yield[p1] = 1; yield[moonnyx] = 3; yield[moonnyx2] = 7; yield[moonnyx3] = 10; yield[moonnyx6] = 21; yield[perennial] = 50; totalAllocPoint = 1000; _mint(address(this), _amt); balances[address(this)] = _amt; } modifier onlyAdmin() { require(_msgSender() == adminAddress, "admin: wut?"); _; } modifier iswhitelisted() { require(investorsMap[_msgSender()].isWhiteListed == true); _; } modifier hasEnoughSeedBalance(uint _qty) { require(balances[_msgSender()] >= _qty, "Insufficient balance"); _; } receive() external payable { assert(_msgSender() == WBNB); // only accept BNB via fallback from the WBNB contract } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function mint(uint256 amount) public onlyOwner returns (bool) { require(cS.add(amount) <= fxsupply, "Supply threshold is reached"); _mint(msg.sender, amount); return true; } function setYield(uint8 _duration, uint8 _newYieldVal) public onlyAdmin returns(bool) { uint256 _d = duration[_duration]; yield[_d] = _newYieldVal; return true; } // Update admin address by the previous dev. function setAdmin(address _adminAddress) public onlyOwner { adminAddress = _adminAddress; } function setBlackList(address _blacklistAddress) public onlyAdmin { userInfo[_blacklistAddress].inBlackList = true; } function removeBlackList(address _blacklistAddress) public onlyAdmin { userInfo[_blacklistAddress].inBlackList = false; } // Set the limit amount. Can only be called by the owner. function setLimitAmount(uint256 _amount) public onlyOwner { limitAmount = _amount; } // 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); } else if (_from >= bonusEndBlock) { return 0; } else { return bonusEndBlock.sub(_from); } } // View function to see pending Reward on frontend. function pendingReward(address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[_user]; uint256 accAppPerShare = pool.accAppPerShare; uint256 lpSupply = balances[address(this)]; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 appReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accAppPerShare = accAppPerShare.add(appReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accAppPerShare).div(1e12).sub(user.rewardDebt); } // 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 = balances[address(this)]; if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 appReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accAppPerShare = pool.accAppPerShare.add(appReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Stake tokens to SmartChef function deposit() public payable { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[_msgSender()]; require (user.amount.add(msg.value) <= limitAmount, 'exceed the top'); require (!user.inBlackList, 'in black list'); updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accAppPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { rewardToken.transfer(address(_msgSender()), pending); } } if(msg.value > 0) { IWBNB(WBNB).deposit{value: msg.value}(); assert(IWBNB(WBNB).transfer(address(this), msg.value)); user.amount = user.amount.add(msg.value); } user.rewardDebt = user.amount.mul(pool.accAppPerShare).div(1e12); emit Deposit(_msgSender(), msg.value); } function safeTransferBNB(address to, uint256 value) internal { (bool success, ) = to.call{gas: 23000, value: value}(""); // (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: BNB_TRANSFER_FAILED'); } // Withdraw tokens from STAKING. function withdraw(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[_msgSender()]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accAppPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0 && !user.inBlackList) { rewardToken.transfer(address(_msgSender()), pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); IWBNB(WBNB).withdraw(_amount); safeTransferBNB(address(_msgSender()), _amount); } user.rewardDebt = user.amount.mul(pool.accAppPerShare).div(1e12); emit Withdraw(_msgSender(), _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() public { // PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[_msgSender()]; payable(_msgSender()).transfer(user.amount); emit EmergencyWithdraw(_msgSender(), user.amount); user.amount = 0; user.rewardDebt = 0; } // Withdraw reward. EMERGENCY ONLY. function emergencyRewardWithdraw(uint256 _amount) public onlyOwner { require(_amount < balances[address(this)], 'not enough token'); rewardToken.transfer(address(_msgSender()), _amount); } function getWhiteisted(uint _amt) public payable returns(uint, uint, uint) { investorsMapCounter++; uint amtToSend = _amt.mul(_price); require(msg.value >= _price.mul(5000) && msg.value >= amtToSend, "Minimum buy is 500 APP"); payable(adminAddress).transfer(msg.value); investorsMap[_msgSender()]._addr = _msgSender(); investorsMap[_msgSender()].isWhiteListed = true; investorsMap[_msgSender()]._depositDate = block.timestamp; isinvestorsMaped[_msgSender()] = true; investorsMap[_msgSender()]._token = _amt; investorsMap[_msgSender()].isPaid = false; return (amtToSend, msg.value, _price); } function claimToken() external payable iswhitelisted returns(bool) { require(isinvestorsMaped[_msgSender()] == true, "Not investorsMaped"); require(investorsMap[_msgSender()].isPaid == false, "User already received token"); require(block.timestamp.add(1 days) >= investorsMap[_msgSender()]._depositDate, "Claim date not yet"); uint claim = investorsMap[_msgSender()]._token; balances[address(this)] -= claim; balances[_msgSender()] += claim; approve(address(this), claim); investorsMap[_msgSender()]._token = 0; investorsMap[_msgSender()].isWhiteListed = false; investorsMap[_msgSender()].isPaid = true; investorsMap[_msgSender()].harvest += claim; realInvestors.push(_msgSender()); holdersCount ++; emit SeedPurchased(_msgSender(), claim, block.timestamp); return true; } function stakeAPP(uint _qty, uint8 _duration) public hasEnoughSeedBalance(_qty) returns(bool) { require(_duration > 0 && _duration <= 6, "Duration out of range"); uint init_balance = balances[_msgSender()]; balances[_msgSender()] -= _qty; germinator[_msgSender()] += _qty; uint256 k = duration[_duration]; uint8 reward_base = yield[k]; investorsMap[_msgSender()].rewardBase = reward_base; investorsMap[_msgSender()]._duration = k; investorsMap[_msgSender()]._depositDate = block.timestamp; investorsMap[_msgSender()].lockGerminator = true; require(balances[_msgSender()] + _qty == init_balance, "Something went wrong"); emit SownSeed(_msgSender(), _qty, block.timestamp); return true; } function unstakeAPP() public returns(bool) { investorsMap[_msgSender()].lockGerminator = false; uint amtDue = germinator[_msgSender()].mul(investorsMap[_msgSender()].rewardBase); germinator[_msgSender()] -= amtDue; balances[_msgSender()] += amtDue; investorsMap[_msgSender()].harvest += amtDue; investorsMap[_msgSender()].rewardBase = 0; emit Unstaked(_msgSender(), amtDue); return true; } function harvest() public returns(bool, uint256) { require(germinator[_msgSender()] > 0 && (investorsMap[_msgSender()].lockGerminator = false), "User have no stake"); require(block.timestamp >= (investorsMap[_msgSender()]._depositDate + investorsMap[_msgSender()]._duration), "Root not yet mature"); uint _s = germinator[_msgSender()]; germinator[_msgSender()] -= _s; _burn(_msgSender(), _s); uint8 _reward_b = investorsMap[_msgSender()].rewardBase; uint _reward = _s * _reward_b; balances[address(this)] -= _reward; balances[_msgSender()] += _reward; investorsMap[_msgSender()].harvest = _reward; emit Harvest(_msgSender(), _reward, block.timestamp); return (true, _reward); } function setPriceBase(uint256 _newPriceBase) public onlyAdmin returns(bool) { _price = _newPriceBase; return true; } function getContractBalance() external view onlyAdmin returns(uint) { return balances[address(this)]; } function checkStakedBalance() public view returns(uint) { return germinator[_msgSender()]; } }
Withdraw tokens from STAKING.
function withdraw(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[_msgSender()]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accAppPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0 && !user.inBlackList) { rewardToken.transfer(address(_msgSender()), pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); IWBNB(WBNB).withdraw(_amount); safeTransferBNB(address(_msgSender()), _amount); } user.rewardDebt = user.amount.mul(pool.accAppPerShare).div(1e12); emit Withdraw(_msgSender(), _amount); }
13,062,421
./partial_match/3/0x7dfcAd83cd93E309338705dca079add3A4bD72DC/sources/Nexon.sol
Function to Set the price of each token for ETH purchase/
function setPriceToken(uint256 tokenPriceETH) external onlyOwner returns (bool){ require(tokenPriceETH >0,"Invalid Amount"); _tokenPriceETH = tokenPriceETH; return(true); }
5,068,679
// SPDX-License-Identifier: MIT pragma solidity >=0.7.2; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import { SafeMath } from '@openzeppelin/contracts/math/SafeMath.sol'; import { IERC20 } from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import { SafeERC20 } from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import { IAction } from '../interfaces/IAction.sol'; import "hardhat/console.sol"; /** * Error Codes * O1: actions for the vault have not been initialized * O2: cannot execute transaction, vault is in emergency state * O3: cannot call setActions, actions have already been initialized * O4: action being set is using an invalid address * O5: action being set is a duplicated action * O6: deposited underlying (msg.value) must be greater than 0 * O7: cannot accept underlying deposit, total underlying controlled by the vault would exceed vault cap * O8: unable to withdraw underlying, underlying to withdraw would exceed or be equal to the current vault underlying balance * O9: unable to withdraw underlying, underlying fee transfer to fee recipient (feeRecipient) failed * O10: unable to withdraw underlying, underlying withdrawal to user (msg.sender) failed * O11: cannot close vault positions, vault is not in locked state (VaultState.Locked) * O12: unable to rollover vault, length of allocation percentages (_allocationPercentages) passed is not equal to the initialized actions length * O13: unable to rollover vault, vault is not in unlocked state (VaultState.Unlocked) * O14: unable to rollover vault, the calculated percentage sum (sumPercentage) is greater than the base (BASE) * O15: unable to rollover vault, the calculated percentage sum (sumPercentage) is not equal to the base (BASE) * O16: withdraw reserve percentage must be less than 50% (5000) * O17: cannot call emergencyPause, vault is already in emergency state * O18: cannot call resumeFromPause, vault is not in emergency state * O19: cannot accept underlying deposit, accounting before and after deposit does not match * O20: unable to withdraw underlying, accounting before and after withdrawal does not match */ /** * @title OpynPerpVault * @author Opyn Team * @dev implementation of the Opyn Perp Vault contract for covered calls using as collateral the underlying. */ contract OpynPerpVault is ERC20, ReentrancyGuard, Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; enum VaultState { Emergency, Locked, Unlocked } /// @dev actions that build up this strategy (vault) address[] public actions; /// @dev address to which all withdrawal fees are sent address public feeWithdrawalRecipient; /// @dev address to which all performance fees are sent address public feePerformanceRecipient; /// @dev address of the underlying address address public underlying; uint256 public constant BASE = 10000; // 100% /// @dev Cap for the vault. hardcoded at 1000 for initial release uint256 public cap = 1000 ether; /// @dev withdrawal fee percentage. 50 being 0.5% uint256 public withdrawalFeePercentage = 50; /// @dev what percentage should be reserved in vault for withdraw. 1000 being 10% uint256 public withdrawReserve = 0; /// @dev performance fee percentage. 1000 being 10% uint256 public performanceFeePercentage = 1000; VaultState public state; VaultState public stateBeforePause; /*===================== * Events * *====================*/ event CapUpdated(uint256 newCap); event Deposit(address account, uint256 amountDeposited, uint256 shareMinted); event Rollover(uint256[] allocations); event StateUpdated(VaultState state); event FeeSent(uint256 amount, address feeRecipient); event Withdraw(address account, uint256 amountWithdrawn, uint256 shareBurned); /*===================== * Modifiers * *====================*/ /** * @dev can only be called if actions are initialized */ function actionsInitialized() private view { require(actions.length > 0, "O1"); } /** * @dev can only be executed if vault is not in emergency state */ function notEmergency() private view { require(state != VaultState.Emergency, "O2"); } /*===================== * external function * *====================*/ constructor ( address _underlying, address _feeWithdrawalRecipient, address _feePerformanceRecipient, string memory _tokenName, string memory _tokenSymbol ) ERC20(_tokenName, _tokenSymbol) { underlying = _underlying; feeWithdrawalRecipient = _feeWithdrawalRecipient; feePerformanceRecipient = _feePerformanceRecipient; state = VaultState.Unlocked; } function setActions(address[] memory _actions) external onlyOwner { require(actions.length == 0, "O3"); // assign actions for(uint256 i = 0 ; i < _actions.length; i++ ) { // check all items before actions[i], does not equal to action[i] require(_actions[i] != address(0), "O4"); for(uint256 j = 0; j < i; j++) { require(_actions[i] != _actions[j], "O5"); } actions.push(_actions[i]); } } /** * @notice allows owner to change the cap */ function setCap(uint256 _newCap) external onlyOwner { cap = _newCap; emit CapUpdated(_newCap); } /** * @notice total underlying controlled by this vault */ function totalUnderlyingAsset() public view returns (uint256) { uint256 debt = 0; uint256 length = actions.length; for (uint256 i = 0; i < length; i++) { debt = debt.add(IAction(actions[i]).currentValue()); } return _balance().add(debt); } /** * @dev return how much underlying you can get if you burn the number of shares, after charging the withdrawal fee. */ function getWithdrawAmountByShares(uint256 _shares) external view returns (uint256) { uint256 withdrawAmount = _getWithdrawAmountByShares(_shares); return withdrawAmount.sub(_getWithdrawFee(withdrawAmount)); } /** * @notice deposits underlying into the contract and mints vault shares. * @dev deposit into the contract, then mint the shares to depositor, and emit the deposit event * @param amount amount of underlying to deposit */ function depositUnderlying(uint256 amount) external nonReentrant { notEmergency(); actionsInitialized(); require(amount > 0, 'O6'); // keep track of underlying balance before uint256 totalUnderlyingBeforeDeposit = totalUnderlyingAsset(); // deposit underlying to vault IERC20 underlyingToken = IERC20(underlying); underlyingToken.safeTransferFrom(msg.sender, address(this), amount); // keep track of underlying balance after uint256 totalUnderlyingAfterDeposit = totalUnderlyingAsset(); require(totalUnderlyingAfterDeposit < cap, 'O7'); require(totalUnderlyingAfterDeposit.sub(totalUnderlyingBeforeDeposit) == amount, 'O19'); // mint shares and emit event uint256 share = _getSharesByDepositAmount(amount, totalUnderlyingBeforeDeposit); emit Deposit(msg.sender, amount, share); _mint(msg.sender, share); } /** * @notice withdraws underlying from vault using vault shares * @dev burns shares, sends underlying to user, sends withdrawal fee to withdrawal fee recepient * @param _share is the number of vault shares to be burned */ function withdrawUnderlying(uint256 _share) external nonReentrant { notEmergency(); actionsInitialized(); // keep track of underlying balance before IERC20 underlyingToken = IERC20(underlying); uint256 totalUnderlyingBeforeWithdrawal = totalUnderlyingAsset(); // withdraw underlying from vault uint256 underlyingToRecipientBeforeFees = _getWithdrawAmountByShares(_share); uint256 fee = _getWithdrawFee(underlyingToRecipientBeforeFees); uint256 underlyingToRecipientAfterFees = underlyingToRecipientBeforeFees.sub(fee); require(underlyingToRecipientBeforeFees <= _balance(), 'O8'); // burn shares _burn(msg.sender, _share); // transfer withdrawal fee to recipient underlyingToken.safeTransfer(feeWithdrawalRecipient, fee); emit FeeSent(fee, feeWithdrawalRecipient); // send underlying to user underlyingToken.safeTransfer(msg.sender, underlyingToRecipientAfterFees); // keep track of underlying balance after uint256 totalUnderlyingAfterWithdrawal = totalUnderlyingAsset(); require(totalUnderlyingBeforeWithdrawal.sub(totalUnderlyingAfterWithdrawal) == underlyingToRecipientBeforeFees, 'O20'); emit Withdraw(msg.sender, underlyingToRecipientAfterFees, _share); } /** * @notice anyone can call this to close out the previous round by calling "closePositions" on all actions. * @notice can only be called when the vault is locked. It sets the state to unlocked and brings funds from each action to the vault. * @dev iterrate through each action, close position and withdraw funds */ function closePositions() public { actionsInitialized(); require(state == VaultState.Locked, "O11"); state = VaultState.Unlocked; address cacheAddress = underlying; address[] memory cacheActions = actions; for (uint256 i = 0; i < cacheActions.length; i = i + 1) { // asset amount used in minting options for cycle uint256 lockedAsset = IAction(cacheActions[i]).currentLockedAsset(); // 1. close position. this should revert if any position is not ready to be closed. IAction(cacheActions[i]).closePosition(); // 2. withdraw underlying from the action uint256 actionBalance = IERC20(cacheAddress).balanceOf(cacheActions[i]); uint256 netActionBalance; if (actionBalance > 0){ netActionBalance = actionBalance; // check if performance fee applies and strategy was profitable if(performanceFeePercentage > 0 && actionBalance > lockedAsset){ // get profit uint256 profit = actionBalance.sub(lockedAsset); uint256 performanceFee = _getPerformanceFee(profit); // transfer performance fee IERC20(cacheAddress).safeTransferFrom(cacheActions[i], feePerformanceRecipient, performanceFee); emit FeeSent(performanceFee, feePerformanceRecipient); // update action net balance netActionBalance = actionBalance.sub(performanceFee); } // underlying back to vault IERC20(cacheAddress).safeTransferFrom(cacheActions[i], address(this), netActionBalance); } } emit StateUpdated(VaultState.Unlocked); } /** * @notice can only be called when the vault is unlocked. It sets the state to locked and distributes funds to each action. */ function rollOver(uint256[] calldata _allocationPercentages) external onlyOwner nonReentrant { actionsInitialized(); require(_allocationPercentages.length == actions.length, 'O12'); require(state == VaultState.Unlocked, "O13"); state = VaultState.Locked; address cacheAddress = underlying; address[] memory cacheActions = actions; uint256 cacheBase = BASE; uint256 cacheTotalAsset = totalUnderlyingAsset(); // keep track of total percentage to make sure we're summing up to 100% uint256 sumPercentage = withdrawReserve; for (uint256 i = 0; i < _allocationPercentages.length; i = i + 1) { sumPercentage = sumPercentage.add(_allocationPercentages[i]); require(sumPercentage <= cacheBase, 'O14'); uint256 newAmount = cacheTotalAsset.mul(_allocationPercentages[i]).div(cacheBase); if (newAmount > 0) IERC20(cacheAddress).safeTransfer(cacheActions[i], newAmount); IAction(cacheActions[i]).rolloverPosition(); } require(sumPercentage == cacheBase, 'O15'); emit Rollover(_allocationPercentages); emit StateUpdated(VaultState.Locked); } /** * @dev set the vault withdrawal fee recipient */ function setWithdrawalFeeRecipient(address _newWithdrawalFeeRecipient) external onlyOwner { feeWithdrawalRecipient = _newWithdrawalFeeRecipient; } /** * @dev set the vault performance fee recipient */ function setPerformanceFeeRecipient(address _newPerformanceFeeRecipient) external onlyOwner { feePerformanceRecipient = _newPerformanceFeeRecipient; } /** * @dev set the vault fee recipient - use when performance fee and withdrawal fee is sent to the same recipient */ function setFeeRecipient(address _newFeeRecipient) external onlyOwner { feeWithdrawalRecipient = _newFeeRecipient; feePerformanceRecipient = _newFeeRecipient; } /** * @dev set the percentage fee that should be applied upon withdrawal */ function setWithdrawalFeePercentage(uint256 _newWithdrawalFeePercentage) external onlyOwner { withdrawalFeePercentage = _newWithdrawalFeePercentage; } /** * @dev set the percentage fee that should be applied on profits at the end of cycles */ function setPerformanceFeePercentage(uint256 _newPerformanceFeePercentage) external onlyOwner { performanceFeePercentage = _newPerformanceFeePercentage; } /** * @dev set the percentage that should be reserved in vault for withdraw */ function setWithdrawReserve(uint256 _reserve) external onlyOwner { require(_reserve < 5000, "O16"); withdrawReserve = _reserve; } /** * @dev set the state to "Emergency", which disable all withdraw and deposit */ function emergencyPause() external onlyOwner { require(state != VaultState.Emergency, "O17"); stateBeforePause = state; state = VaultState.Emergency; emit StateUpdated(VaultState.Emergency); } /** * @dev set the state from "Emergency", which disable all withdraw and deposit */ function resumeFromPause() external onlyOwner { require(state == VaultState.Emergency, "O18"); state = stateBeforePause; emit StateUpdated(stateBeforePause); } /** * @dev return how many shares you can get if you deposit {_amount} underlying * @param _amount amount of token depositing */ function getSharesByDepositAmount(uint256 _amount) external view returns (uint256) { return _getSharesByDepositAmount(_amount, totalUnderlyingAsset()); } /*===================== * Internal functions * *====================*/ /** * @dev returns remaining underlying balance in the vault. */ function _balance() internal view returns (uint256) { return IERC20(underlying).balanceOf(address(this)); } /** * @dev return how many shares you can get if you deposit {_amount} underlying * @param _amount amount of underlying depositing * @param _totalAssetAmount amount of underlying already in the pool before deposit */ function _getSharesByDepositAmount(uint256 _amount, uint256 _totalAssetAmount) internal view returns (uint256) { uint256 shareSupply = totalSupply(); // share amount return shareSupply == 0 ? _amount : _amount.mul(shareSupply).div(_totalAssetAmount); } /** * @dev return how much underlying you can get if you burn the number of shares */ function _getWithdrawAmountByShares(uint256 _share) internal view returns (uint256) { // withdrawal amount return _share.mul(totalUnderlyingAsset()).div(totalSupply()); } /** * @dev get amount of fee charged based on total amount of underlying withdrawing. */ function _getWithdrawFee(uint256 _withdrawAmount) internal view returns (uint256) { return _withdrawAmount.mul(withdrawalFeePercentage).div(BASE); } /** * @dev get amount of fee charged based on total profit amount earned in a cycle. */ function _getPerformanceFee(uint256 _profitAmount) internal view returns (uint256) { return _profitAmount.mul(performanceFeePercentage).div(BASE); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; 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 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.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; /** * @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.7.2; interface IAction { /** * The function used to determin how much asset the current action is controlling. * this will impact the withdraw and deposit amount calculated from the vault. */ function currentValue() external view returns (uint256); /** * The function for the vault to call at the end of each vault's round. * after calling this function, the vault will try to pull assets back from the action and enable withdraw. */ function closePosition() external; /** * The function for the vault to call when the vault is ready to start the next round. * the vault will push assets to action before calling this function, but the amount can change compare to * the last round. So each action should check their asset balance instead of using any cached balance. * * Each action can also add additional checks and revert the `rolloverPosition` call if the action * is not ready to go into the next round. */ function rolloverPosition() external; /** * The function used to determine how much asset is locked in the current action. * this will impact the closeposition amount calculated from the vault. */ function currentLockedAsset() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
===================== Internal functions ====================/ returns remaining underlying balance in the vault./
function _balance() internal view returns (uint256) { return IERC20(underlying).balanceOf(address(this)); }
1,583,018
pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./IExternalStake.sol"; contract SDAOBondedTokenStake is IExternalStake, Ownable, ReentrancyGuard{ using SafeMath for uint256; ERC20 public token; // Address of token contract and same used for rewards ERC20 public bonusToken; // Address of bonus token contract struct StakeInfo { bool exist; uint256 amount; uint256 rewardComputeIndex; uint256 bonusAmount; } // Staking period timestamp (Debatable on timestamp vs blocknumber - went with timestamp) struct StakePeriod { uint256 startPeriod; uint256 submissionEndPeriod; uint256 endPeriod; uint256 maxStake; uint256 windowRewardAmount; uint256 windowMaxAmount; } address public tokenOperator; // Address to manage the Stake uint256 public maxAirDropStakeBlocks; // Block numbers to complete the airDrop Auto Stakes mapping (address => uint256) public balances; // Useer Token balance in the contract uint256 public currentStakeMapIndex; // Current Stake Index to avoid math calc in all methods mapping (uint256 => StakePeriod) public stakeMap; // List of Stake Holders address[] stakeHolders; // All Stake Holders mapping(address => StakeInfo) stakeHolderInfo; // To store the total stake in a window uint256 public windowTotalStake; // Events event NewOperator(address tokenOperator); event WithdrawToken(address indexed tokenOperator, uint256 amount); event OpenForStake(uint256 indexed stakeIndex, address indexed tokenOperator, uint256 startPeriod, uint256 endPeriod, uint256 rewardAmount); event SubmitStake(uint256 indexed stakeIndex, address indexed staker, uint256 stakeAmount); event WithdrawStake(uint256 indexed stakeIndex, address indexed staker, uint256 stakeAmount, uint256 bonusAmount); event ClaimStake(uint256 indexed stakeIndex, address indexed staker, uint256 totalAmount, uint256 bonusAmount); event AddReward(address indexed staker, uint256 indexed stakeIndex, address tokenOperator, uint256 stakeAmount, uint256 rewardAmount, uint256 windowTotalStake); // Modifiers modifier onlyOperator() { require( msg.sender == tokenOperator, "Only operator can call this function." ); _; } // Token Operator should be able to do auto renewal modifier allowSubmission() { require( now >= stakeMap[currentStakeMapIndex].startPeriod && now <= stakeMap[currentStakeMapIndex].submissionEndPeriod, "Staking at this point not allowed" ); _; } modifier validStakeLimit(address staker, uint256 stakeAmount) { uint256 stakerTotalStake; stakerTotalStake = stakeAmount.add(stakeHolderInfo[staker].amount); // Check for Max Stake per Wallet and stake window max limit require( stakeAmount > 0 && stakerTotalStake <= stakeMap[currentStakeMapIndex].maxStake && windowTotalStake.add(stakeAmount) <= stakeMap[currentStakeMapIndex].windowMaxAmount, "Exceeding max limits" ); _; } // Check for claim - Stake Window should be either in submission phase or after end period modifier allowClaimStake() { require( (now >= stakeMap[currentStakeMapIndex].startPeriod && now <= stakeMap[currentStakeMapIndex].submissionEndPeriod && stakeHolderInfo[msg.sender].amount > 0) || (now > stakeMap[currentStakeMapIndex].endPeriod && stakeHolderInfo[msg.sender].amount > 0), "Invalid claim request"); _; } constructor(address _token, uint256 _maxAirDropStakeBlocks) public { token = ERC20(_token); tokenOperator = msg.sender; currentStakeMapIndex = 0; windowTotalStake = 0; maxAirDropStakeBlocks = _maxAirDropStakeBlocks.add(block.number); } function updateOperator(address newOperator) external onlyOwner { require(newOperator != address(0), "Invalid operator address"); tokenOperator = newOperator; emit NewOperator(newOperator); } function withdrawToken(uint256 value) external onlyOperator { // Check if contract is having required balance require(token.balanceOf(address(this)) >= value, "Not enough balance in the contract"); require(token.transfer(msg.sender, value), "Unable to transfer token to the operator account"); emit WithdrawToken(tokenOperator, value); } // To set the bonus token for future needs function setBonusToken(address _bonusToken) external onlyOwner { require(_bonusToken != address(0), "Invalid bonus token"); bonusToken = ERC20(_bonusToken); } function openForStake(uint256 _startPeriod, uint256 _submissionEndPeriod, uint256 _endPeriod, uint256 _windowRewardAmount, uint256 _maxStake, uint256 _windowMaxAmount) external onlyOperator { // Check Input Parameters require(_startPeriod >= now && _startPeriod < _submissionEndPeriod && _submissionEndPeriod < _endPeriod, "Invalid stake period"); require(_windowRewardAmount > 0 && _maxStake > 0 && _windowMaxAmount > 0, "Invalid inputs" ); // Check Stake in Progress require(currentStakeMapIndex == 0 || (now > stakeMap[currentStakeMapIndex].submissionEndPeriod && _startPeriod >= stakeMap[currentStakeMapIndex].endPeriod), "Cannot have more than one stake request at a time"); // Move the staking period to next one currentStakeMapIndex = currentStakeMapIndex + 1; StakePeriod memory stakePeriod; // Set Staking attributes stakePeriod.startPeriod = _startPeriod; stakePeriod.submissionEndPeriod = _submissionEndPeriod; stakePeriod.endPeriod = _endPeriod; stakePeriod.windowRewardAmount = _windowRewardAmount; stakePeriod.maxStake = _maxStake; stakePeriod.windowMaxAmount = _windowMaxAmount; stakeMap[currentStakeMapIndex] = stakePeriod; // Add the current window reward to the window total stake windowTotalStake = windowTotalStake.add(_windowRewardAmount); emit OpenForStake(currentStakeMapIndex, msg.sender, _startPeriod, _endPeriod, _windowRewardAmount); } // To add the Stake Holder function _createStake(address staker, uint256 stakeAmount) internal returns(bool) { StakeInfo storage stakeInfo = stakeHolderInfo[staker]; // Check if the user already staked in the past if(stakeInfo.exist) { stakeInfo.amount = stakeInfo.amount.add(stakeAmount); } else { StakeInfo memory req; // Create a new stake request req.exist = true; req.amount = stakeAmount; req.rewardComputeIndex = 0; // Add to the Stake Holders List stakeHolderInfo[staker] = req; // Add to the Stake Holders List stakeHolders.push(staker); } return true; } // To submit a new stake for the current window - This function left as is for backward compatability with existing DApps function submitStake(uint256 stakeAmount) external allowSubmission validStakeLimit(msg.sender, stakeAmount) { // Transfer the Tokens to Contract require(token.transferFrom(msg.sender, address(this), stakeAmount), "Unable to transfer token to the contract"); _createStake(msg.sender, stakeAmount); // Update the User balance balances[msg.sender] = balances[msg.sender].add(stakeAmount); // Update current stake period total stake - For Auto Approvals windowTotalStake = windowTotalStake.add(stakeAmount); emit SubmitStake(currentStakeMapIndex, msg.sender, stakeAmount); } // To Submit a new stakeFor in the current window - Can be called from the other contracts like airdrop function submitStakeFor(address staker, uint256 stakeAmount) external virtual override allowSubmission validStakeLimit(staker, stakeAmount) nonReentrant returns(bool) { // Check for the stakerFor Address require(staker != address(0), "Invalid staker"); // Transfer the Tokens to Contract require(token.transferFrom(msg.sender, address(this), stakeAmount), "Unable to transfer token to the contract"); _createStake(staker, stakeAmount); // Update the User balance balances[staker] = balances[staker].add(stakeAmount); // Update current stake period total stake - For Auto Approvals windowTotalStake = windowTotalStake.add(stakeAmount); emit SubmitStake(currentStakeMapIndex, staker, stakeAmount); return true; } // To withdraw stake during submission phase function withdrawStake(uint256 stakeAmount) external allowClaimStake nonReentrant{ //require( // (now >= stakeMap[stakeMapIndex].startPeriod && now <= stakeMap[stakeMapIndex].submissionEndPeriod), // "Stake withdraw at this point is not allowed" //); StakeInfo storage stakeInfo = stakeHolderInfo[msg.sender]; // Validate the input Stake Amount require(stakeAmount > 0 && stakeInfo.amount >= stakeAmount, "Cannot withdraw beyond stake amount"); uint256 bonusAmount; // Update the staker balance in the staking window stakeInfo.amount = stakeInfo.amount.sub(stakeAmount); bonusAmount = stakeInfo.bonusAmount; stakeInfo.bonusAmount = 0; // Update the User balance balances[msg.sender] = balances[msg.sender].sub(stakeAmount); // Update current stake period total stake - For Auto Approvals windowTotalStake = windowTotalStake.sub(stakeAmount); // Return to User Wallet require(token.transfer(msg.sender, stakeAmount), "Unable to transfer token to the account"); // Call the bonus transfer function - Should transfer only if set if(address(bonusToken) != address(0) && bonusAmount > 0) { require(bonusToken.transfer(msg.sender, bonusAmount), "Unable to transfer bonus token to the account"); } emit WithdrawStake(currentStakeMapIndex, msg.sender, stakeAmount, bonusAmount); } // To claim from the stake window function claimStake() external allowClaimStake nonReentrant{ StakeInfo storage stakeInfo = stakeHolderInfo[msg.sender]; uint256 stakeAmount; uint256 bonusAmount; // No more stake windows or in submission phase stakeAmount = stakeInfo.amount; bonusAmount = stakeInfo.bonusAmount; stakeInfo.amount = 0; stakeInfo.bonusAmount = 0; // Update current stake period total stake windowTotalStake = windowTotalStake.sub(stakeAmount); // Check for balance in the contract require(token.balanceOf(address(this)) >= stakeAmount, "Not enough balance in the contract"); // Update the User Balance balances[msg.sender] = balances[msg.sender].sub(stakeAmount); // Call the transfer function require(token.transfer(msg.sender, stakeAmount), "Unable to transfer token back to the account"); // Call the bonus transfer function - Should transfer only if set if(address(bonusToken) != address(0) && bonusAmount > 0) { require(bonusToken.transfer(msg.sender, bonusAmount), "Unable to transfer bonus token to the account"); } emit ClaimStake(currentStakeMapIndex, msg.sender, stakeAmount, bonusAmount); } function _calculateRewardAmount(uint256 stakeMapIndex, uint256 stakeAmount) internal view returns(uint256) { uint256 calcRewardAmount; if(windowTotalStake > stakeMap[stakeMapIndex].windowRewardAmount) { calcRewardAmount = stakeAmount.mul(stakeMap[stakeMapIndex].windowRewardAmount).div(windowTotalStake.sub(stakeMap[stakeMapIndex].windowRewardAmount)); } return calcRewardAmount; } // Update reward for staker in the respective stake window function computeAndAddReward(uint256 stakeMapIndex, address staker, uint256 stakeBonusAmount) public onlyOperator returns(bool) { // Check for the Incubation Period require( now > stakeMap[stakeMapIndex].submissionEndPeriod && now < stakeMap[stakeMapIndex].endPeriod, "Reward cannot be added now" ); StakeInfo storage stakeInfo = stakeHolderInfo[staker]; // Check if reward already computed require(stakeInfo.amount > 0 && stakeInfo.rewardComputeIndex != stakeMapIndex, "Invalid reward request"); // Calculate the totalAmount uint256 totalAmount; uint256 rewardAmount; // Calculate the reward amount for the current window totalAmount = stakeInfo.amount; rewardAmount = _calculateRewardAmount(stakeMapIndex, totalAmount); totalAmount = totalAmount.add(rewardAmount); // Add the reward amount stakeInfo.amount = totalAmount; // Add the bonus Amount stakeInfo.bonusAmount = stakeInfo.bonusAmount.add(stakeBonusAmount); // Update the reward compute index to avoid mulitple addition stakeInfo.rewardComputeIndex = stakeMapIndex; // Update the User Balance balances[staker] = balances[staker].add(rewardAmount); emit AddReward(staker, stakeMapIndex, tokenOperator, totalAmount, rewardAmount, windowTotalStake); return true; } function updateRewards(uint256 stakeMapIndex, address[] calldata staker, uint256 stakeBonusAmount) external onlyOperator { for(uint256 indx = 0; indx < staker.length; indx++) { require(computeAndAddReward(stakeMapIndex, staker[indx], stakeBonusAmount)); } } // AirDrop to Stake - Load existing stakes from Air Drop function airDropStakes(uint256 stakeMapIndex, address[] calldata staker, uint256[] calldata stakeAmount) external onlyOperator { // Add check for Block Number to restrict air drop auto stake phase after certain block number require(block.number < maxAirDropStakeBlocks, "Exceeds airdrop auto stake phase"); // Check Input Parameters require(staker.length == stakeAmount.length, "Invalid Input Arrays"); // Stakers should be for current window require(currentStakeMapIndex == stakeMapIndex, "Invalid Stake Window Index"); for(uint256 indx = 0; indx < staker.length; indx++) { StakeInfo memory req; // Create a stake request with amount req.exist = true; req.amount = stakeAmount[indx]; req.rewardComputeIndex = 0; // Add to the Stake Holders List stakeHolderInfo[staker[indx]] = req; // Add to the Stake Holders List stakeHolders.push(staker[indx]); // Update the User balance balances[staker[indx]] = stakeAmount[indx]; // Update current stake period total stake - Along with Reward windowTotalStake = windowTotalStake.add(stakeAmount[indx]); } } // Getter Functions function getStakeHolders() external view returns(address[] memory) { return stakeHolders; } function getStakeInfo(address staker) external view returns (bool found, uint256 amount, uint256 rewardComputeIndex, uint256 bonusAmount) { StakeInfo memory stakeInfo = stakeHolderInfo[staker]; found = false; if(stakeInfo.exist) { found = true; } amount = stakeInfo.amount; rewardComputeIndex = stakeInfo.rewardComputeIndex; bonusAmount = stakeInfo.bonusAmount; } }
Check Input Parameters Check Stake in Progress Move the staking period to next one Set Staking attributes Add the current window reward to the window total stake
function openForStake(uint256 _startPeriod, uint256 _submissionEndPeriod, uint256 _endPeriod, uint256 _windowRewardAmount, uint256 _maxStake, uint256 _windowMaxAmount) external onlyOperator { require(_startPeriod >= now && _startPeriod < _submissionEndPeriod && _submissionEndPeriod < _endPeriod, "Invalid stake period"); require(_windowRewardAmount > 0 && _maxStake > 0 && _windowMaxAmount > 0, "Invalid inputs" ); require(currentStakeMapIndex == 0 || (now > stakeMap[currentStakeMapIndex].submissionEndPeriod && _startPeriod >= stakeMap[currentStakeMapIndex].endPeriod), "Cannot have more than one stake request at a time"); currentStakeMapIndex = currentStakeMapIndex + 1; StakePeriod memory stakePeriod; stakePeriod.startPeriod = _startPeriod; stakePeriod.submissionEndPeriod = _submissionEndPeriod; stakePeriod.endPeriod = _endPeriod; stakePeriod.windowRewardAmount = _windowRewardAmount; stakePeriod.maxStake = _maxStake; stakePeriod.windowMaxAmount = _windowMaxAmount; stakeMap[currentStakeMapIndex] = stakePeriod; windowTotalStake = windowTotalStake.add(_windowRewardAmount); emit OpenForStake(currentStakeMapIndex, msg.sender, _startPeriod, _endPeriod, _windowRewardAmount); }
12,543,186
pragma solidity 0.6.6; interface UniswapPairContract { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); } interface xETHTokenInterface { //Public functions function maxScalingFactor() external view returns (uint256); function xETHScalingFactor() external view returns (uint256); //rebase permissioned function setTxFee(uint16 fee) external ; function setSellFee(uint16 fee) external ; function rebase(uint256 epoch, uint256 indexDelta, bool positive) external returns (uint256); } contract xETHRebaser { using SafeMath for uint256; modifier onlyGov() { require(msg.sender == gov); _; } /// @notice an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); /// @notice Governance address address public gov; /// @notice Spreads out getting to the target price uint256 public rebaseLag; /// @notice Peg target uint256 public targetRate; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. uint256 public deviationThreshold; /// @notice More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec; /// @notice Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; /// @notice The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec; /// @notice The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec; /// @notice The number of rebase cycles since inception uint256 public epoch; // rebasing is not active initially. It can be activated at T+12 hours from // deployment time ///@notice boolean showing rebase activation status bool public rebasingActive; /// @notice delays rebasing activation to facilitate liquidity uint256 public constant rebaseDelay = 0; address public xETHAddress; address public uniswap_xeth_eth_pair; mapping(address => bool) public whitelistFrom; constructor( address xETHAddress_, address xEthEthPair_ ) public { minRebaseTimeIntervalSec = 1 days; rebaseWindowOffsetSec = 0; // 00:00 UTC rebases // 0.01 ETH targetRate = 10**18; // daily rebase, with targeting reaching peg in 5 days rebaseLag = 10; // 5% deviationThreshold = 5 * 10**15; // 3 hours rebaseWindowLengthSec = 24 hours; uniswap_xeth_eth_pair = xEthEthPair_; xETHAddress = xETHAddress_; gov = msg.sender; } function setWhitelistedFrom(address _addr, bool _whitelisted) external onlyGov { whitelistFrom[_addr] = _whitelisted; } function _isWhitelisted(address _from) internal view returns (bool) { return whitelistFrom[_from]; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is 1e18 */ function rebase() public { // EOA only require(msg.sender == tx.origin); require(_isWhitelisted(msg.sender)); // ensure rebasing at correct time _inRebaseWindow(); require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now); // Snap the rebase time to the start of this window. lastRebaseTimestampSec = now; epoch = epoch.add(1); // get price from uniswap v2; uint256 exchangeRate = getPrice(); // calculates % change to supply (uint256 offPegPerc, bool positive) = computeOffPegPerc(exchangeRate); uint256 indexDelta = offPegPerc; // Apply the Dampening factor. indexDelta = indexDelta.div(rebaseLag); xETHTokenInterface xETH = xETHTokenInterface(xETHAddress); if (positive) { require(xETH.xETHScalingFactor().mul(uint256(10**18).add(indexDelta)).div(10**18) < xETH.maxScalingFactor(), "new scaling factor will be too big"); } // rebase xETH.rebase(epoch, indexDelta, positive); assert(xETH.xETHScalingFactor() <= xETH.maxScalingFactor()); } function getPrice() public view returns (uint256) { (uint xethReserve, uint ethReserve, ) = UniswapPairContract(uniswap_xeth_eth_pair).getReserves(); uint xEthPrice = ethReserve.mul(10**18).div(xethReserve); return xEthPrice; } function setDeviationThreshold(uint256 deviationThreshold_) external onlyGov { require(deviationThreshold > 0); uint256 oldDeviationThreshold = deviationThreshold; deviationThreshold = deviationThreshold_; emit NewDeviationThreshold(oldDeviationThreshold, deviationThreshold_); } /** * @notice Sets the rebase lag parameter. It is used to dampen the applied supply adjustment by 1 / rebaseLag If the rebase lag R, equals 1, the smallest value for R, then the full supply correction is applied on each rebase cycle. If it is greater than 1, then a correction of 1/R of is applied on each rebase. * @param rebaseLag_ The new rebase lag parameter. */ function setRebaseLag(uint256 rebaseLag_) external onlyGov { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; } /** * @notice Sets the targetRate parameter. * @param targetRate_ The new target rate parameter. */ function setTargetRate(uint256 targetRate_) external onlyGov { require(targetRate_ > 0); targetRate = targetRate_; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase * operations, in seconds. * @param rebaseWindowOffsetSec_ The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param rebaseWindowLengthSec_ The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 minRebaseTimeIntervalSec_, uint256 rebaseWindowOffsetSec_, uint256 rebaseWindowLengthSec_) external onlyGov { require(minRebaseTimeIntervalSec_ > 0); require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_); minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; rebaseWindowOffsetSec = rebaseWindowOffsetSec_; rebaseWindowLengthSec = rebaseWindowLengthSec_; } /** * @return If the latest block timestamp is within the rebase time window it, returns true. * Otherwise, returns false. */ function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market _inRebaseWindow(); return true; } function _inRebaseWindow() internal view { require(now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, "too early"); require(now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), "too late"); } /** * @return Computes in % how far off market is from peg */ function computeOffPegPerc(uint256 rate) private view returns (uint256, bool) { if (withinDeviationThreshold(rate)) { return (0, false); } // indexDelta = (rate - targetRate) / targetRate if (rate > targetRate) { return (rate.sub(targetRate).mul(10**18).div(targetRate), true); } else { return (targetRate.sub(rate).mul(10**18).div(targetRate), false); } } /** * @param rate The current exchange rate, an 18 decimal fixed point number. * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate) private view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** 18); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } 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; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function ceil(uint256 a, uint256 m) internal pure returns (uint256) { uint256 c = add(a,m); uint256 d = sub(c,1); return mul(div(d,m),m); } /** * @dev 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; } function divRound(uint256 x, uint256 y) internal pure returns (uint256) { require(y != 0, "Div by zero"); uint256 r = x / y; if (x % y != 0) { r = r + 1; } return r; } }
rebaseLag_ The new rebase lag parameter./
function setRebaseLag(uint256 rebaseLag_) external onlyGov { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; }
2,338,996
./partial_match/4/0x6DA78f115dC013357Da953eB8b4cAba45ef777cC/sources/ATMSettings.sol
Constants / State Variables /// Constructor / External Functions //
function pauseATM(address atmAddress) external onlyPauser() isInitialized() { require(!_getSettings().isPaused(), "PLATFORM_IS_ALREADY_PAUSED"); require(!atmPaused[atmAddress], "ATM_IS_ALREADY_PAUSED"); atmPaused[atmAddress] = true; emit ATMPaused(atmAddress, msg.sender); } @param atmAddress ATM address to unpause.
8,544,042
/** *Submitted for verification at BscScan.com on 2021-03-22 */ // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; library Strings { function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } 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)); } 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"); } } } 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 EnumerableSet { 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; } 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; } } 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; } } function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } function _length(Set storage set) private view returns (uint256) { return set._values.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; } function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } library EnumerableMap { struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } function _length(Map storage map) private view returns (uint256) { return map._entries.length; } function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } library Counters { using SafeMath for uint256; struct Counter { uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } 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; } } library Address { function isContract(address account) internal view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _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); } } } } interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } abstract contract ERC165 is IERC165 { bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { _registerInterface(_INTERFACE_ID_ERC165); } function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom(address from, address to, uint256 tokenId) external; function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } interface IERC721Receiver { function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } pragma solidity >=0.6.2 <0.8.0; interface IERC721Enumerable is IERC721 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); } pragma solidity >=0.6.0 <0.8.0; contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } function name() public view override returns (string memory) { return _name; } function symbol() public view override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } function baseURI() public view returns (string memory) { return _baseURI; } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } 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); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } abstract contract Initializable { bool private _initialized; bool private _initializing; 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) { address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // 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 Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { 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 LotteryOwnable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function initOwner(address owner) internal { _owner = owner; emit OwnershipTransferred(address(0), owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == msg.sender, "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 LotteryNFT is ERC721, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIds; mapping (uint256 => uint8[4]) public lotteryInfo; mapping (uint256 => uint256) public lotteryAmount; mapping (uint256 => uint256) public issueIndex; mapping (uint256 => bool) public claimInfo; constructor() public ERC721("Atari Lottery Ticket", "ATRITK") {} function newLotteryItem(address player, uint8[4] memory _lotteryNumbers, uint256 _amount, uint256 _issueIndex) public onlyOwner returns (uint256) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(player, newItemId); lotteryInfo[newItemId] = _lotteryNumbers; lotteryAmount[newItemId] = _amount; issueIndex[newItemId] = _issueIndex; return newItemId; } function getLotteryNumbers(uint256 tokenId) external view returns (uint8[4] memory) { return lotteryInfo[tokenId]; } function getLotteryAmount(uint256 tokenId) external view returns (uint256) { return lotteryAmount[tokenId]; } function getLotteryIssueIndex(uint256 tokenId) external view returns (uint256) { return issueIndex[tokenId]; } function claimReward(uint256 tokenId) external onlyOwner { claimInfo[tokenId] = true; } function multiClaimReward(uint256[] memory _tokenIds) external onlyOwner { for (uint i = 0; i < _tokenIds.length; i++) { claimInfo[_tokenIds[i]] = true; } } function burn(uint256 tokenId) external onlyOwner { _burn(tokenId); } function getClaimStatus(uint256 tokenId) external view returns (bool) { return claimInfo[tokenId]; } } contract Lottery is LotteryOwnable, Initializable { using SafeMath for uint256; using SafeMath for uint8; using SafeERC20 for IERC20; uint8 constant keyLengthForEachBuy = 11; // Allocation for first/sencond/third reward uint8[3] public allocation; // The TOKEN to buy lottery IERC20 public atari; // The Lottery NFT for tickets LotteryNFT public lotteryNFT; // adminAddress address public adminAddress; // maxNumber uint8 public maxNumber; // minPrice, if decimal is not 18, please reset it uint256 public minPrice; //remain balance fro last game uint256 public remainBalance; // ================================= // issueId => winningNumbers[numbers] mapping (uint256 => uint8[4]) public historyNumbers; // issueId => [tokenId] mapping (uint256 => uint256[]) public lotteryInfo; // issueId => [totalAmount, firstMatchAmount, secondMatchingAmount, thirdMatchingAmount] mapping (uint256 => uint256[]) public historyAmount; // issueId => nomatch mapping (uint256 => uint256) public nomatch; // issueId => trickyNumber => buyAmountSum mapping (uint256 => mapping(uint64 => uint256)) public userBuyAmountSum; // address => [tokenId] mapping (address => uint256[]) public userInfo; uint256 public issueIndex = 0; uint256 public totalAddresses = 0; uint256 public totalAmount = 0; uint256 public lastTimestamp; uint256 public nextPharse; uint256 public nextDraw; uint256 public DrawDuration; uint256 public ParseDuration; uint8[4] public winningNumbers; // default false bool public drawingPhase; // ================================= event Buy(address indexed user, uint256 tokenId); event Drawing(uint256 indexed issueIndex, uint8[4] winningNumbers); event Claim(address indexed user, uint256 tokenid, uint256 amount); event DevWithdraw(address indexed user, uint256 amount); event Reset(uint256 indexed issueIndex); event MultiClaim(address indexed user, uint256 amount); event MultiBuy(address indexed user, uint256 amount); constructor() public { } function initialize( IERC20 _atari, LotteryNFT _lottery, uint256 _minPrice, uint8 _maxNumber, address _owner, address _adminAddress ) public initializer { atari = _atari; lotteryNFT = _lottery; minPrice = _minPrice; maxNumber = _maxNumber; adminAddress = _adminAddress; lastTimestamp = block.timestamp; allocation = [60, 20, 10]; DrawDuration = 302400; ParseDuration = 43200; nextDraw=lastTimestamp.add(DrawDuration); nextPharse=nextDraw.sub(ParseDuration); initOwner(_owner); } uint8[4] private nullTicket = [0,0,0,0]; modifier onlyAdmin() { require(msg.sender == adminAddress, "admin: wut?"); _; } function drawed() public view returns(bool) { return winningNumbers[0] != 0; } function reset() external onlyAdmin { require(drawed(), "drawed?"); lastTimestamp = block.timestamp; totalAddresses = 0; totalAmount=0; winningNumbers[0]=0; winningNumbers[1]=0; winningNumbers[2]=0; winningNumbers[3]=0; drawingPhase = false; issueIndex = issueIndex +1; if(remainBalance>0) { internalBuy(remainBalance, nullTicket); } remainBalance = 0; nextDraw=lastTimestamp.add(DrawDuration); nextPharse=nextDraw.sub(ParseDuration); emit Reset(issueIndex); } function enterDrawingPhase() external { require(block.timestamp>=nextPharse,"not parse time"); require(!drawed(), 'drawed'); drawingPhase = true; } // add externalRandomNumber to prevent node validators exploiting function drawing(uint256 _externalRandomNumber) external { require(block.timestamp>=nextDraw,"not draw time"); require(!drawed(), "reset?"); require(drawingPhase, "enter drawing phase first"); bytes32 _structHash; uint256 _randomNumber; uint8 _maxNumber = maxNumber; bytes32 _blockhash = blockhash(block.number-1); // waste some gas fee here for (uint i = 0; i < 10; i++) { getTotalRewards(issueIndex); } uint256 gasleft = gasleft(); // 1 _structHash = keccak256( abi.encode( _blockhash, totalAddresses, gasleft, _externalRandomNumber ) ); _randomNumber = uint256(_structHash); assembly {_randomNumber := add(mod(_randomNumber, _maxNumber),1)} winningNumbers[0]=uint8(_randomNumber); // 2 _structHash = keccak256( abi.encode( _blockhash, totalAmount, gasleft, _externalRandomNumber ) ); _randomNumber = uint256(_structHash); assembly {_randomNumber := add(mod(_randomNumber, _maxNumber),1)} winningNumbers[1]=uint8(_randomNumber); // 3 _structHash = keccak256( abi.encode( _blockhash, lastTimestamp, gasleft, _externalRandomNumber ) ); _randomNumber = uint256(_structHash); assembly {_randomNumber := add(mod(_randomNumber, _maxNumber),1)} winningNumbers[2]=uint8(_randomNumber); // 4 _structHash = keccak256( abi.encode( _blockhash, gasleft, _externalRandomNumber ) ); _randomNumber = uint256(_structHash); assembly {_randomNumber := add(mod(_randomNumber, _maxNumber),1)} winningNumbers[3]=uint8(_randomNumber); historyNumbers[issueIndex] = winningNumbers; historyAmount[issueIndex] = calculateMatchingRewardAmount(); //unmatched amount if(historyAmount[issueIndex][0]==0){ nomatch[issueIndex] = 0; } else { nomatch[issueIndex] = ((historyAmount[issueIndex][0].mul(allocation[0])-historyAmount[issueIndex][1]).div(historyAmount[issueIndex][0])+ (historyAmount[issueIndex][0].mul(allocation[1])-historyAmount[issueIndex][2]).div(historyAmount[issueIndex][0])+ (historyAmount[issueIndex][0].mul(allocation[2])-historyAmount[issueIndex][3]).div(historyAmount[issueIndex][0])); } //matched number remainBalance = getTotalRewards(issueIndex).mul(nomatch[issueIndex]).mul(85).div(10000); drawingPhase = false; emit Drawing(issueIndex, winningNumbers); } function internalBuy(uint256 _price, uint8[4] memory _numbers) internal { require (!drawed(), 'drawed, can not buy now'); for (uint i = 0; i < 4; i++) { require (_numbers[i] <= maxNumber, 'exceed the maximum'); } uint256 tokenId = lotteryNFT.newLotteryItem(address(this), _numbers, _price, issueIndex); lotteryInfo[issueIndex].push(tokenId); totalAmount = totalAmount.add(_price); lastTimestamp = block.timestamp; emit Buy(address(this), tokenId); } function buy(uint256 _price, uint8[4] memory _numbers) external { require(!drawed(), 'drawed, can not buy now'); require(!drawingPhase, 'drawing, can not buy now'); require (_price >= minPrice, 'price must above minPrice'); for (uint i = 0; i < 4; i++) { require (_numbers[i] <= maxNumber, 'exceed number scope'); } uint256 tokenId = lotteryNFT.newLotteryItem(msg.sender, _numbers, _price, issueIndex); lotteryInfo[issueIndex].push(tokenId); if (userInfo[msg.sender].length == 0) { totalAddresses = totalAddresses + 1; } userInfo[msg.sender].push(tokenId); totalAmount = totalAmount.add(_price); lastTimestamp = block.timestamp; uint64[keyLengthForEachBuy] memory userNumberIndex = generateNumberIndexKey(_numbers); for (uint i = 0; i < keyLengthForEachBuy; i++) { userBuyAmountSum[issueIndex][userNumberIndex[i]]=userBuyAmountSum[issueIndex][userNumberIndex[i]].add(_price); } atari.safeTransferFrom(address(msg.sender), address(this), _price); emit Buy(msg.sender, tokenId); } function multiBuy(uint256 _price, uint8[4][] memory _numbers) external { require (!drawed(), 'drawed, can not buy now'); require(!drawingPhase, 'drawing, can not buy now'); require (_price >= minPrice, 'price must above minPrice'); uint256 totalPrice = 0; for (uint i = 0; i < _numbers.length; i++) { for (uint j = 0; j < 4; j++) { require (_numbers[i][j] <= maxNumber && _numbers[i][j] > 0, 'exceed number scope'); } uint256 tokenId = lotteryNFT.newLotteryItem(msg.sender, _numbers[i], _price, issueIndex); lotteryInfo[issueIndex].push(tokenId); if (userInfo[msg.sender].length == 0) { totalAddresses = totalAddresses + 1; } userInfo[msg.sender].push(tokenId); totalAmount = totalAmount.add(_price); lastTimestamp = block.timestamp; totalPrice = totalPrice.add(_price); uint64[keyLengthForEachBuy] memory numberIndexKey = generateNumberIndexKey(_numbers[i]); for (uint k = 0; k < keyLengthForEachBuy; k++) { userBuyAmountSum[issueIndex][numberIndexKey[k]]=userBuyAmountSum[issueIndex][numberIndexKey[k]].add(_price); } } atari.safeTransferFrom(address(msg.sender), address(this), totalPrice); emit MultiBuy(msg.sender, totalPrice); } function claimReward(uint256 _tokenId) external { require(msg.sender == lotteryNFT.ownerOf(_tokenId), "not from owner"); require (!lotteryNFT.getClaimStatus(_tokenId), "claimed"); uint256 reward = getRewardView(_tokenId); lotteryNFT.claimReward(_tokenId); if(reward>0) { atari.safeTransfer(address(msg.sender), reward); } emit Claim(msg.sender, _tokenId, reward); } function multiClaim(uint256[] memory _tickets) external { uint256 totalReward = 0; for (uint i = 0; i < _tickets.length; i++) { require (msg.sender == lotteryNFT.ownerOf(_tickets[i]), "not from owner"); require (!lotteryNFT.getClaimStatus(_tickets[i]), "claimed"); uint256 reward = getRewardView(_tickets[i]); if(reward>0) { totalReward = reward.add(totalReward); } } lotteryNFT.multiClaimReward(_tickets); if(totalReward>0) { atari.safeTransfer(address(msg.sender), totalReward); } emit MultiClaim(msg.sender, totalReward); } function generateNumberIndexKey(uint8[4] memory number) public pure returns (uint64[keyLengthForEachBuy] memory) { uint64[4] memory tempNumber; tempNumber[0]=uint64(number[0]); tempNumber[1]=uint64(number[1]); tempNumber[2]=uint64(number[2]); tempNumber[3]=uint64(number[3]); uint64[keyLengthForEachBuy] memory result; result[0] = tempNumber[0]*256*256*256*256*256*256 + 1*256*256*256*256*256 + tempNumber[1]*256*256*256*256 + 2*256*256*256 + tempNumber[2]*256*256 + 3*256 + tempNumber[3]; result[1] = tempNumber[0]*256*256*256*256 + 1*256*256*256 + tempNumber[1]*256*256 + 2*256+ tempNumber[2]; result[2] = tempNumber[0]*256*256*256*256 + 1*256*256*256 + tempNumber[1]*256*256 + 3*256+ tempNumber[3]; result[3] = tempNumber[0]*256*256*256*256 + 2*256*256*256 + tempNumber[2]*256*256 + 3*256 + tempNumber[3]; result[4] = 1*256*256*256*256*256 + tempNumber[1]*256*256*256*256 + 2*256*256*256 + tempNumber[2]*256*256 + 3*256 + tempNumber[3]; result[5] = tempNumber[0]*256*256 + 1*256+ tempNumber[1]; result[6] = tempNumber[0]*256*256 + 2*256+ tempNumber[2]; result[7] = tempNumber[0]*256*256 + 3*256+ tempNumber[3]; result[8] = 1*256*256*256 + tempNumber[1]*256*256 + 2*256 + tempNumber[2]; result[9] = 1*256*256*256 + tempNumber[1]*256*256 + 3*256 + tempNumber[3]; result[10] = 2*256*256*256 + tempNumber[2]*256*256 + 3*256 + tempNumber[3]; return result; } function calculateMatchingRewardAmount() internal view returns (uint256[4] memory) { uint64[keyLengthForEachBuy] memory numberIndexKey = generateNumberIndexKey(winningNumbers); uint256 totalAmout1 = userBuyAmountSum[issueIndex][numberIndexKey[0]]; uint256 sumForTotalAmout2 = userBuyAmountSum[issueIndex][numberIndexKey[1]]; sumForTotalAmout2 = sumForTotalAmout2.add(userBuyAmountSum[issueIndex][numberIndexKey[2]]); sumForTotalAmout2 = sumForTotalAmout2.add(userBuyAmountSum[issueIndex][numberIndexKey[3]]); sumForTotalAmout2 = sumForTotalAmout2.add(userBuyAmountSum[issueIndex][numberIndexKey[4]]); uint256 totalAmout2 = sumForTotalAmout2.sub(totalAmout1.mul(4)); uint256 sumForTotalAmout3 = userBuyAmountSum[issueIndex][numberIndexKey[5]]; sumForTotalAmout3 = sumForTotalAmout3.add(userBuyAmountSum[issueIndex][numberIndexKey[6]]); sumForTotalAmout3 = sumForTotalAmout3.add(userBuyAmountSum[issueIndex][numberIndexKey[7]]); sumForTotalAmout3 = sumForTotalAmout3.add(userBuyAmountSum[issueIndex][numberIndexKey[8]]); sumForTotalAmout3 = sumForTotalAmout3.add(userBuyAmountSum[issueIndex][numberIndexKey[9]]); sumForTotalAmout3 = sumForTotalAmout3.add(userBuyAmountSum[issueIndex][numberIndexKey[10]]); uint256 totalAmout3 = sumForTotalAmout3.add(totalAmout1.mul(6)).sub(sumForTotalAmout2.mul(3)); return [totalAmount, totalAmout1, totalAmout2, totalAmout3]; } function getMatchingRewardAmount(uint256 _issueIndex, uint256 _matchingNumber) public view returns (uint256) { return historyAmount[_issueIndex][5 - _matchingNumber]; } function getTotalRewards(uint256 _issueIndex) public view returns(uint256) { require (_issueIndex <= issueIndex, '_issueIndex <= issueIndex'); if(!drawed() && _issueIndex == issueIndex) { return totalAmount; } return historyAmount[_issueIndex][0]; } function getRewardView(uint256 _tokenId) public view returns(uint256) { uint256 _issueIndex = lotteryNFT.getLotteryIssueIndex(_tokenId); uint8[4] memory lotteryNumbers = lotteryNFT.getLotteryNumbers(_tokenId); uint8[4] memory _winningNumbers = historyNumbers[_issueIndex]; require(_winningNumbers[0] != 0, "not drawed"); uint256 matchingNumber = 0; for (uint i = 0; i < lotteryNumbers.length; i++) { if (_winningNumbers[i] == lotteryNumbers[i]) { matchingNumber= matchingNumber +1; } } uint256 reward = 0; if (matchingNumber > 1) { uint256 amount = lotteryNFT.getLotteryAmount(_tokenId); uint256 poolAmount = getTotalRewards(_issueIndex).mul(allocation[4-matchingNumber]).div(100); reward = amount.mul(1e12).div(getMatchingRewardAmount(_issueIndex, matchingNumber)).mul(poolAmount); } //if nomatch 15% reward if(nomatch[_issueIndex]>0){ uint256 amount = lotteryNFT.getLotteryAmount(_tokenId).mul(1e12); reward = reward.add(amount.mul(nomatch[_issueIndex]).mul(15).div(10000)); } return reward.div(1e12); } function getMatchingNumber (uint256 _tokenId) internal view returns(uint256) { uint256 _issueIndex = lotteryNFT.getLotteryIssueIndex(_tokenId); uint8[4] memory lotteryNumbers = lotteryNFT.getLotteryNumbers(_tokenId); uint8[4] memory _winningNumbers = historyNumbers[_issueIndex]; require(_winningNumbers[0] != 0, "not drawed"); uint256 matchingNumber = 0; for (uint i = 0; i < lotteryNumbers.length; i++) { if (_winningNumbers[i] == lotteryNumbers[i]) { matchingNumber= matchingNumber +1; } } return matchingNumber; } // Update admin address by the previous dev. function setAdmin(address _adminAddress) public onlyOwner { adminAddress = _adminAddress; } // Withdraw without caring about rewards. EMERGENCY ONLY. function adminWithdraw(uint256 _amount) public onlyAdmin { atari.safeTransfer(address(msg.sender), _amount); emit DevWithdraw(msg.sender, _amount); } //safe balance withdraw function adminWithdrawSafe() public onlyAdmin { uint256 _amount = atari.balanceOf(address(this)).sub(getTotalRewards(issueIndex)); atari.safeTransfer(address(msg.sender),_amount); emit DevWithdraw(msg.sender, _amount); } // Set the minimum price for one ticket function setMinPrice(uint256 _price) external onlyAdmin { minPrice = _price; } // Set the minimum price for one ticket function setMaxNumber(uint8 _maxNumber) external onlyAdmin { maxNumber = _maxNumber; } // Set the allocation for one reward function setAllocation(uint8 _allcation1, uint8 _allcation2, uint8 _allcation3) external onlyAdmin { allocation = [_allcation1, _allcation2, _allcation3]; } //function get userInfo function getUserInfo(address user) external view returns(uint256[] memory _userinfo){ _userinfo = userInfo[user]; } function getHistoryNumbers(uint256 _issueIndex) external view returns(uint8[4] memory _historyNumbers){ _historyNumbers = historyNumbers[_issueIndex]; } function getHistoryAmounts(uint256 _issueIndex) external view returns(uint256[4] memory _historyAmount){ _historyAmount[0] = historyAmount[_issueIndex][0]; _historyAmount[1] = historyAmount[_issueIndex][1]; _historyAmount[2] = historyAmount[_issueIndex][2]; _historyAmount[3] = historyAmount[_issueIndex][3]; } } contract multicall{ Lottery public lottery; LotteryNFT public lotteryNFT; constructor(Lottery _lottery, LotteryNFT _lotteryNFT) public { lottery = _lottery; lotteryNFT = _lotteryNFT; } function setPath(Lottery _lottery, LotteryNFT _lotteryNFT) external { lottery = _lottery; lotteryNFT = _lotteryNFT; } function ticketDatas(uint256[] memory _tickets)external view returns(uint256[] memory rewardAmounts,bool[] memory claimStatus,bool[] memory drawStatus,uint8[][] memory ticketNumber){ rewardAmounts= new uint256[](_tickets.length); claimStatus = new bool[](_tickets.length); drawStatus = new bool[](_tickets.length); ticketNumber =new uint8[][](_tickets.length); for (uint i = 0; i < _tickets.length; i++) { uint256 _issueIndex = lotteryNFT.getLotteryIssueIndex(_tickets[i]); // ticket number uint8[4] memory lotteryNumbers = lotteryNFT.getLotteryNumbers(_tickets[i]); uint8[] memory temp = new uint8[](4); temp[0]=lotteryNumbers[0]; temp[1]=lotteryNumbers[1]; temp[2]=lotteryNumbers[2]; temp[3]=lotteryNumbers[3]; ticketNumber[i] = temp; //winningNumbers uint8[4] memory _winningNumbers =lottery.getHistoryNumbers(_issueIndex); if(_winningNumbers[0] == 0) { drawStatus[i] = false; rewardAmounts[i] = 0; } else { drawStatus[i]=true; rewardAmounts[i] = lottery.getRewardView(_tickets[i]); } claimStatus[i] = lotteryNFT.getClaimStatus(_tickets[i]); } } function historyDatas(uint256[] memory _issueIndexs) external view returns(uint8[][] memory _historyNumbers ,uint256[][] memory _historyAmount) { _historyNumbers = new uint8[][](_issueIndexs.length); for (uint i = 0; i < _issueIndexs.length; i++) { uint8[4] memory _winningNumbers =lottery.getHistoryNumbers(_issueIndexs[i]); uint8[] memory temp = new uint8[](4); temp[0]=_winningNumbers[0]; temp[1]=_winningNumbers[1]; temp[2]=_winningNumbers[2]; temp[3]=_winningNumbers[3]; _historyNumbers[i]=temp; } _historyAmount = new uint256[][](_issueIndexs.length); for (uint i = 0; i < _issueIndexs.length; i++) { uint256 issueIndex = lottery.issueIndex(); if(_issueIndexs[i]>issueIndex-1){ uint256[] memory temp = new uint256[](4); temp[0]=0; temp[1]=0; temp[2]=0; temp[3]=0; _historyAmount[i]=temp; } else { uint256[4] memory _winningAmounts =lottery.getHistoryAmounts(_issueIndexs[i]); uint256[] memory temp = new uint256[](4); temp[0]=_winningAmounts[0]; temp[1]=_winningAmounts[1]; temp[2]=_winningAmounts[2]; temp[3]=_winningAmounts[3]; _historyAmount[i]=temp; } } } }
Set the minimum price for one ticket
function setMinPrice(uint256 _price) external onlyAdmin { minPrice = _price; }
1,157,889
./full_match/1/0x88cf4d065f9d1578239D5c5020c24aEc16789034/sources/contracts/ClayGen.sol
BaseOreHasEyesHasMouthBgColorLargeOre
function getTraitTypes() internal pure returns (Trait[][6] memory) { Trait[][6] memory TIERS = [ new Trait[](4), new Trait[](9), new Trait[](2), new Trait[](2), new Trait[](6), new Trait[](2) ]; TIERS[0][0] = Trait('Base', 'Clay'); TIERS[0][1] = Trait('Base', 'Stone'); TIERS[0][2] = Trait('Base', 'Metal'); TIERS[0][3] = Trait('Base', 'Obsidian'); TIERS[1][0] = Trait('Ore', 'None'); TIERS[1][1] = Trait('Ore', 'Grass'); TIERS[1][2] = Trait('Ore', 'Bronze'); TIERS[1][3] = Trait('Ore', 'Jade'); TIERS[1][4] = Trait('Ore', 'Gold'); TIERS[1][5] = Trait('Ore', 'Ruby'); TIERS[1][6] = Trait('Ore', 'Sapphire'); TIERS[1][7] = Trait('Ore', 'Amethyst'); TIERS[1][8] = Trait('Ore', 'Diamond'); TIERS[2][0] = Trait('HasEyes', 'No'); TIERS[2][1] = Trait('HasEyes', 'Yes'); TIERS[3][0] = Trait('HasMouth', 'No'); TIERS[3][1] = Trait('HasMouth', 'Yes'); TIERS[4][0] = Trait('BgColor', 'Forest'); TIERS[4][1] = Trait('BgColor', 'Mountain'); TIERS[4][2] = Trait('BgColor', 'River'); TIERS[4][3] = Trait('BgColor', 'Field'); TIERS[4][4] = Trait('BgColor', 'Cave'); TIERS[4][5] = Trait('BgColor', 'Clouds'); TIERS[5][0] = Trait('LargeOre', 'No'); TIERS[5][1] = Trait('LargeOre', 'Yes'); return TIERS; }
4,840,777
/** * @title The contract that incorporates the logic of the wallet (for internal usage) * @notice This contract is used when proposals are stored as structs but not created as individual contract by the factory. */ pragma solidity ^0.4.21; import "./Wallet.sol"; import "./ExternalWallet.sol"; import "./Accessible.sol"; import "./ProposalInterface.sol"; import "./DAA.sol"; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; import "../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol"; contract Treasury is Ownable{ Wallet public daoWallet; ExternalWallet public daoExternalWallet; Accessible public accessibleGate; ProposalInterface public proposalGate; DAA public daa; mapping(bytes32=>bool) public cleared; // /** // *@param WalletType True when the wallet is internal; False when external // *@param PayorDraw True when the account pays to the wallet; Otherwise, false // */ // event WalletActivity(address indexed Account, bool indexed WalletType, bool indexed PayOrDraw, uint256 Amount, uint256 timeStamp); modifier uponProposalSuccess(bytes32 _proposalID) { require(proposalGate.getProposalFinalResult(_proposalID)); _; } modifier expectProposalType(bytes32 _proposalID, bool _isGAProposal) { require(proposalGate.getProposalType(_proposalID) == _isGAProposal); _; } modifier memberOnly { require(accessibleGate.checkIsMember(msg.sender)); _; } /** *@dev When the delegate stepped down, no one can drain money from the internal wallet. * GA proposals can be concluded. Deposit in the external wallet can be reclaimed and withdrawed. * Normal proposals can be conlcluded, but no money can be withdrawed at the moment until the new delegate is in place. */ modifier allowPayout { require(accessibleGate.hasDelegate()); _; } /** *@dev Check if an adress is not empty. */ modifier notEmpty(address _adr) { require(_adr != 0x0); _; } /** *@title contructor of the treasury *@dev The treasury operates the two wallets, therefore their addresses are needed. * Treasury also needs to double check with the status of each member. * Treasury needs to check the status of proposals with the proposal manager. *@param _walletAdr The address of the DAO wallet *@param _extWalletAdr The address of the wallet where external organisations can deposit money *@param _membershipAdr The address of the Membership contract *@param _proposalInterfaceAdr The address of the proposal Manager (interface) */ constructor(address _walletAdr, address _extWalletAdr, address _membershipAdr, address _proposalInterfaceAdr) public { daoWallet = Wallet(_walletAdr); daoExternalWallet = ExternalWallet(_extWalletAdr); accessibleGate = Accessible(_membershipAdr); proposalGate = ProposalInterface(_proposalInterfaceAdr); } /** *@title Update the address of the membership contract *@dev This function can only be called by the DAA, eventually trigged by a successful proposal *@param _newAccessible The address of the new membership contract. */ function updateMembershipContractAddress(address _newAccessible) public onlyOwner notEmpty(_newAccessible) { // require(_newAccessible != 0x0); accessibleGate = Accessible(_newAccessible); } /** *@title Update address of the proposal manager contract *@dev This function can only be called by the DAA, eventually trigged by a successful proposal *@param _newProposal The address of the new proposal manager contract. */ function updateProposalContractAddress(address _newProposal) public onlyOwner notEmpty(_newProposal) { // require(_newProposal != 0x0); proposalGate = ProposalInterface(_newProposal); } /** *@title After a normal proposal is concluded, the beneficiary can trigger this function and * let the treasury to prepare for the allowance accordingly. *@dev Anyone can call this function to let the tresury increase allowance of * the beneficiary after the conclusion of proposals. *@param _proposalID the reference ID of proposals. */ function startClearing(bytes32 _proposalID) uponProposalSuccess(_proposalID) expectProposalType(_proposalID, false) public returns (bool) { address _destination = proposalGate.getProposaldestinationAddress(_proposalID); uint256 _amount = proposalGate.getProposalAllowance(_proposalID); if (daoWallet.increaseAllowance(_destination, _amount)) { cleared[_proposalID] = true; return true; } else { return false; } } /** *@title Member pay annual membership fee with this function *@dev Transfer the money to the wallet. */ function payContribution() public payable memberOnly returns(bool) { return daoWallet.payContribution.value(msg.value)(msg.sender); } /** *@title Pay the fee when the membership is granted (whitelisted by two) *@dev Transfer the money to the wallet only when the value is higher than needed. */ function payNewMembershipFee() public payable returns (bool) { require(accessibleGate.checkIsWhitelistedByTwo(msg.sender)); require(accessibleGate.reachDesiredValue(msg.value)); accessibleGate.addNewMember(msg.sender); daoWallet.payContribution.value(msg.value)(msg.sender); // emit WalletActivity(msg.sender, true, true, msg.value, block.timestamp); } /** *@title The beneficiary can request payment when proposal is successful and properly concluded. *@dev This action can only be taken when there's a delegate of the DAAS. */ function withdrawMoneyFromInternalWallet() public allowPayout returns(bool) { return daoWallet.withdrawMoney(msg.sender); } /** *@title The beneficiary can also withdraw money from the external wallet if possible *@dev This action can take place even the delegate is not in charge (no modifier of "allowPayout") *@param _proposalID the reference ID of proposals. */ function withdrawMoneyFromExternalWallet(bytes32 _proposalID) public returns (bool) { return daoExternalWallet.withdrawMoney(_proposalID, msg.sender); } /** *@title Change the address of wallets, upon success of proposal *@dev When the proposal is successful, anyone can trigger this action. *@notice Anyone can call this function. *@param _proposalID the reference ID of proposals. */ function changeWalletAddress( bytes32 _proposalID ) public uponProposalSuccess(_proposalID) returns (bool) { require(proposalGate.checkActionIsUpdateWallet(_proposalID)); address _newInternalWalletAdr; address _newExternalWalletAdr; (_newInternalWalletAdr, _newExternalWalletAdr) = proposalGate.getProposalProposedWalletAddress(_proposalID); // require(msg.sender == address(proposalGate)); require(_newInternalWalletAdr != 0x0 || _newExternalWalletAdr != 0x0); // This function can only be called by the proposalManager (upon ) // only upon success of GA proposal. If one address is 0x0 then that wallet doesn't change. if (_newInternalWalletAdr != 0x0) { daoWallet = Wallet(_newInternalWalletAdr); daoWallet.changeWalletAddress(_newInternalWalletAdr); daa.updateInternalWallet(_newInternalWalletAdr); } if (_newExternalWalletAdr != 0x0) { daoExternalWallet = ExternalWallet(_newExternalWalletAdr); daoExternalWallet.changeWalletAddress(_newExternalWalletAdr); daa.updateExternalWallet(_newExternalWalletAdr); } return true; } /** *@title Getter of member's contribution (membership fee/donation) *@param _adr the address of account */ function getIndividualContribution(address _adr) public view returns (uint256) { return daoWallet.getIndividualContribution(_adr); } /** *@title Getter of external funding of each external funds *@param _proposalID the reference ID of proposals. */ function getProjectExternalFund(bytes32 _proposalID) public view returns (uint256) { return daoExternalWallet.getProjectExternalFund(_proposalID); } }
Getter of external funding of each external funds _proposalID the reference ID of proposals./
function getProjectExternalFund(bytes32 _proposalID) public view returns (uint256) { return daoExternalWallet.getProjectExternalFund(_proposalID); }
12,711,099
/* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.5; import "../src/LibAddressArray.sol"; contract TestLibAddressArray { using LibAddressArray for address[]; /// @dev Append a new address to an array of addresses. /// The `addressArray` may need to be reallocated to make space /// for the new address. Because of this we return the resulting /// memory location of `addressArray`. /// @param addressArray Array of addresses. /// @param addressToAppend Address to append. /// @return Array of addresses: [... addressArray, addressToAppend] function publicAppend(address[] memory addressArray, address addressToAppend) public pure returns (address[] memory) { return addressArray.append(addressToAppend); } /// @dev Moves the free memory pointer by `freeMemOffset` bytes, /// then performs the append. /// This tests the behavior of the address array being reallocated if /// the memory immediately after the old array is claimed. /// @param addressArray Array of addresses. /// @param freeMemOffset Number of (signed) bytes to offset the free memory pointer (0x40). /// @param addressToAppend Address to append. /// @return The new address array. /// @return The memory address of the old address array. /// @return The memory address of the new address array. function testAppendRealloc( address[] memory addressArray, int256 freeMemOffset, address addressToAppend ) public pure returns ( address[] memory result, uint256 oldArrayMemStart, uint256 newArrayMemStart ) { assembly { // Remember the original memory address of the array. oldArrayMemStart := addressArray // Move the free memory pointer. mstore(0x40, add(mload(0x40), freeMemOffset)) } // Call append. result = addressArray.append(addressToAppend); // Get the new array memory address. assembly { newArrayMemStart := result } } /// @dev Checks if an address array contains the target address. /// @param addressArray Array of addresses. /// @param target Address to search for in array. /// @return True if the addressArray contains the target. function publicContains(address[] memory addressArray, address target) public pure returns (bool success) { return addressArray.contains(target); } /// @dev Finds the index of an address within an array. /// @param addressArray Array of addresses. /// @param target Address to search for in array. /// @return Existence and index of the target in the array. function publicIndexOf(address[] memory addressArray, address target) public pure returns (bool success, uint256 index) { (success, index) = addressArray.indexOf(target); } }
Finds the index of an address within an array. addressArray Array of addresses. target Address to search for in array. return Existence and index of the target in the array.
function publicIndexOf(address[] memory addressArray, address target) public pure returns (bool success, uint256 index) { (success, index) = addressArray.indexOf(target); }
1,059,825
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; // @title: Crypto Panther Club // @developer: Arthur V. // @artist: https://marcinglod.com // @url: https://cryptopanther.club // // ,,,. // ,(%&&&&/ ,@@@#//&@@#. // (@&@# .* .&@@&&@@% (@% &@@.#@&@. // #@&@,/@@@( .#@@@@@@#, #@@@@@@@@&@( #@*,%*,%@@@( // &@&@* /%* *@@@@&#(/,. *@@@. .,,*/* * &@@@@@@@@@&&&%@@@&/ // .*#%(,*. *(#%@%*./@(,@&@#.&@@@@@@&&&./@&&&&&&&&&&&&@* // ,@@&@./@@@@@&* *.,@&&@# ,#&&%, /@&&&&&&&&&&&&&&@% // ,@&&@@&( .*/#&@@& /@&&&&&&@@&&&@&&&&@&&&&&&&&&&&&@& // #@* *@@@@@@@@@# %@&&&&&&&@@&&&&&@@*[email protected]&&&&&&&&&&&@* // .* .,*(&@&&&&&#,.***,./&@&&&&&&&&&&@( // *. /@@@@( ,@&&&&&@/ @@&&&&&&&&&&&@&. // %@@#. .#@@@@@@@@% (@@&*.#@&&&&&&&&&@@#, // %@@@@@@( #@@@@@@@@@@@@# .%@&&&@@@@@@@@( // (/(&@@@@@.*@@@@@@@@@@&##&* &&&&&&/,#%#%* // (@@@@@@@/*@@@@@@@@@@@&@& (%#((, *,.,,/&# // .,,(#, ,**/((#(//.*&@&&@/ #@&&@@@% // %@@@@@@@@@@* *@@@( %@&@* *@&&&&@* // ,**, /%@@@@&* /@@&&&&@.,@&, .&@&&@& // %@&&&@@% * *@@&&&&&&@/ @% &@&&@# ,&@@&%/. // (@@&&@&*.#@&&&&&&&@# #&, .&@&@/.&@&&&&&&&@@&%(*. // %@ @@&&&&&&@@/ .* (@&&&&&&&&&&&&&&&&&&&&@@&(. // %@&&&&&&/,/%&@@@@%. #@&&@&#(%&@&&&&&&&&&&&&&&&&&&&@@&#*. // /@&&&&&%%@&&&&@@@%%* *@&@( /@@@( %@&&&##&@@@@&&&&&&&&&&&&@@% // &@&&&&&&&&&#*/#%&&@#. /@@,[email protected]@@@@@@@* %@&&&&/ .*(%&@&&&&&&&& // %@&&&&&&&@@&&&&&&&&@/ /@( @@@@@@@@@@@ *@&&&@# *&@@&&& // /@&&&&&&&&@%(@@&&&@% *@*[email protected]@@@@@@@@@@@.,@&&&@% ,/% // &@&&&&&&&&@/ #@@@, ,@*[email protected]@@@@@@@@@@@@, @&&&&@, // /@&&&&&&&&&@%, [email protected]( @@@@@@@@@@@@@@/ &@&&&@/ // &@&&&&&&&&&@* &@ (@@@@@@@@@@@@@@# %@&&&@% // (@&&&&&&@#. %@/ @@@@@@@@@@@@@@@&.*@&&&&@* // ,@&&&@# #@@ /@@@@@@@@@@@@@@@@/ &@&&&@& // .&@&&@&, #@@% %@@@@@@@@@@@@@@@@&./@&&&&@# // (@&&&@@. (@&@( &@@@@@@@@@@@@@@@@@# &@&&&&@( // ,@&&&&@&* /@&&@/ &@@@@@@@@@@@@@@@@@@*,&&&&&&@( import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; contract CryptoPantherClub is ERC721, ReentrancyGuard, VRFConsumerBase, Ownable { // ======== Counter ========= using Counters for Counters.Counter; Counters.Counter private supplyCounter; // ======== Supply ========= uint256 public constant MAX_SUPPLY = 5555; // ======== Max Mints Per Address ========= uint256 public maxPerAddressWhitelist; uint256 public maxPerAddressPublic; // ======== Price ========= uint256 public priceWhitelist; uint256 public pricePublic; // ======== Mints Per Address Mapping ======== struct MintTypes { uint256 _numberOfMintsByAddress; } mapping(address => MintTypes) public addressToMints; // ======== Base URI ========= string private baseURI; // ======== Phase ========= enum SalePhase{ Locked, Whitelist, PrePublic, Public, Ended } SalePhase public phase = SalePhase.Locked; // ======== Chainlink VRF (v.1) ======== bytes32 internal immutable keyHash; uint256 internal immutable fee; uint256 public indexShift = 0; // ======== Whitelist Coupons ======== address private constant ownerSigner = 0x493e23ed0756415107993FE3D777Ca1A356FB038; enum CouponType{ Whitelist } struct Coupon { bytes32 r; bytes32 s; uint8 v; } // ======== Constructor ========= constructor( string memory name_, string memory symbol_, string memory hiddenURI_ ) VRFConsumerBase( 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator 0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token ) ERC721(name_, symbol_) { baseURI = hiddenURI_; keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445; // VRF keyHash fee = 2 * 10 ** 18; // 2 LINK } // ======== Team Reserve (Events, Promotions, etc.) ========= function reserve(uint256 amount_) external onlyLockedPhase onlyOwner { require(amount_ > 0, "Amount can't be zero."); for(uint256 ind_ = 0; ind_ < amount_; ind_++) { _safeMint(msg.sender, totalSupply() + 1); supplyCounter.increment(); } } // ======== Set Whitelist Price ======== function setPriceWhitelist(uint256 price_) external onlyLockedPhase onlyOwner { priceWhitelist = price_; } // ======== Set Public Pirce ======== function setPricePublic(uint256 price_) external onlyPrePublicPhase onlyOwner { pricePublic = price_; } // ======== Set Max Whitelist Mint Amount Per Address ======== function setMaxPerAddressWhitelist(uint256 amount_) external onlyLockedPhase onlyOwner { maxPerAddressWhitelist = amount_; } // ======== Set Max Public Mint Amount Per Address ======== function setMaxPerAddressPublic(uint256 amount_) external onlyPrePublicPhase onlyOwner { maxPerAddressPublic = amount_; } // ======== Enable Whitelist Mint ========= function setWhitelistPhase() external onlyLockedPhase onlyOwner { require(priceWhitelist != 0, "Whitelist price is not set."); require(maxPerAddressWhitelist != 0, "Max whitelist mint amount not set."); phase = SalePhase.Whitelist; } // ======== Enable PrePublic Phase ========= function setPrePublicPhase() external onlyWhitelistPhase onlyOwner { phase = SalePhase.PrePublic; } // ======== Enable Public Mint ========= function setPublicPhase() external onlyPrePublicPhase onlyOwner { require(pricePublic != 0, "Public price is not set."); require(maxPerAddressPublic != 0, "Max public mint amount not set."); phase = SalePhase.Public; } // ======== End Sale ========= function setEndedPhase() external onlyOwner { phase = SalePhase.Ended; } // ======== Whitelist Mint ========= function whitelistMint(uint256 amount_, Coupon memory coupon_) public payable onlyWhitelistPhase validateAmount(amount_, maxPerAddressWhitelist) validateSupply(amount_) validateEthPayment(amount_, priceWhitelist) nonReentrant { require(amount_ + addressToMints[msg.sender]._numberOfMintsByAddress <= maxPerAddressWhitelist, "Exceeds number of whitelist mints allowed."); bytes32 digest = keccak256(abi.encode(CouponType.Whitelist, msg.sender)); require(isVerifiedCoupon(digest, coupon_), "Invalid coupon"); addressToMints[msg.sender]._numberOfMintsByAddress += amount_; for(uint256 ind_ = 0; ind_ < amount_; ind_++) { _safeMint(msg.sender, totalSupply() + 1); supplyCounter.increment(); } if (totalSupply() == MAX_SUPPLY) { phase = SalePhase.Ended; } } // ======== Public Mint ========= function mint(uint256 amount_) public payable onlyPublicPhase validateAmount(amount_, maxPerAddressPublic) validateSupply(amount_) validateEthPayment(amount_, pricePublic) nonReentrant { require(amount_ + addressToMints[msg.sender]._numberOfMintsByAddress <= maxPerAddressPublic, "Exceeds number of mints allowed."); addressToMints[msg.sender]._numberOfMintsByAddress += amount_; for(uint256 ind_ = 0; ind_ < amount_; ind_++) { _safeMint(msg.sender, totalSupply() + 1); supplyCounter.increment(); } if (totalSupply() == MAX_SUPPLY) { phase = SalePhase.Ended; } } // ======== Reveal Metadata ========= function reveal(string memory baseURI_) external onlyEndedPhase onlyZeroIndexShift onlyOwner { baseURI = baseURI_; requestRandomIndexShift(); } // ======== Return Base URI ========= function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // ======== Return Token URI ========= function tokenURI(uint256 tokenId) public view virtual override(ERC721) returns (string memory) { require(_exists(tokenId), "Nonexistent token."); string memory sequenceId; if (indexShift > 0) { sequenceId = Strings.toString((tokenId + indexShift) % MAX_SUPPLY + 1); } else { sequenceId = "0"; } return string(abi.encodePacked(baseURI, sequenceId)); } // ======== Get Total Supply ======== function totalSupply() public view returns (uint256) { return supplyCounter.current(); } // ======== Get Random Number Using Chainlink VRF ========= function requestRandomIndexShift() private returns (bytes32 requestId) { require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK."); return requestRandomness(keyHash, fee); } // ======== Set Random Starting Index ========= function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { indexShift = (randomness % MAX_SUPPLY) + 1; } // ======== Verify Coupon ========= function isVerifiedCoupon(bytes32 digest_, Coupon memory coupon_) internal view returns (bool) { address signer = ecrecover(digest_, coupon_.v, coupon_.r, coupon_.s); require(signer != address(0), 'ECDSA: invalid signature'); return signer == ownerSigner; } // ======== Withdraw ========= function withdraw(address payee_, uint256 amount_) external onlyOwner { (bool success, ) = payee_.call{value: amount_}(''); require(success, 'Transfer failed.'); } // ======== Modifiers ======== modifier validateEthPayment(uint256 amount_, uint256 price_) { require(amount_ * price_ <= msg.value, "Ether value sent is not correct."); _; } modifier validateSupply(uint256 amount_) { require(totalSupply() + amount_ <= MAX_SUPPLY, "Max supply exceeded."); _; } modifier validateAmount(uint256 amount_, uint256 max_) { require(amount_ > 0 && amount_ <= max_, "Amount is out of range."); _; } modifier onlyLockedPhase() { require(phase == SalePhase.Locked, "Minting is not locked."); _; } modifier onlyWhitelistPhase() { require(phase == SalePhase.Whitelist, "Whitelist sale is not active."); _; } modifier onlyPrePublicPhase() { require(phase == SalePhase.PrePublic, "PrePublic phase is not active."); _; } modifier onlyPublicPhase() { require(phase == SalePhase.Public, "Public sale is not active."); _; } modifier onlyEndedPhase() { require(phase == SalePhase.Ended, "Sale has not ended."); _; } modifier onlyZeroIndexShift() { require(indexShift == 0, "Already randomized."); _; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/LinkTokenInterface.sol"; import "./VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 private constant USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface internal immutable LINK; address private immutable vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 => uint256) /* keyHash */ /* nonce */ private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor(address _vrfCoordinator, address _link) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool success); function transferFrom( address from, address to, uint256 value ) external returns (bool success); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } }
======== Team Reserve (Events, Promotions, etc.) =========
function reserve(uint256 amount_) external onlyLockedPhase onlyOwner { require(amount_ > 0, "Amount can't be zero."); for(uint256 ind_ = 0; ind_ < amount_; ind_++) { _safeMint(msg.sender, totalSupply() + 1); supplyCounter.increment(); } }
614,589
/* * Copyright (C) 2018, Visible Energy Inc. and the Blockduino contributors. */ pragma solidity ^0.4.24; /// @title Blockduino SDK /// @notice The contract with the functions to interact with Blockduino boards /// @dev Communication off-chain with the board is through the Blockduino core contract // declarations of public core contract functions used by the SDK contract Blockduino { function request(address callbackAddr, bytes4 callbackFID, uint8 _method, address _device, uint8[2] _paramsIntegers, bytes32 _paramsBytes) public payable returns (int); function getDevice(address _addr) external constant returns (address, address, bool, bytes32); } contract usingBlockduinoSDK { address public contract_owner; Blockduino public CONTRACT; // -- START ------ RaspberryHAL // /// @devel pin numbering mnemonics using BCM mode /// symbols will have the numeric value of the mnemonic enum pin { D0, // pin 27 (ID_SD) D1, // pin 28 (ID_SC) D2, // pin 3 (SDA) D3, // pin 5 (SCL) D4, // pin 7 (GPCLK0) D5, // pin 29 D6, // pin 31 D7, // pin 26 (CE1) D8, // pin 24 (CE0) D9, // pin 21 (MISO) D10, // pin 19 (MOSI) D11, // pin 23 (SCLK) D12, // pin 32 (PWM0) D13, // pin 33 (PWM1) D14, // pin 8 (TXD) D15, // pin 10 (RXD) D16, // pin 36 D17, // pin 11 D18, // pin 12 (PWM0) D19, // pin 35 (MISO) D20, // pin 38 (MOSI) D21, // pin 40 (SCLK) D22, // pin 15 D23, // pin 16 D24, // pin 18 D25, // pin 22 D26, // pin 37 D27 // pin 13 } /* digital pins modes */ uint8 constant INPUT = 1; uint8 constant OUTPUT = 2; uint8 constant INPUT_PULLUP = 3; uint8 constant INPUT_PULLDOWN = 4; /* digital pins state values */ uint8 constant LOW = 0; uint8 HIGH = 1; // // -- END ------ RaspberryHAL /// @dev This contract is never deployed by itself but is always the base contract of an application /// @param bcCont the Blockduino core contract address /// @param owner the owner of the derived contract constructor (address bcCont, address owner) public { contract_owner = owner; CONTRACT = Blockduino(bcCont); } // RPC method names and numbering uint8 constant BD_pinMode = 1; uint8 constant BD_digitalRead = 2; uint8 constant BD_digitalWrite = 3; uint8 constant BD_pinToggle = 4; uint8 constant BD_serialRead = 5; uint8 constant BD_serialWrite = 6; // minimum gas required for a RPC uint constant MIN_GAS = 30000 + 20000; uint constant GAS_PRICE = 4 * 10 ** 10; uint constant BD_MINFEE = MIN_GAS * GAS_PRICE; // the FID of a null callback bytes4 constant CB_NULL = '0x0'; /// @dev modifier to restrict use of a function to the device owner /// @param _addr is the Blockduino device address modifier onlyByDeviceOwner(address _addr) { address device_owner; bool restricted; // obtain device details from the core contract (,device_owner, restricted,) = CONTRACT.getDevice(_addr); if (restricted) { require(device_owner == msg.sender, "Device registered to different owner"); } _; } // event used for tracing the SDK request to the Blockduino contract event BlockduinoSDK(uint8 _method, address _device, uint8[2] _paramsIntegers, bytes32 _paramsBytes); /// @dev propagate a RPC request to the core contract and log it for tracing function request(bytes4 callbackFID, uint8 _method, address _device, uint8[2] _paramsIntegers, bytes32 _paramsBytes) private returns(int) { int reply = 1; // send a transaction to the Blockduino core contract calling the Blockduino.request() function // reply = CONTRACT.request.gas(1000000)(this, callbackFID, _method, _device, _paramsIntegers, _paramsBytes); reply = CONTRACT.request.gas(BD_MINFEE)(this, callbackFID, _method, _device, _paramsIntegers, _paramsBytes); if (reply <= 0) { // let the caller issue a refund when appropriate return reply; } // TODO: save and use the reply that is actually a request ID for successful requests // log the SDK call emit BlockduinoSDK(_method, _device, _paramsIntegers, _paramsBytes); return reply; } /// @dev Set a GPIO pin mode /// @param _device the Blockduino device address /// @param _pin affected GPIO pin /// @param _mode new mode /// @param callbackFID the callback function ID function pinMode(address _device, pin _pin, uint8 _mode, bytes4 callbackFID) public payable onlyByDeviceOwner(_device) returns(int) { bytes32 rpc_params_bytes = '0x0'; uint8[2] memory rpc_params_int; int reply; rpc_params_int[1] = _mode; rpc_params_int[0] = uint8(_pin); // call the Blockduino contract with the RPC request reply = request(callbackFID, BD_pinMode, _device, rpc_params_int, rpc_params_bytes); return reply; } /// @dev Read the state of a digital pin /// @param _device the Blockduino device address /// @param _pin GPIO pin to read /// @param callbackFID the callback function ID function digitalRead(address _device, pin _pin, bytes4 callbackFID) public payable onlyByDeviceOwner(_device) returns(int) { bytes32 rpc_params_bytes = '0x0'; uint8[2] memory rpc_params_int; int reply; rpc_params_int[0] = uint8(_pin); // call the Blockduino contract with the RPC request reply = request(callbackFID, BD_digitalRead, _device, rpc_params_int, rpc_params_bytes); return reply; } /// @dev Write the state of a digital pin /// @param _device the Blockduino device address /// @param _pin GPIO pin to write /// @param _state the new state for the pin /// @param callbackFID the callback function ID function digitalWrite(address _device, pin _pin, uint8 _state, bytes4 callbackFID) public payable onlyByDeviceOwner(_device) returns(int) { bytes32 rpc_params_bytes = '0x0'; uint8[2] memory rpc_params_int; int reply; rpc_params_int[0] = uint8(_pin); rpc_params_int[1] = _state; // call the Blockduino contract with the RPC request reply = request(callbackFID, BD_digitalWrite, _device, rpc_params_int, rpc_params_bytes); return reply; } /// @dev Toggle the state of a digital pin /// @param _device the Blockduino device address /// @param _pin GPIO pin to toggle /// @param callbackFID the callback function ID function pinToggle(address _device, pin _pin, bytes4 callbackFID) public payable onlyByDeviceOwner(_device) returns(int) { bytes32 rpc_params_bytes = '0x0'; uint8[2] memory rpc_params_int; int reply; rpc_params_int[0] = uint8(_pin); // call the Blockduino contract with the RPC request reply = request(callbackFID, BD_pinToggle, _device, rpc_params_int, rpc_params_bytes); return reply; } /// @dev Read a single bytes32 buffer from the serial port /// @param _device the Blockduino device address /// @param _maxbytes number of bytes to read /// @param callbackFID the callback function ID function serialRead(address _device, uint8 _maxbytes, bytes4 callbackFID) public payable onlyByDeviceOwner(_device) returns(int) { bytes32 rpc_params_bytes = '0x0'; uint8[2] memory rpc_params_int; int reply; rpc_params_int[0] = uint8(_maxbytes); // call the Blockduino contract with the RPC request reply = request(callbackFID, BD_serialRead, _device, rpc_params_int, rpc_params_bytes); return reply; } /// @dev Write bytes from a single bytes32 buffer to the serial port /// @param _device the Blockduino device address /// @param _numbytes number of bytes to write /// @param _buffer the buffer to write /// @param callbackFID the callback function ID function serialWrite(address _device, uint8 _numbytes, bytes32 _buffer, bytes4 callbackFID) public payable onlyByDeviceOwner(_device) returns(int) { bytes32 rpc_params_bytes = _buffer; uint8[2] memory rpc_params_int; int reply; rpc_params_int[0] = uint8(_numbytes); // call the Blockduino contract with the RPC request reply = request(callbackFID, BD_serialWrite, _device, rpc_params_int, rpc_params_bytes); return reply; } }
propagate a RPC request to the core contract and log it for tracing send a transaction to the Blockduino core contract calling the Blockduino.request() function reply = CONTRACT.request.gas(1000000)(this, callbackFID, _method, _device, _paramsIntegers, _paramsBytes); let the caller issue a refund when appropriate
function request(bytes4 callbackFID, uint8 _method, address _device, uint8[2] _paramsIntegers, bytes32 _paramsBytes) private returns(int) { int reply = 1; reply = CONTRACT.request.gas(BD_MINFEE)(this, callbackFID, _method, _device, _paramsIntegers, _paramsBytes); if (reply <= 0) { return reply; } return reply; }
12,799,178
./full_match/4/0x4767dd7aD034c6Db23363ac9F32cDBD5449C3424/sources/contracts/mm/MMAssociation.sol
Allows the Association owner to change whether defi can be used./
function setDefiEnabled(bool enabled) public onlyOwner { require( defiImplementation != address(0), "Association: DeFi implementation not set." ); defiEnabled = enabled; }
674,051
// SPDX-License-Identifier: MIT // Copyright 2021 Primitive Finance // // 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.6.2; /** * @title Primitive Connector * @author Primitive * @notice Low-level abstract contract for Primitive Connectors to inherit from. * @dev @primitivefi/[email protected] */ // Open Zeppelin import {Context} from "@openzeppelin/contracts/GSN/Context.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // Primitive import {CoreLib, IOption} from "../libraries/CoreLib.sol"; import { IPrimitiveConnector, IPrimitiveRouter, IWETH } from "../interfaces/IPrimitiveConnector.sol"; abstract contract PrimitiveConnector is IPrimitiveConnector, Context { using SafeERC20 for IERC20; // Reverts when `transfer` or `transferFrom` erc20 calls don't return proper data IWETH internal _weth; // Canonical WETH9 IPrimitiveRouter internal _primitiveRouter; // The PrimitiveRouter contract which executes calls. mapping(address => mapping(address => bool)) internal _approved; // Stores approvals for future checks. // ===== Constructor ===== constructor(address weth_, address primitiveRouter_) public { _weth = IWETH(weth_); _primitiveRouter = IPrimitiveRouter(primitiveRouter_); checkApproval(weth_, primitiveRouter_); // Approves this contract's weth to be spent by router. } /** * @notice Reverts if the `option` is not registered in the PrimitiveRouter contract. * @dev Any `option` which is deployed from the Primitive Registry can be registered with the Router. * @param option The Primitive Option to check if registered. */ modifier onlyRegistered(IOption option) { require( _primitiveRouter.getRegisteredOption(address(option)), "PrimitiveSwaps: EVIL_OPTION" ); _; } // ===== External ===== /** * @notice Approves the `spender` to pull `token` from this contract. * @dev This contract does not hold funds, infinite approvals cannot be exploited for profit. * @param token The token to approve spending for. * @param spender The address to allow to spend `token`. */ function checkApproval(address token, address spender) public override returns (bool) { if (!_approved[token][spender]) { IERC20(token).safeApprove(spender, uint256(-1)); _approved[token][spender] = true; } return true; } // ===== Internal ===== /** * @notice Deposits `msg.value` into the Weth contract for Weth tokens. * @return Whether or not ether was deposited into Weth. */ function _depositETH() internal returns (bool) { if (msg.value > 0) { _weth.deposit.value(msg.value)(); return true; } return false; } /** * @notice Uses this contract's balance of Weth to withdraw Ether and send it to `getCaller()`. */ function _withdrawETH() internal returns (bool) { uint256 quantity = IERC20(address(_weth)).balanceOf(address(this)); if (quantity > 0) { // Withdraw ethers with weth. _weth.withdraw(quantity); // Send ether. (bool success, ) = getCaller().call.value(quantity)(""); // Revert is call is unsuccessful. require(success, "Connector: ERR_SENDING_ETHER"); return success; } return true; } /** * @notice Calls the Router to pull `token` from the getCaller() and send them to this contract. * @dev This eliminates the need for users to approve the Router and each connector. * @param token The token to pull from `getCaller()` into this contract. * @param quantity The amount of `token` to pull into this contract. * @return Whether or not the `token` was transferred into this contract. */ function _transferFromCaller(address token, uint256 quantity) internal returns (bool) { if (quantity > 0) { _primitiveRouter.transferFromCaller(token, quantity); return true; } return false; } /** * @notice Pushes this contract's balance of `token` to `getCaller()`. * @dev getCaller() is the original `msg.sender` of the Router's `execute` fn. * @param token The token to transfer to `getCaller()`. * @return Whether or not the `token` was transferred to `getCaller()`. */ function _transferToCaller(address token) internal returns (bool) { uint256 quantity = IERC20(token).balanceOf(address(this)); if (quantity > 0) { IERC20(token).safeTransfer(getCaller(), quantity); return true; } return false; } /** * @notice Calls the Router to pull `token` from the getCaller() and send them to this contract. * @dev This eliminates the need for users to approve the Router and each connector. * @param token The token to pull from `getCaller()`. * @param quantity The amount of `token` to pull. * @param receiver The `to` address to send `quantity` of `token` to. * @return Whether or not `token` was transferred to `receiver`. */ function _transferFromCallerToReceiver( address token, uint256 quantity, address receiver ) internal returns (bool) { if (quantity > 0) { _primitiveRouter.transferFromCallerToReceiver(token, quantity, receiver); return true; } return false; } /** * @notice Uses this contract's balance of underlyingTokens to mint optionTokens to this contract. * @param optionToken The Primitive Option to mint. * @return (uint, uint) (longOptions, shortOptions) */ function _mintOptions(IOption optionToken) internal returns (uint256, uint256) { address underlying = optionToken.getUnderlyingTokenAddress(); _transferBalanceToReceiver(underlying, address(optionToken)); // Sends to option contract return optionToken.mintOptions(address(this)); } /** * @notice Uses this contract's balance of underlyingTokens to mint optionTokens to `receiver`. * @param optionToken The Primitive Option to mint. * @param receiver The address that will received the minted long and short optionTokens. * @return (uint, uint) Returns the (long, short) option tokens minted */ function _mintOptionsToReceiver(IOption optionToken, address receiver) internal returns (uint256, uint256) { address underlying = optionToken.getUnderlyingTokenAddress(); _transferBalanceToReceiver(underlying, address(optionToken)); // Sends to option contract return optionToken.mintOptions(receiver); } /** * @notice Pulls underlying tokens from `getCaller()` to option contract, then invokes mintOptions(). * @param optionToken The option token to mint. * @param quantity The amount of option tokens to mint. * @return (uint, uint) Returns the (long, short) option tokens minted */ function _mintOptionsFromCaller(IOption optionToken, uint256 quantity) internal returns (uint256, uint256) { require(quantity > 0, "ERR_ZERO"); _transferFromCallerToReceiver( optionToken.getUnderlyingTokenAddress(), quantity, address(optionToken) ); return optionToken.mintOptions(address(this)); } /** * @notice Multi-step operation to close options. * 1. Transfer balanceOf `redeem` option token to the option contract. * 2. If NOT expired, pull `option` tokens from `getCaller()` and send to option contract. * 3. Invoke `closeOptions()` to burn the options and release underlyings to this contract. * @return The amount of underlyingTokens released to this contract. */ function _closeOptions(IOption optionToken) internal returns (uint256) { address redeem = optionToken.redeemToken(); uint256 short = IERC20(redeem).balanceOf(address(this)); uint256 long = IERC20(address(optionToken)).balanceOf(getCaller()); uint256 proportional = CoreLib.getProportionalShortOptions(optionToken, long); // IF user has more longs than proportional shorts, close the `short` amount. if (proportional > short) { proportional = short; } // If option is expired, transfer the amt of proportional thats larger. if (optionToken.getExpiryTime() >= now) { // Transfers the max proportional amount of short options to option contract. IERC20(redeem).safeTransfer(address(optionToken), proportional); // Pulls the max amount of long options and sends to option contract. _transferFromCallerToReceiver( address(optionToken), CoreLib.getProportionalLongOptions(optionToken, proportional), address(optionToken) ); } else { // If not expired, transfer all redeem in balance. IERC20(redeem).safeTransfer(address(optionToken), short); } uint outputUnderlyings; if(proportional > 0) { (, , outputUnderlyings) = optionToken.closeOptions(address(this)); } return outputUnderlyings; } /** * @notice Multi-step operation to exercise options. * 1. Transfer balanceOf `strike` token to option contract. * 2. Transfer `amount` of options to exercise to option contract. * 3. Invoke `exerciseOptions()` and specify `getCaller()` as the receiver. * @dev If the balanceOf `strike` and `amount` of options are not in correct proportions, call will fail. * @param optionToken The option to exercise. * @param amount The quantity of options to exercise. */ function _exerciseOptions(IOption optionToken, uint256 amount) internal returns (uint256, uint256) { address strike = optionToken.getStrikeTokenAddress(); _transferBalanceToReceiver(strike, address(optionToken)); IERC20(address(optionToken)).safeTransfer(address(optionToken), amount); return optionToken.exerciseOptions(getCaller(), amount, new bytes(0)); } /** * @notice Transfers this contract's balance of Redeem tokens and invokes the redemption function. * @param optionToken The optionToken to redeem, not the redeem token itself. */ function _redeemOptions(IOption optionToken) internal returns (uint256) { address redeem = optionToken.redeemToken(); _transferBalanceToReceiver(redeem, address(optionToken)); return optionToken.redeemStrikeTokens(getCaller()); } /** * @notice Utility function to transfer this contract's balance of `token` to `receiver`. * @param token The token to transfer. * @param receiver The address that receives the token. * @return Returns the quantity of `token` transferred. */ function _transferBalanceToReceiver(address token, address receiver) internal returns (uint256) { uint256 quantity = IERC20(token).balanceOf(address(this)); IERC20(token).safeTransfer(receiver, quantity); return quantity; } // ===== Fallback ===== receive() external payable { assert(_msgSender() == address(_weth)); // only accept ETH via fallback from the WETH contract } // ===== View ===== /** * @notice Returns the Weth contract address. */ function getWeth() public view override returns (IWETH) { return _weth; } /** * @notice Returns the state variable `_CALLER` in the Primitive Router. */ function getCaller() public view override returns (address) { return _primitiveRouter.getCaller(); } /** * @notice Returns the Primitive Router contract address. */ function getPrimitiveRouter() public view override returns (IPrimitiveRouter) { return _primitiveRouter; } /** * @notice Returns whether or not `spender` is approved to spend `token`, from this contract. */ function isApproved(address token, address spender) public view override returns (bool) { return _approved[token][spender]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for 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 // Copyright 2021 Primitive Finance // // 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.6.2; /** * @title Primitive Swaps Lib * @author Primitive * @notice Library for calculating different proportions of long and short option tokens. * @dev @primitivefi/[email protected] */ import {IOption} from "@primitivefi/contracts/contracts/option/interfaces/ITrader.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; library CoreLib { using SafeMath for uint256; // Reverts on math underflows/overflows /** * @dev Calculates the proportional quantity of long option tokens per short option token. * @notice For each long option token, there is quoteValue / baseValue quantity of short option tokens. * @param optionToken The Option to use to calculate proportional amounts. Each option has different proportions. * @param short The amount of short options used to calculate the proportional amount of long option tokens. * @return The proportional amount of long option tokens based on `short`. */ function getProportionalLongOptions(IOption optionToken, uint256 short) internal view returns (uint256) { return short.mul(optionToken.getBaseValue()).div(optionToken.getQuoteValue()); } /** * @dev Calculates the proportional quantity of short option tokens per long option token. * @notice For each short option token, there is baseValue / quoteValue quantity of long option tokens. * @param optionToken The Option to use to calculate proportional amounts. Each option has different proportions. * @param long The amount of long options used to calculate the proportional amount of short option tokens. * @return The proportional amount of short option tokens based on `long`. */ function getProportionalShortOptions(IOption optionToken, uint256 long) internal view returns (uint256) { return long.mul(optionToken.getQuoteValue()).div(optionToken.getBaseValue()); } // 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"); } } // SPDX-License-Identifier: MIT // Copyright 2021 Primitive Finance // // 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.6.2; import {IPrimitiveRouter} from "../interfaces/IPrimitiveRouter.sol"; import {IWETH} from "../interfaces/IWETH.sol"; interface IPrimitiveConnector { // ===== External ===== function checkApproval(address token, address spender) external returns (bool); // ===== View ===== function getWeth() external view returns (IWETH); function getCaller() external view returns (address); function getPrimitiveRouter() external view returns (IPrimitiveRouter); function isApproved(address token, address spender) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.2; import { IOption } from "./IOption.sol"; interface ITrader { function safeMint( IOption optionToken, uint256 mintQuantity, address receiver ) external returns (uint256, uint256); function safeExercise( IOption optionToken, uint256 exerciseQuantity, address receiver ) external returns (uint256, uint256); function safeRedeem( IOption optionToken, uint256 redeemQuantity, address receiver ) external returns (uint256); function safeClose( IOption optionToken, uint256 closeQuantity, address receiver ) external returns ( uint256, uint256, uint256 ); function safeUnwind( IOption optionToken, uint256 unwindQuantity, address receiver ) external returns ( uint256, uint256, uint256 ); } // SPDX-License-Identifier: MIT pragma solidity 0.6.2; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; interface IOption is IERC20 { function mintOptions(address receiver) external returns (uint256, uint256); function exerciseOptions( address receiver, uint256 outUnderlyings, bytes calldata data ) external returns (uint256, uint256); function redeemStrikeTokens(address receiver) external returns (uint256); function closeOptions(address receiver) external returns ( uint256, uint256, uint256 ); function redeemToken() external view returns (address); function getStrikeTokenAddress() external view returns (address); function getUnderlyingTokenAddress() external view returns (address); function getBaseValue() external view returns (uint256); function getQuoteValue() external view returns (uint256); function getExpiryTime() external view returns (uint256); function underlyingCache() external view returns (uint256); function strikeCache() external view returns (uint256); function factory() external view returns (address); function getCacheBalances() external view returns (uint256, uint256); function getAssetAddresses() external view returns ( address, address, address ); function getParameters() external view returns ( address _underlyingToken, address _strikeToken, address _redeemToken, uint256 _base, uint256 _quote, uint256 _expiry ); function initRedeemToken(address _redeemToken) external; function updateCacheBalances() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {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 internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT // Copyright 2021 Primitive Finance // // 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.6.2; import { IOption, IERC20 } from "@primitivefi/contracts/contracts/option/interfaces/IOption.sol"; import { IRegistry } from "@primitivefi/contracts/contracts/option/interfaces/IRegistry.sol"; import {IWETH} from "./IWETH.sol"; interface IPrimitiveRouter { // ===== Admin ===== function halt() external; // ===== Registration ===== function setRegisteredOptions(address[] calldata optionAddresses) external returns (bool); function setRegisteredConnectors( address[] calldata connectors, bool[] calldata isValid ) external returns (bool); // ===== Operations ===== function transferFromCaller(address token, uint256 amount) external returns (bool); function transferFromCallerToReceiver( address token, uint256 amount, address receiver ) external returns (bool); // ===== Execution ===== function executeCall(address connector, bytes calldata params) external payable; // ==== View ==== function getWeth() external view returns (IWETH); function getRoute() external view returns (address); function getCaller() external view returns (address); function getRegistry() external view returns (IRegistry); function getRegisteredOption(address option) external view returns (bool); function getRegisteredConnector(address connector) external view returns (bool); function apiVersion() external pure returns (string memory); } // SPDX-License-Identifier: MIT // Copyright 2021 Primitive Finance // // 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.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.2; interface IRegistry { function pauseDeployments() external; function unpauseDeployments() external; function deployOption( address underlyingToken, address strikeToken, uint256 base, uint256 quote, uint256 expiry ) external returns (address); function setOptionFactory(address optionFactory_) external; function setRedeemFactory(address redeemFactory_) external; function optionFactory() external returns (address); function redeemFactory() external returns (address); function verifyToken(address tokenAddress) external; function verifyExpiry(uint256 expiry) external; function unverifyToken(address tokenAddress) external; function unverifyExpiry(uint256 expiry) external; function calculateOptionAddress( address underlyingToken, address strikeToken, uint256 base, uint256 quote, uint256 expiry ) external view returns (address); function getOptionAddress( address underlyingToken, address strikeToken, uint256 base, uint256 quote, uint256 expiry ) external view returns (address); function isVerifiedOption(address optionAddress) external view returns (bool); } // SPDX-License-Identifier: MIT // Copyright 2021 Primitive Finance // // 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.6.2; /** * @title Primitive Connector TEST * @author Primitive * @notice Low-level abstract contract for Primitive Connectors to inherit from. * @dev @primitivefi/[email protected] */ import {PrimitiveConnector, IOption} from "../connectors/PrimitiveConnector.sol"; contract ConnectorTest is PrimitiveConnector { event Log(address indexed caller); constructor(address weth_, address primitiveRouter_) public PrimitiveConnector(weth_, primitiveRouter_) {} function depositETH() external payable returns (bool) { emit Log(getCaller()); return _depositETH(); } function withdrawETH() external returns (bool) { emit Log(getCaller()); return _withdrawETH(); } function transferFromCaller(address token, uint256 quantity) external returns (bool) { emit Log(getCaller()); return _transferFromCaller(token, quantity); } function transferToCaller(address token) external returns (bool) { emit Log(getCaller()); return _transferToCaller(token); } function transferFromCallerToReceiver( address token, uint256 quantity, address receiver ) external returns (bool) { emit Log(getCaller()); return _transferFromCallerToReceiver(token, quantity, receiver); } function mintOptions(IOption optionToken, uint256 quantity) external returns (uint256, uint256) { emit Log(getCaller()); _transferFromCaller(optionToken.getUnderlyingTokenAddress(), quantity); return _mintOptions(optionToken); } function mintOptionsToReceiver( IOption optionToken, uint256 quantity, address receiver ) external returns (uint256, uint256) { emit Log(getCaller()); _transferFromCaller(optionToken.getUnderlyingTokenAddress(), quantity); return _mintOptionsToReceiver(optionToken, receiver); } function mintOptionsFromCaller(IOption optionToken, uint256 quantity) external returns (uint256, uint256) { emit Log(getCaller()); return _mintOptionsFromCaller(optionToken, quantity); } function closeOptions(IOption optionToken, uint256 short) external returns (uint256) { emit Log(getCaller()); _transferFromCaller(optionToken.redeemToken(), short); return _closeOptions(optionToken); } function exerciseOptions( IOption optionToken, uint256 amount, uint256 strikeAmount ) external returns (uint256, uint256) { _transferFromCaller(optionToken.getStrikeTokenAddress(), strikeAmount); _transferFromCaller(address(optionToken), amount); emit Log(getCaller()); return _exerciseOptions(optionToken, amount); } function redeemOptions(IOption optionToken, uint256 short) external returns (uint256) { _transferFromCaller(optionToken.redeemToken(), short); emit Log(getCaller()); return _redeemOptions(optionToken); } function transferBalanceToReceiver(address token, address receiver) external returns (uint256) { emit Log(getCaller()); return _transferBalanceToReceiver(token, receiver); } } // SPDX-License-Identifier: MIT // Copyright 2021 Primitive Finance // // 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.6.2; /** * @title Primitive Router * @author Primitive * @notice Swap option tokens on Uniswap & Sushiswap venues. * @dev @primitivefi/[email protected] */ // Open Zeppelin import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; // Uniswap import { IUniswapV2Callee } from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Callee.sol"; // Primitive import { IPrimitiveSwaps, IUniswapV2Router02, IUniswapV2Factory, IUniswapV2Pair, IOption, IERC20Permit } from "../interfaces/IPrimitiveSwaps.sol"; import {PrimitiveConnector} from "./PrimitiveConnector.sol"; import {SwapsLib, SafeMath} from "../libraries/SwapsLib.sol"; interface DaiPermit { function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) external; } contract PrimitiveSwaps is PrimitiveConnector, IPrimitiveSwaps, IUniswapV2Callee, ReentrancyGuard { using SafeERC20 for IERC20; // Reverts when `transfer` or `transferFrom` erc20 calls don't return proper data using SafeMath for uint256; // Reverts on math underflows/overflows event Initialized(address indexed from); // Emitted on deployment. event Buy( address indexed from, address indexed option, uint256 quantity, uint256 premium ); event Sell( address indexed from, address indexed option, uint256 quantity, uint256 payout ); IUniswapV2Factory private _factory; // The Uniswap V2 _factory contract to get pair addresses from IUniswapV2Router02 private _router; // The Uniswap contract used to interact with the protocol modifier onlySelf() { require(_msgSender() == address(this), "PrimitiveSwaps: NOT_SELF"); _; } // ===== Constructor ===== constructor( address weth_, address primitiveRouter_, address factory_, address router_ ) public PrimitiveConnector(weth_, primitiveRouter_) { _factory = IUniswapV2Factory(factory_); _router = IUniswapV2Router02(router_); emit Initialized(_msgSender()); } // ===== Swap Operations ===== /** * @notice IMPORTANT: amountOutMin parameter is the price to swap shortOptionTokens to underlyingTokens. * IMPORTANT: If the ratio between shortOptionTokens and underlyingTokens is 1:1, then only the swap fee (0.30%) has to be paid. * @dev Opens a longOptionToken position by minting long + short tokens, then selling the short tokens. * @param optionToken The option address. * @param amountOptions The quantity of longOptionTokens to purchase. * @param maxPremium The maximum quantity of underlyingTokens to pay for the optionTokens. * @return Whether or not the call succeeded. */ function openFlashLong( IOption optionToken, uint256 amountOptions, uint256 maxPremium ) public override nonReentrant onlyRegistered(optionToken) returns (bool) { // Calls pair.swap(), and executes `flashMintShortOptionsThenSwap` in the `uniswapV2Callee` callback. (IUniswapV2Pair pair, address underlying, ) = getOptionPair(optionToken); SwapsLib._flashSwap( pair, // Pair to flash swap from. underlying, // Token to swap to, i.e. receive optimistically. amountOptions, // Amount of underlying to optimistically receive to mint options with. abi.encodeWithSelector( // Start: Function to call in the callback. bytes4( keccak256( bytes("flashMintShortOptionsThenSwap(address,uint256,uint256)") ) ), optionToken, // Option token to mint with flash loaned tokens. amountOptions, // Quantity of underlyingTokens from flash loan to use to mint options. maxPremium // Total price paid (in underlyingTokens) for selling shortOptionTokens. ) // End: Function to call in the callback. ); return true; } /** * @notice Executes the same as `openFlashLong`, but calls `permit` to pull underlying tokens. */ function openFlashLongWithPermit( IOption optionToken, uint256 amountOptions, uint256 maxPremium, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public override nonReentrant onlyRegistered(optionToken) returns (bool) { // Calls pair.swap(), and executes `flashMintShortOptionsThenSwap` in the `uniswapV2Callee` callback. (IUniswapV2Pair pair, address underlying, ) = getOptionPair(optionToken); IERC20Permit(underlying).permit( getCaller(), address(_primitiveRouter), maxPremium, deadline, v, r, s ); SwapsLib._flashSwap( pair, // Pair to flash swap from. underlying, // Token to swap to, i.e. receive optimistically. amountOptions, // Amount of underlying to optimistically receive to mint options with. abi.encodeWithSelector( // Start: Function to call in the callback. bytes4( keccak256( bytes("flashMintShortOptionsThenSwap(address,uint256,uint256)") ) ), optionToken, // Option token to mint with flash loaned tokens. amountOptions, // Quantity of underlyingTokens from flash loan to use to mint options. maxPremium // Total price paid (in underlyingTokens) for selling shortOptionTokens. ) // End: Function to call in the callback. ); return true; } /** * @notice Executes the same as `openFlashLongWithPermit`, but for DAI. */ function openFlashLongWithDAIPermit( IOption optionToken, uint256 amountOptions, uint256 maxPremium, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public override nonReentrant onlyRegistered(optionToken) returns (bool) { // Calls pair.swap(), and executes `flashMintShortOptionsThenSwap` in the `uniswapV2Callee` callback. (IUniswapV2Pair pair, address underlying, ) = getOptionPair(optionToken); DaiPermit(underlying).permit( getCaller(), address(_primitiveRouter), IERC20Permit(underlying).nonces(getCaller()), deadline, true, v, r, s ); SwapsLib._flashSwap( pair, // Pair to flash swap from. underlying, // Token to swap to, i.e. receive optimistically. amountOptions, // Amount of underlying to optimistically receive to mint options with. abi.encodeWithSelector( // Start: Function to call in the callback. bytes4( keccak256( bytes("flashMintShortOptionsThenSwap(address,uint256,uint256)") ) ), optionToken, // Option token to mint with flash loaned tokens. amountOptions, // Quantity of underlyingTokens from flash loan to use to mint options. maxPremium // Total price paid (in underlyingTokens) for selling shortOptionTokens. ) // End: Function to call in the callback. ); return true; } /** * @notice Uses Ether to pay to purchase the option tokens. * IMPORTANT: amountOutMin parameter is the price to swap shortOptionTokens to underlyingTokens. * IMPORTANT: If the ratio between shortOptionTokens and underlyingTokens is 1:1, then only the swap fee (0.30%) has to be paid. * @dev Opens a longOptionToken position by minting long + short tokens, then selling the short tokens. * @param optionToken The option address. * @param amountOptions The quantity of longOptionTokens to purchase. */ function openFlashLongWithETH(IOption optionToken, uint256 amountOptions) external payable override nonReentrant onlyRegistered(optionToken) returns (bool) { require(msg.value > 0, "PrimitiveSwaps: ZERO"); // Fail early if no Ether was sent. // Calls pair.swap(), and executes `flashMintShortOptionsThenSwap` in the `uniswapV2Callee` callback. (IUniswapV2Pair pair, address underlying, ) = getOptionPair(optionToken); SwapsLib._flashSwap( pair, // Pair to flash swap from. underlying, // Token to swap to, i.e. receive optimistically. amountOptions, // Amount of underlying to optimistically receive to mint options with. abi.encodeWithSelector( // Start: Function to call in the callback. bytes4( keccak256( bytes( "flashMintShortOptionsThenSwapWithETH(address,uint256,uint256)" ) ) ), optionToken, // Option token to mint with flash loaned tokens amountOptions, // Quantity of underlyingTokens from flash loan to use to mint options. msg.value // total price paid (in underlyingTokens) for selling shortOptionTokens. ) // End: Function to call in the callback. ); return true; } /** * @dev Closes a longOptionToken position by flash swapping in redeemTokens, * closing the option, and paying back in underlyingTokens. * @notice IMPORTANT: If minPayout is 0, this function will cost the caller to close the option, for no gain. * @param optionToken The address of the longOptionTokens to close. * @param amountRedeems The quantity of redeemTokens to borrow to close the options. * @param minPayout The minimum payout of underlyingTokens sent out to the user. */ function closeFlashLong( IOption optionToken, uint256 amountRedeems, uint256 minPayout ) external override nonReentrant onlyRegistered(optionToken) returns (bool) { // Calls pair.swap(), and executes `flashCloseLongOptionsThenSwap` in the `uniswapV2Callee` callback. (IUniswapV2Pair pair, , address redeem) = getOptionPair(optionToken); SwapsLib._flashSwap( pair, // Pair to flash swap from. redeem, // Token to swap to, i.e. receive optimistically. amountRedeems, // Amount of underlying to optimistically receive to close options with. abi.encodeWithSelector( // Start: Function to call in the callback. bytes4( keccak256( bytes("flashCloseLongOptionsThenSwap(address,uint256,uint256)") ) ), optionToken, // Option token to close with flash loaned redeemTokens. amountRedeems, // Quantity of redeemTokens from flash loan to use to close options. minPayout // Total remaining underlyingTokens after flash loan is paid. ) // End: Function to call in the callback. ); return true; } /** * @dev Closes a longOptionToken position by flash swapping in redeemTokens, * closing the option, and paying back in underlyingTokens. * @notice IMPORTANT: If minPayout is 0, this function will cost the caller to close the option, for no gain. * @param optionToken The address of the longOptionTokens to close. * @param amountRedeems The quantity of redeemTokens to borrow to close the options. * @param minPayout The minimum payout of underlyingTokens sent out to the user. */ function closeFlashLongForETH( IOption optionToken, uint256 amountRedeems, uint256 minPayout ) external override nonReentrant onlyRegistered(optionToken) returns (bool) { // Calls pair.swap(), and executes `flashCloseLongOptionsThenSwapForETH` in the `uniswapV2Callee` callback. (IUniswapV2Pair pair, , address redeem) = getOptionPair(optionToken); SwapsLib._flashSwap( pair, // Pair to flash swap from. redeem, // Token to swap to, i.e. receive optimistically. amountRedeems, // Amount of underlying to optimistically receive to close options with. abi.encodeWithSelector( // Start: Function to call in the callback. bytes4( keccak256( bytes( "flashCloseLongOptionsThenSwapForETH(address,uint256,uint256)" ) ) ), optionToken, // Option token to close with flash loaned redeemTokens. amountRedeems, // Quantity of redeemTokens from flash loan to use to close options. minPayout // Total remaining underlyingTokens after flash loan is paid. ) // End: Function to call in the callback. ); return true; } // ===== Flash Callback Functions ===== /** * @notice Callback function executed in a UniswapV2Pair.swap() call for `openFlashLong`. * @dev Pays underlying token `premium` for `quantity` of `optionAddress` tokens. * @param optionAddress The address of the Option contract. * @param quantity The quantity of options to mint using borrowed underlyingTokens. * @param maxPremium The maximum quantity of underlyingTokens to pay for the optionTokens. * @return Returns (amount, premium) of options purchased for total premium price. */ function flashMintShortOptionsThenSwap( address optionAddress, uint256 quantity, uint256 maxPremium ) public onlySelf onlyRegistered(IOption(optionAddress)) returns (uint256, uint256) { IOption optionToken = IOption(optionAddress); (IUniswapV2Pair pair, address underlying, address redeem) = getOptionPair(optionToken); // Mint option and redeem tokens to this contract. _mintOptions(optionToken); // Get the repayment amounts. (uint256 premium, uint256 redeemPremium) = SwapsLib.repayOpen(_router, optionToken, quantity); // If premium is non-zero and non-negative (most cases), send underlyingTokens to the pair as payment (premium). if (premium > 0) { // Check for users to not pay over their max desired value. require(maxPremium >= premium, "PrimitiveSwaps: MAX_PREMIUM"); // Pull underlyingTokens from the `getCaller()` to pay the remainder of the flash swap. // Push underlying tokens back to the pair as repayment. _transferFromCallerToReceiver(underlying, premium, address(pair)); } // Pay pair in redeem tokens. if (redeemPremium > 0) { IERC20(redeem).safeTransfer(address(pair), redeemPremium); } // Return tokens to `getCaller()`. _transferToCaller(redeem); _transferToCaller(optionAddress); emit Buy(getCaller(), optionAddress, quantity, premium); return (quantity, premium); } /** * @notice Callback function executed in a UniswapV2Pair.swap() call for `openFlashLongWithETH`. * @dev Pays `premium` in ether for `quantity` of `optionAddress` tokens. * @param optionAddress The address of the Option contract. * @param quantity The quantity of options to mint using borrowed underlyingTokens. * @param maxPremium The maximum quantity of underlyingTokens to pay for the optionTokens. * @return Returns (amount, premium) of options purchased for total premium price. */ function flashMintShortOptionsThenSwapWithETH( address optionAddress, uint256 quantity, uint256 maxPremium ) public onlySelf onlyRegistered(IOption(optionAddress)) returns (uint256, uint256) { IOption optionToken = IOption(optionAddress); (IUniswapV2Pair pair, address underlying, address redeem) = getOptionPair(optionToken); require(underlying == address(_weth), "PrimitiveSwaps: NOT_WETH"); // Ensure Weth Call. // Mint option and redeem tokens to this contract. _mintOptions(optionToken); // Get the repayment amounts. (uint256 premium, uint256 redeemPremium) = SwapsLib.repayOpen(_router, optionToken, quantity); // If premium is non-zero and non-negative (most cases), send underlyingTokens to the pair as payment (premium). if (premium > 0) { // Check for users to not pay over their max desired value. require(maxPremium >= premium, "PrimitiveSwaps: MAX_PREMIUM"); // Wrap exact Ether amount of `premium`. _weth.deposit.value(premium)(); // Transfer Weth to pair to pay for premium. IERC20(address(_weth)).safeTransfer(address(pair), premium); // Return remaining Ether to caller. _withdrawETH(); } // Pay pair in redeem. if (redeemPremium > 0) { IERC20(redeem).safeTransfer(address(pair), redeemPremium); } // Return tokens to `getCaller()`. _transferToCaller(redeem); _transferToCaller(optionAddress); emit Buy(getCaller(), optionAddress, quantity, premium); return (quantity, premium); } /** * @dev Sends shortOptionTokens to _msgSender(), and pays back the UniswapV2Pair in underlyingTokens. * @notice IMPORTANT: If minPayout is 0, the `to` address is liable for negative payouts *if* that occurs. * @param optionAddress The address of the longOptionTokes to close. * @param flashLoanQuantity The quantity of shortOptionTokens borrowed to use to close longOptionTokens. * @param minPayout The minimum payout of underlyingTokens sent to the `to` address. */ function flashCloseLongOptionsThenSwap( address optionAddress, uint256 flashLoanQuantity, uint256 minPayout ) public onlySelf onlyRegistered(IOption(optionAddress)) returns (uint256, uint256) { IOption optionToken = IOption(optionAddress); (IUniswapV2Pair pair, address underlying, address redeem) = getOptionPair(optionToken); // Close the options, releasing underlying tokens to this contract. uint256 outputUnderlyings = _closeOptions(optionToken); // Get repay amounts. (uint256 payout, uint256 cost, uint256 outstanding) = SwapsLib.repayClose(_router, optionToken, flashLoanQuantity); if (payout > 0) { cost = outputUnderlyings.sub(payout); } // Pay back the pair in underlyingTokens. if (cost > 0) { IERC20(underlying).safeTransfer(address(pair), cost); } if (outstanding > 0) { // Pull underlyingTokens from the `getCaller()` to pay the remainder of the flash swap. // Revert if the minPayout is less than or equal to the underlyingPayment of 0. // There is 0 underlyingPayment in the case that outstanding > 0. // This code branch can be successful by setting `minPayout` to 0. // This means the user is willing to pay to close the position. require(minPayout <= payout, "PrimitiveSwaps: NEGATIVE_PAYOUT"); _transferFromCallerToReceiver(underlying, outstanding, address(pair)); } // If payout is non-zero and non-negative, send it to the `getCaller()` address. if (payout > 0) { // Revert if minPayout is greater than the actual payout. require(payout >= minPayout, "PrimitiveSwaps: MIN_PREMIUM"); _transferToCaller(underlying); } emit Sell(getCaller(), optionAddress, flashLoanQuantity, payout); return (payout, cost); } /** * @dev Sends shortOptionTokens to _msgSender(), and pays back the UniswapV2Pair in underlyingTokens. * @notice IMPORTANT: If minPayout is 0, the `getCaller()` address is liable for negative payouts *if* that occurs. * @param optionAddress The address of the longOptionTokes to close. * @param flashLoanQuantity The quantity of shortOptionTokens borrowed to use to close longOptionTokens. * @param minPayout The minimum payout of underlyingTokens sent to the `to` address. */ function flashCloseLongOptionsThenSwapForETH( address optionAddress, uint256 flashLoanQuantity, uint256 minPayout ) public onlySelf onlyRegistered(IOption(optionAddress)) returns (uint256, uint256) { IOption optionToken = IOption(optionAddress); (IUniswapV2Pair pair, address underlying, address redeem) = getOptionPair(optionToken); require(underlying == address(_weth), "PrimitiveSwaps: NOT_WETH"); // Close the options, releasing underlying tokens to this contract. _closeOptions(optionToken); // Get repay amounts. (uint256 payout, uint256 cost, uint256 outstanding) = SwapsLib.repayClose(_router, optionToken, flashLoanQuantity); // Pay back the pair in underlyingTokens. if (cost > 0) { IERC20(underlying).safeTransfer(address(pair), cost); } if (outstanding > 0) { // Pull underlyingTokens from the `getCaller()` to pay the remainder of the flash swap. // Revert if the minPayout is less than or equal to the underlyingPayment of 0. // There is 0 underlyingPayment in the case that outstanding > 0. // This code branch can be successful by setting `minPayout` to 0. // This means the user is willing to pay to close the position. require(minPayout <= payout, "PrimitiveSwaps: NEGATIVE_PAYOUT"); _transferFromCallerToReceiver(underlying, outstanding, address(pair)); } // If payout is non-zero and non-negative, send it to the `getCaller()` address. if (payout > 0) { // Revert if minPayout is greater than the actual payout. require(payout >= minPayout, "PrimitiveSwaps: MIN_PREMIUM"); _withdrawETH(); // Unwrap's this contract's balance of Weth and sends Ether to `getCaller()`. } emit Sell(getCaller(), optionAddress, flashLoanQuantity, payout); return (payout, cost); } // ===== Flash Loans ===== /** * @dev The callback function triggered in a UniswapV2Pair.swap() call when the `data` parameter has data. * @param sender The original _msgSender() of the UniswapV2Pair.swap() call. * @param amount0 The quantity of token0 received to the `to` address in the swap() call. * @param amount1 The quantity of token1 received to the `to` address in the swap() call. * @param data The payload passed in the `data` parameter of the swap() call. */ function uniswapV2Call( address sender, uint256 amount0, uint256 amount1, bytes calldata data ) external override(IPrimitiveSwaps, IUniswapV2Callee) { assert( _msgSender() == _factory.getPair( IUniswapV2Pair(_msgSender()).token0(), IUniswapV2Pair(_msgSender()).token1() ) ); // Ensure that _msgSender() is actually a V2 pair. require(sender == address(this), "PrimitiveSwaps: NOT_SENDER"); // Ensure called by this contract. (bool success, bytes memory returnData) = address(this).call(data); // Execute the callback. (uint256 amountA, uint256 amountB) = abi.decode(returnData, (uint256, uint256)); require( success && (returnData.length == 0 || amountA > 0 || amountB > 0), "PrimitiveSwaps: CALLBACK" ); } // ===== View ===== /** * @notice Gets the UniswapV2Router02 contract address. */ function getRouter() public view override returns (IUniswapV2Router02) { return _router; } /** * @notice Gets the UniswapV2Factory contract address. */ function getFactory() public view override returns (IUniswapV2Factory) { return _factory; } /** * @notice Fetchs the Uniswap Pair for an option's redeemToken and underlyingToken params. * @param option The option token to get the corresponding UniswapV2Pair market. * @return The pair address, as well as the tokens of the pair. */ function getOptionPair(IOption option) public view override returns ( IUniswapV2Pair, address, address ) { address redeem = option.redeemToken(); address underlying = option.getUnderlyingTokenAddress(); IUniswapV2Pair pair = IUniswapV2Pair(_factory.getPair(redeem, underlying)); return (pair, underlying, redeem); } /** * @dev Calculates the effective premium, denominated in underlyingTokens, to buy `quantity` of `optionToken`s. * @notice UniswapV2 adds a 0.3009027% fee which is applied to the premium as 0.301%. * IMPORTANT: If the pair's reserve ratio is incorrect, there could be a 'negative' premium. * Buying negative premium options will pay out redeemTokens. * An 'incorrect' ratio occurs when the (reserves of redeemTokens / strike ratio) >= reserves of underlyingTokens. * Implicitly uses the `optionToken`'s underlying and redeem tokens for the pair. * @param optionToken The optionToken to get the premium cost of purchasing. * @param quantity The quantity of long option tokens that will be purchased. * @return (uint, uint) Returns the `premium` to buy `quantity` of `optionToken` and the `negativePremium`. */ function getOpenPremium(IOption optionToken, uint256 quantity) public view override returns (uint256, uint256) { return SwapsLib.getOpenPremium(_router, optionToken, quantity); } /** * @dev Calculates the effective premium, denominated in underlyingTokens, to sell `optionToken`s. * @param optionToken The optionToken to get the premium cost of purchasing. * @param quantity The quantity of short option tokens that will be closed. * @return (uint, uint) Returns the `premium` to sell `quantity` of `optionToken` and the `negativePremium`. */ function getClosePremium(IOption optionToken, uint256 quantity) public view override returns (uint256, uint256) { return SwapsLib.getClosePremium(_router, optionToken, quantity); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } pragma solidity >=0.5.0; interface IUniswapV2Callee { function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external; } // SPDX-License-Identifier: MIT // Copyright 2021 Primitive Finance // // 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.6.2; import { IUniswapV2Router02 } from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import { IUniswapV2Factory } from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import {IUniswapV2Pair} from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import {IOption} from "@primitivefi/contracts/contracts/option/interfaces/IOption.sol"; import {IERC20Permit} from "./IERC20Permit.sol"; interface IPrimitiveSwaps { // ==== External Functions ==== function openFlashLong( IOption optionToken, uint256 amountOptions, uint256 maxPremium ) external returns (bool); function openFlashLongWithPermit( IOption optionToken, uint256 amountOptions, uint256 maxPremium, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external returns (bool); function openFlashLongWithDAIPermit( IOption optionToken, uint256 amountOptions, uint256 maxPremium, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external returns (bool); function openFlashLongWithETH(IOption optionToken, uint256 amountOptions) external payable returns (bool); function closeFlashLong( IOption optionToken, uint256 amountRedeems, uint256 minPayout ) external returns (bool); function closeFlashLongForETH( IOption optionToken, uint256 amountRedeems, uint256 minPayout ) external returns (bool); // ===== Callback ===== function uniswapV2Call( address sender, uint256 amount0, uint256 amount1, bytes calldata data ) external; // ==== View ==== function getRouter() external view returns (IUniswapV2Router02); function getFactory() external view returns (IUniswapV2Factory); function getOptionPair(IOption option) external view returns ( IUniswapV2Pair, address, address ); function getOpenPremium(IOption optionToken, uint256 quantity) external view returns (uint256, uint256); function getClosePremium(IOption optionToken, uint256 quantity) external view returns (uint256, uint256); } // SPDX-License-Identifier: MIT // Copyright 2021 Primitive Finance // // 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.6.2; /** * @title Primitive Swaps Lib * @author Primitive * @notice Library for Swap Logic for Uniswap AMM. * @dev @primitivefi/[email protected] */ import { IUniswapV2Router02 } from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import {IUniswapV2Pair} from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import {CoreLib, IOption, SafeMath} from "./CoreLib.sol"; library SwapsLib { using SafeMath for uint256; // Reverts on math underflows/overflows /** * @notice Passes in `params` to the UniswapV2Pair.swap() function to trigger the callback. * @param pair The Uniswap Pair to call. * @param token The token in the Pair to swap to, and thus optimistically receive. * @param amount The quantity of `token`s to optimistically receive first. * @param params The data to call from this contract, using the `uniswapV2Callee` callback. * @return Whether or not the swap() call suceeded. */ function _flashSwap( IUniswapV2Pair pair, address token, uint256 amount, bytes memory params ) internal returns (bool) { // Receives `amount` of `token` to this contract address. uint256 amount0Out = pair.token0() == token ? amount : 0; uint256 amount1Out = pair.token0() == token ? 0 : amount; // Execute the callback function in params. pair.swap(amount0Out, amount1Out, address(this), params); return true; } /** * @notice Gets the amounts to pay out, pay back, and outstanding cost. * @param router The UniswapV2Router02 to use for calculating `amountsOut`. * @param optionToken The option token to use for fetching its corresponding Uniswap Pair. * @param redeemAmount The quantity of REDEEM tokens, with `quoteValue` units, needed to close the options. */ function repayClose( IUniswapV2Router02 router, IOption optionToken, uint256 redeemAmount ) internal view returns ( uint256, uint256, uint256 ) { // Outstanding is the cost remaining, should be 0 in most cases. // Payout is the `premium` that the original caller receives in underlyingTokens. (uint256 payout, uint256 outstanding) = getClosePremium(router, optionToken, redeemAmount); // In most cases there will be an underlying payout, which is subtracted from the redeemAmount. uint256 cost = CoreLib.getProportionalLongOptions(optionToken, redeemAmount); if (payout > 0) { cost = cost.sub(payout); } return (payout, cost, outstanding); } /** * @notice Returns the swap amounts required to return to repay the flash loan used to open a long position. * @param router The UniswapV2Router02 to use for calculating `amountsOut`. * @param optionToken The option token to use for fetching its corresponding Uniswap Pair. * @param underlyingAmount The quantity of UNDERLYING tokens, with `baseValue` units, needed to open the options. */ function repayOpen( IUniswapV2Router02 router, IOption optionToken, uint256 underlyingAmount ) internal view returns (uint256, uint256) { // Premium is the `underlyingTokens` required to buy the `optionToken`. // ExtraRedeems is the `redeemTokens` that are remaining. // If `premium` is not 0, `extraRedeems` should be 0, else `extraRedeems` is the payout (a negative premium). (uint256 premium, uint256 extraRedeems) = getOpenPremium(router, optionToken, underlyingAmount); uint256 redeemPremium = CoreLib.getProportionalShortOptions(optionToken, underlyingAmount); if (extraRedeems > 0) { redeemPremium = redeemPremium.sub(extraRedeems); } return (premium, redeemPremium); } /** * @dev Calculates the effective premium, denominated in underlyingTokens, to buy `quantity` of `optionToken`s. * @notice UniswapV2 adds a 0.3009027% fee which is applied to the premium as 0.301%. * IMPORTANT: If the pair's reserve ratio is incorrect, there could be a 'negative' premium. * Buying negative premium options will pay out redeemTokens. * An 'incorrect' ratio occurs when the (reserves of redeemTokens / strike ratio) >= reserves of underlyingTokens. * Implicitly uses the `optionToken`'s underlying and redeem tokens for the pair. * @param router The UniswapV2Router02 contract. * @param optionToken The optionToken to get the premium cost of purchasing. * @param quantity The quantity of long option tokens that will be purchased. */ function getOpenPremium( IUniswapV2Router02 router, IOption optionToken, uint256 quantity ) internal view returns ( /* override */ uint256, uint256 ) { // longOptionTokens are opened by doing a swap from redeemTokens to underlyingTokens effectively. address[] memory path = new address[](2); path[0] = optionToken.redeemToken(); path[1] = optionToken.getUnderlyingTokenAddress(); // `quantity` of underlyingTokens are output from the swap. // They are used to mint options, which will mint `quantity` * quoteValue / baseValue amount of redeemTokens. uint256 redeemsMinted = CoreLib.getProportionalShortOptions(optionToken, quantity); // The loanRemainderInUnderlyings will be the amount of underlyingTokens that are needed from the original // transaction caller in order to pay the flash swap. // IMPORTANT: THIS IS EFFECTIVELY THE PREMIUM PAID IN UNDERLYINGTOKENS TO PURCHASE THE OPTIONTOKEN. uint256 loanRemainderInUnderlyings; // Economically, negativePremiumPaymentInRedeems value should always be 0. // In the case that we minted more redeemTokens than are needed to pay back the flash swap, // (short -> underlying is a positive trade), there is an effective negative premium. // In that case, this function will send out `negativePremiumAmount` of redeemTokens to the original caller. // This means the user gets to keep the extra redeemTokens for free. // Negative premium amount is the opposite difference of the loan remainder: (paid - flash loan amount) uint256 negativePremiumPaymentInRedeems; // Since the borrowed amount is underlyingTokens, and we are paying back in redeemTokens, // we need to see how much redeemTokens must be returned for the borrowed amount. // We can find that value by doing the normal swap math, getAmountsIn will give us the amount // of redeemTokens are needed for the output amount of the flash loan. // IMPORTANT: amountsIn[0] is how many short tokens we need to pay back. // This value is most likely greater than the amount of redeemTokens minted. uint256[] memory amountsIn = router.getAmountsIn(quantity, path); uint256 redeemsRequired = amountsIn[0]; // the amountIn of redeemTokens based on the amountOut of `quantity`. // If redeemsMinted is greater than redeems required, there is a cost of 0, implying a negative premium. uint256 redeemCostRemaining = redeemsRequired > redeemsMinted ? redeemsRequired.sub(redeemsMinted) : 0; // If there is a negative premium, calculate the quantity of remaining redeemTokens after the `redeemsMinted` is spent. negativePremiumPaymentInRedeems = redeemsMinted > redeemsRequired ? redeemsMinted.sub(redeemsRequired) : 0; // In most cases, there will be an outstanding cost (assuming we minted less redeemTokens than the // required amountIn of redeemTokens for the swap). if (redeemCostRemaining > 0) { // The user won't want to pay back the remaining cost in redeemTokens, // because they borrowed underlyingTokens to mint them in the first place. // So instead, we get the quantity of underlyingTokens that could be paid instead. // We can calculate this using normal swap math. // getAmountsOut will return the quantity of underlyingTokens that are output, // based on some input of redeemTokens. // The input redeemTokens is the remaining redeemToken cost, and the output // underlyingTokens is the proportional amount of underlyingTokens. // amountsOut[1] is then the outstanding flash loan value denominated in underlyingTokens. uint256[] memory amountsOut = router.getAmountsOut(redeemCostRemaining, path); // Returning withdrawn tokens to the pair has a fee of .003 / .997 = 0.3009027% which must be applied. loanRemainderInUnderlyings = ( amountsOut[1].mul(100000).add(amountsOut[1].mul(301)) ) .div(100000); } return (loanRemainderInUnderlyings, negativePremiumPaymentInRedeems); } /** * @dev Calculates the effective premium, denominated in underlyingTokens, to sell `optionToken`s. * @param router The UniswapV2Router02 contract. * @param optionToken The optionToken to get the premium cost of purchasing. * @param quantity The quantity of short option tokens that will be closed. */ function getClosePremium( IUniswapV2Router02 router, IOption optionToken, uint256 quantity ) internal view returns ( /* override */ uint256, uint256 ) { // longOptionTokens are closed by doing a swap from underlyingTokens to redeemTokens. address[] memory path = new address[](2); path[0] = optionToken.getUnderlyingTokenAddress(); path[1] = optionToken.redeemToken(); uint256 outputUnderlyings = CoreLib.getProportionalLongOptions(optionToken, quantity); // The loanRemainder will be the amount of underlyingTokens that are needed from the original // transaction caller in order to pay the flash swap. uint256 loanRemainder; // Economically, underlyingPayout value should always be greater than 0, or this trade shouldn't be made. // If an underlyingPayout is greater than 0, it means that the redeemTokens borrowed are worth less than the // underlyingTokens received from closing the redeemToken<>optionTokens. // If the redeemTokens are worth more than the underlyingTokens they are entitled to, // then closing the redeemTokens will cost additional underlyingTokens. In this case, // the transaction should be reverted. Or else, the user is paying extra at the expense of // rebalancing the pool. uint256 underlyingPayout; // Since the borrowed amount is redeemTokens, and we are paying back in underlyingTokens, // we need to see how much underlyingTokens must be returned for the borrowed amount. // We can find that value by doing the normal swap math, getAmountsIn will give us the amount // of underlyingTokens are needed for the output amount of the flash loan. // IMPORTANT: amountsIn 0 is how many underlyingTokens we need to pay back. // This value is most likely greater than the amount of underlyingTokens received from closing. uint256[] memory amountsIn = router.getAmountsIn(quantity, path); uint256 underlyingsRequired = amountsIn[0]; // the amountIn required of underlyingTokens based on the amountOut of flashloanQuantity // If outputUnderlyings (received from closing) is greater than underlyings required, // there is a positive payout. underlyingPayout = outputUnderlyings > underlyingsRequired ? outputUnderlyings.sub(underlyingsRequired) : 0; // If there is a negative payout, calculate the remaining cost of underlyingTokens. uint256 underlyingCostRemaining = underlyingsRequired > outputUnderlyings ? underlyingsRequired.sub(outputUnderlyings) : 0; // In the case that there is a negative payout (additional underlyingTokens are required), // get the remaining cost into the `loanRemainder` variable and also check to see // if a user is willing to pay the negative cost. There is no rational economic incentive for this. if (underlyingCostRemaining > 0) { loanRemainder = underlyingCostRemaining; } return (underlyingPayout, loanRemainder); } } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } pragma solidity >=0.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; } // SPDX-License-Identifier: MIT // Copyright 2021 Primitive Finance // // 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.5.0; interface IERC20Permit { function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function nonces(address owner) external view returns (uint256); function DOMAIN_SEPARATOR() external view returns (bytes32); } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // SPDX-License-Identifier: MIT // Copyright 2021 Primitive Finance // // 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.6.2; /** * @title Primitive Liquidity * @author Primitive * @notice Manage liquidity on Uniswap & Sushiswap Venues. * @dev @primitivefi/[email protected] */ // Open Zeppelin import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; // Interfaces import { IPrimitiveLiquidity, IUniswapV2Router02, IUniswapV2Factory, IUniswapV2Pair, IERC20Permit, IOption } from "../interfaces/IPrimitiveLiquidity.sol"; // Primitive import {PrimitiveConnector} from "./PrimitiveConnector.sol"; import {CoreLib, SafeMath} from "../libraries/CoreLib.sol"; interface DaiPermit { function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) external; } contract PrimitiveLiquidity is PrimitiveConnector, IPrimitiveLiquidity, ReentrancyGuard { using SafeERC20 for IERC20; // Reverts when `transfer` or `transferFrom` erc20 calls don't return proper data using SafeMath for uint256; // Reverts on math underflows/overflows event Initialized(address indexed from); // Emitted on deployment. event AddLiquidity(address indexed from, address indexed option, uint256 sum); event RemoveLiquidity(address indexed from, address indexed option, uint256 sum); IUniswapV2Factory private _factory; // The Uniswap V2 factory contract to get pair addresses from. IUniswapV2Router02 private _router; // The Uniswap Router contract used to interact with the protocol. // ===== Constructor ===== constructor( address weth_, address primitiveRouter_, address factory_, address router_ ) public PrimitiveConnector(weth_, primitiveRouter_) { _factory = IUniswapV2Factory(factory_); _router = IUniswapV2Router02(router_); emit Initialized(_msgSender()); } // ===== Liquidity Operations ===== /** * @dev Adds redeemToken liquidity to a redeem<>underlyingToken pair by minting redeemTokens with underlyingTokens. * @notice Pulls underlying tokens from `getCaller()` and pushes UNI-V2 liquidity tokens to the "getCaller()" address. * underlyingToken -> redeemToken -> UNI-V2. * @param optionAddress The address of the optionToken to get the redeemToken to mint then provide liquidity for. * @param quantityOptions The quantity of underlyingTokens to use to mint option + redeem tokens. * @param amountBMax The quantity of underlyingTokens to add with redeemTokens to the Uniswap V2 Pair. * @param amountBMin The minimum quantity of underlyingTokens expected to provide liquidity with. * @param deadline The timestamp to expire a pending transaction. * @return Returns (amountA, amountB, liquidity) amounts. */ function addShortLiquidityWithUnderlying( address optionAddress, uint256 quantityOptions, uint256 amountBMax, uint256 amountBMin, uint256 deadline ) public override nonReentrant onlyRegistered(IOption(optionAddress)) returns ( uint256, uint256, uint256 ) { uint256 amountA; uint256 amountB; uint256 liquidity; address underlying = IOption(optionAddress).getUnderlyingTokenAddress(); // Pulls total = (quantityOptions + amountBMax) of underlyingTokens from `getCaller()` to this contract. { uint256 sum = quantityOptions.add(amountBMax); _transferFromCaller(underlying, sum); } // Pushes underlyingTokens to option contract and mints option + redeem tokens to this contract. IERC20(underlying).safeTransfer(optionAddress, quantityOptions); (, uint256 outputRedeems) = IOption(optionAddress).mintOptions(address(this)); { // scope for adding exact liquidity, avoids stack too deep errors IOption optionToken = IOption(optionAddress); address redeem = optionToken.redeemToken(); AddAmounts memory params; params.amountAMax = outputRedeems; params.amountBMax = amountBMax; params.amountAMin = outputRedeems; params.amountBMin = amountBMin; params.deadline = deadline; // Approves Uniswap V2 Pair pull tokens from this contract. checkApproval(redeem, address(_router)); checkApproval(underlying, address(_router)); // Adds liquidity to Uniswap V2 Pair and returns liquidity shares to the "getCaller()" address. (amountA, amountB, liquidity) = _addLiquidity(redeem, underlying, params); // Check for exact liquidity provided. assert(amountA == outputRedeems); // Return remaining tokens _transferToCaller(underlying); _transferToCaller(redeem); _transferToCaller(address(optionToken)); } { // scope for event, avoids stack too deep errors address a0 = optionAddress; uint256 q0 = quantityOptions; uint256 q1 = amountBMax; emit AddLiquidity(getCaller(), a0, q0.add(q1)); } return (amountA, amountB, liquidity); } /** * @dev Adds redeemToken liquidity to a redeem<>underlyingToken pair by minting shortOptionTokens with underlyingTokens. * Doesn't check for registered optionAddress because the returned function does. * @notice Pulls underlying tokens from `getCaller()` and pushes UNI-V2 liquidity tokens to the "getCaller()" address. * underlyingToken -> redeemToken -> UNI-V2. Uses permit so user does not need to `approve()` our contracts. * @param optionAddress The address of the optionToken to get the redeemToken to mint then provide liquidity for. * @param quantityOptions The quantity of underlyingTokens to use to mint option + redeem tokens. * @param amountBMax The quantity of underlyingTokens to add with shortOptionTokens to the Uniswap V2 Pair. * @param amountBMin The minimum quantity of underlyingTokens expected to provide liquidity with. * @param deadline The timestamp to expire a pending transaction. * @return Returns (amountA, amountB, liquidity) amounts. */ function addShortLiquidityWithUnderlyingWithPermit( address optionAddress, uint256 quantityOptions, uint256 amountBMax, uint256 amountBMin, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override returns ( uint256, uint256, uint256 ) { IERC20Permit underlying = IERC20Permit(IOption(optionAddress).getUnderlyingTokenAddress()); uint256 sum = quantityOptions.add(amountBMax); underlying.permit(getCaller(), address(_primitiveRouter), sum, deadline, v, r, s); return addShortLiquidityWithUnderlying( optionAddress, quantityOptions, amountBMax, amountBMin, deadline ); } /** * @dev Doesn't check for registered optionAddress because the returned function does. * @notice Specialized function for `permit` calling on Put options (DAI). */ function addShortLiquidityDAIWithPermit( address optionAddress, uint256 quantityOptions, uint256 amountBMax, uint256 amountBMin, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override returns ( uint256, uint256, uint256 ) { DaiPermit dai = DaiPermit(IOption(optionAddress).getUnderlyingTokenAddress()); address caller = getCaller(); dai.permit( caller, address(_primitiveRouter), IERC20Permit(address(dai)).nonces(caller), deadline, true, v, r, s ); return addShortLiquidityWithUnderlying( optionAddress, quantityOptions, amountBMax, amountBMin, deadline ); } /** * @dev Adds redeemToken liquidity to a redeem<>underlyingToken pair by minting shortOptionTokens with underlyingTokens. * @notice Pulls underlying tokens from `getCaller()` and pushes UNI-V2 liquidity tokens to the `getCaller()` address. * underlyingToken -> redeemToken -> UNI-V2. * @param optionAddress The address of the optionToken to get the redeemToken to mint then provide liquidity for. * @param quantityOptions The quantity of underlyingTokens to use to mint option + redeem tokens. * @param amountBMax The quantity of underlyingTokens to add with shortOptionTokens to the Uniswap V2 Pair. * @param amountBMin The minimum quantity of underlyingTokens expected to provide liquidity with. * @param deadline The timestamp to expire a pending transaction. * @return Returns (amountA, amountB, liquidity) amounts. */ function addShortLiquidityWithETH( address optionAddress, uint256 quantityOptions, uint256 amountBMax, uint256 amountBMin, uint256 deadline ) external payable override nonReentrant onlyRegistered(IOption(optionAddress)) returns ( uint256, uint256, uint256 ) { require( msg.value >= quantityOptions.add(amountBMax), "PrimitiveLiquidity: INSUFFICIENT" ); uint256 amountA; uint256 amountB; uint256 liquidity; address underlying = IOption(optionAddress).getUnderlyingTokenAddress(); require(underlying == address(_weth), "PrimitiveLiquidity: NOT_WETH"); _depositETH(); // Wraps `msg.value` to Weth. // Pushes Weth to option contract and mints option + redeem tokens to this contract. IERC20(underlying).safeTransfer(optionAddress, quantityOptions); (, uint256 outputRedeems) = IOption(optionAddress).mintOptions(address(this)); { // scope for adding exact liquidity, avoids stack too deep errors IOption optionToken = IOption(optionAddress); address redeem = optionToken.redeemToken(); AddAmounts memory params; params.amountAMax = outputRedeems; params.amountBMax = amountBMax; params.amountAMin = outputRedeems; params.amountBMin = amountBMin; params.deadline = deadline; // Approves Uniswap V2 Pair pull tokens from this contract. checkApproval(redeem, address(_router)); checkApproval(underlying, address(_router)); // Adds liquidity to Uniswap V2 Pair. (amountA, amountB, liquidity) = _addLiquidity(redeem, underlying, params); assert(amountA == outputRedeems); // Check for exact liquidity provided. // Return remaining tokens and ether. _withdrawETH(); _transferToCaller(redeem); _transferToCaller(address(optionToken)); } { // scope for event, avoids stack too deep errors address a0 = optionAddress; uint256 q0 = quantityOptions; uint256 q1 = amountBMax; emit AddLiquidity(getCaller(), a0, q0.add(q1)); } return (amountA, amountB, liquidity); } struct AddAmounts { uint256 amountAMax; uint256 amountBMax; uint256 amountAMin; uint256 amountBMin; uint256 deadline; } /** * @notice Calls UniswapV2Router02.addLiquidity() function using this contract's tokens. * @param tokenA The first token of the Uniswap Pair to add as liquidity. * @param tokenB The second token of the Uniswap Pair to add as liquidity. * @param params The amounts specified to be added as liquidity. Adds exact short options. * @return Returns (amountTokenA, amountTokenB, liquidity) amounts. */ function _addLiquidity( address tokenA, address tokenB, AddAmounts memory params ) internal returns ( uint256, uint256, uint256 ) { return _router.addLiquidity( tokenA, tokenB, params.amountAMax, params.amountBMax, params.amountAMin, params.amountBMin, getCaller(), params.deadline ); } /** * @dev Combines Uniswap V2 Router "removeLiquidity" function with Primitive "closeOptions" function. * @notice Pulls UNI-V2 liquidity shares with shortOption<>underlying token, and optionTokens from `getCaller()`. * Then closes the longOptionTokens and withdraws underlyingTokens to the `getCaller()` address. * Sends underlyingTokens from the burned UNI-V2 liquidity shares to the `getCaller()` address. * UNI-V2 -> optionToken -> underlyingToken. * @param optionAddress The address of the option that will be closed from burned UNI-V2 liquidity shares. * @param liquidity The quantity of liquidity tokens to pull from `getCaller()` and burn. * @param amountAMin The minimum quantity of shortOptionTokens to receive from removing liquidity. * @param amountBMin The minimum quantity of underlyingTokens to receive from removing liquidity. * @return Returns the sum of the removed underlying tokens. */ function removeShortLiquidityThenCloseOptions( address optionAddress, uint256 liquidity, uint256 amountAMin, uint256 amountBMin ) public override nonReentrant onlyRegistered(IOption(optionAddress)) returns (uint256) { IOption optionToken = IOption(optionAddress); (IUniswapV2Pair pair, address underlying, address redeem) = getOptionPair(optionToken); // Gets amounts struct. RemoveAmounts memory params; params.liquidity = liquidity; params.amountAMin = amountAMin; params.amountBMin = amountBMin; // Pulls lp tokens from `getCaller()` and pushes them to the pair in preparation to invoke `burn()`. _transferFromCallerToReceiver(address(pair), liquidity, address(pair)); // Calls `burn` on the `pair`, returning amounts to this contract. (, uint256 underlyingAmount) = _removeLiquidity(pair, redeem, underlying, params); uint256 underlyingProceeds = _closeOptions(optionToken); // Returns amount of underlying tokens released. // Return remaining tokens/ether. _withdrawETH(); // Unwraps Weth and sends ether to `getCaller()`. _transferToCaller(redeem); // Push any remaining redeemTokens from removing liquidity (dust). _transferToCaller(underlying); // Pushes underlying token to `getCaller()`. uint256 sum = underlyingProceeds.add(underlyingAmount); // Total underlyings sent to `getCaller()`. emit RemoveLiquidity(getCaller(), address(optionToken), sum); return sum; } /** * @notice Pulls LP tokens, burns them, removes liquidity, pull option token, burns then, pushes all underlying tokens. * @dev Uses permit to pull LP tokens. * @param optionAddress The address of the option that will be closed from burned UNI-V2 liquidity shares. * @param liquidity The quantity of liquidity tokens to pull from _msgSender() and burn. * @param amountAMin The minimum quantity of shortOptionTokens to receive from removing liquidity. * @param amountBMin The minimum quantity of underlyingTokens to receive from removing liquidity. * @param deadline The timestamp to expire a pending transaction and `permit` call. * @return Returns the sum of the removed underlying tokens. */ function removeShortLiquidityThenCloseOptionsWithPermit( address optionAddress, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override returns (uint256) { IOption optionToken = IOption(optionAddress); (IUniswapV2Pair pair, , ) = getOptionPair(optionToken); pair.permit(getCaller(), address(_primitiveRouter), liquidity, deadline, v, r, s); return removeShortLiquidityThenCloseOptions( address(optionToken), liquidity, amountAMin, amountBMin ); } struct RemoveAmounts { uint256 liquidity; uint256 amountAMin; uint256 amountBMin; } /** * @notice Calls `UniswapV2Pair.burn(address(this))` to burn LP tokens for pair tokens. * @param pair The UniswapV2Pair contract to burn LP tokens of. * @param tokenA The first token of the pair. * @param tokenB The second token of the pair. * @param params The amounts to specify the amount to remove and minAmounts to withdraw. * @return Returns (amountTokenA, amountTokenB) which is (redeem, underlying) amounts. */ function _removeLiquidity( IUniswapV2Pair pair, address tokenA, address tokenB, RemoveAmounts memory params ) internal returns (uint256, uint256) { (uint256 amount0, uint256 amount1) = pair.burn(address(this)); (address token0, ) = CoreLib.sortTokens(tokenA, tokenB); (uint256 amountA, uint256 amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= params.amountAMin, "PrimitiveLiquidity: INSUFFICIENT_A"); require(amountB >= params.amountBMin, "PrimitiveLiquidity: INSUFFICIENT_B"); return (amountA, amountB); } // ===== View ===== /** * @notice Gets the UniswapV2Router02 contract address. */ function getRouter() public view override returns (IUniswapV2Router02) { return _router; } /** * @notice Gets the UniswapV2Factory contract address. */ function getFactory() public view override returns (IUniswapV2Factory) { return _factory; } /** * @notice Fetchs the Uniswap Pair for an option's redeemToken and underlyingToken params. * @param option The option token to get the corresponding UniswapV2Pair market. * @return The pair address, as well as the tokens of the pair. */ function getOptionPair(IOption option) public view override returns ( IUniswapV2Pair, address, address ) { address redeem = option.redeemToken(); address underlying = option.getUnderlyingTokenAddress(); IUniswapV2Pair pair = IUniswapV2Pair(_factory.getPair(redeem, underlying)); return (pair, underlying, redeem); } } // SPDX-License-Identifier: MIT // Copyright 2021 Primitive Finance // // 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.6.2; import { IUniswapV2Router02 } from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import { IUniswapV2Factory } from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import {IUniswapV2Pair} from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import {IOption} from "@primitivefi/contracts/contracts/option/interfaces/IOption.sol"; import {IERC20Permit} from "./IERC20Permit.sol"; interface IPrimitiveLiquidity { // ==== External ==== function addShortLiquidityWithUnderlying( address optionAddress, uint256 quantityOptions, uint256 amountBMax, uint256 amountBMin, uint256 deadline ) external returns ( uint256, uint256, uint256 ); function addShortLiquidityWithETH( address optionAddress, uint256 quantityOptions, uint256 amountBMax, uint256 amountBMin, uint256 deadline ) external payable returns ( uint256, uint256, uint256 ); function addShortLiquidityWithUnderlyingWithPermit( address optionAddress, uint256 quantityOptions, uint256 amountBMax, uint256 amountBMin, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external returns ( uint256, uint256, uint256 ); function addShortLiquidityDAIWithPermit( address optionAddress, uint256 quantityOptions, uint256 amountBMax, uint256 amountBMin, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external returns ( uint256, uint256, uint256 ); function removeShortLiquidityThenCloseOptions( address optionAddress, uint256 liquidity, uint256 amountAMin, uint256 amountBMin ) external returns (uint256); function removeShortLiquidityThenCloseOptionsWithPermit( address optionAddress, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external returns (uint256); // ==== View ==== function getRouter() external view returns (IUniswapV2Router02); function getFactory() external view returns (IUniswapV2Factory); function getOptionPair(IOption option) external view returns ( IUniswapV2Pair, address, address ); } // SPDX-License-Identifier: MIT // Copyright 2021 Primitive Finance // // 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.6.2; /** * @title TestERC20 * @author Primitive * @notice An opinionated ERC20 with `permit` to use ONLY for testing. * @dev @primitivefi/[email protected] */ import {IERC20Permit} from "../interfaces/IERC20Permit.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; contract TestERC20 { using SafeMath for uint256; string public name = "Test Token"; string public symbol; uint8 public constant decimals = 18; uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; mapping(address => uint256) public nonces; bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); constructor( string memory name_, string memory symbol_, uint256 initialSupply ) public { name = name_; symbol = symbol_; _mint(msg.sender, initialSupply); uint256 chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name_)), keccak256(bytes("1")), chainId, address(this) ) ); } /** * @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 returns (bool) { _mint(to, value); return true; } function _mint(address to, uint256 value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint256 value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve( address owner, address spender, uint256 value ) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer( address from, address to, uint256 value ) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint256 value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint256 value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom( address from, address to, uint256 value ) external returns (bool) { if (allowance[from][msg.sender] != uint256(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(deadline >= block.timestamp, "Primitive: EXPIRED"); 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, "Primitive: INVALID_SIGNATURE" ); _approve(owner, spender, value); } } // SPDX-License-Identifier: MIT // Copyright 2021 Primitive Finance // // 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.6.2; /** * @title Primitive Router * @author Primitive * @notice Contract to execute Primitive Connector functions. * @dev @primitivefi/[email protected] */ // Open Zeppelin import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import { IPrimitiveRouter, IRegistry, IOption, IERC20, IWETH } from "./interfaces/IPrimitiveRouter.sol"; /** * @notice Used to execute calls on behalf of the Router contract. * @dev Changes `msg.sender` context so the Router is not `msg.sender`. */ contract Route { function executeCall(address target, bytes calldata params) external payable { (bool success, bytes memory returnData) = target.call.value(msg.value)(params); require(success, "Route: EXECUTION_FAIL"); } } contract PrimitiveRouter is IPrimitiveRouter, Ownable, Pausable, ReentrancyGuard { using SafeERC20 for IERC20; // Reverts when `transfer` or `transferFrom` erc20 calls don't return proper data. using SafeMath for uint256; // Reverts on math underflows/overflows. // Constants address private constant _NO_CALLER = address(0x0); // Default state for `_CALLER`. // Events event Initialized(address indexed from); // Emmitted on deployment event Executed(address indexed from, address indexed to, bytes params); event RegisteredOptions(address[] indexed options); event RegisteredConnectors(address[] indexed connectors, bool[] registered); // State variables IRegistry private _registry; // The Primitive Registry which deploys Option clones. IWETH private _weth; // Canonical WETH9 Route private _route; // Intermediary to do connector.call() from. address private _CONNECTOR = _NO_CALLER; // If _EXECUTING, the `connector` of the execute call param. address private _CALLER = _NO_CALLER; // If _EXECUTING, the orginal `_msgSender()` of the execute call. bool private _EXECUTING; // True if the `executeCall` function was called. // Whitelisted mappings mapping(address => bool) private _registeredConnectors; mapping(address => bool) private _registeredOptions; /** * @notice A mutex to use during an `execute` call. * @dev Checks to make sure the `_CONNECTOR` in state is the `msg.sender`. * Checks to make sure a `_CALLER` was set. * Fails if this modifier is triggered by an external call. * Fails if this modifier is triggered by calling a function without going through `executeCall`. */ modifier isExec() { require(_CONNECTOR == _msgSender(), "Router: NOT_CONNECTOR"); require(_CALLER != _NO_CALLER, "Router: NO_CALLER"); require(!_EXECUTING, "Router: IN_EXECUTION"); _EXECUTING = true; _; _EXECUTING = false; } // ===== Constructor ===== constructor(address weth_, address registry_) public { require(address(_weth) == address(0x0), "Router: INITIALIZED"); _route = new Route(); _weth = IWETH(weth_); _registry = IRegistry(registry_); emit Initialized(_msgSender()); } // ===== Pausability ===== /** * @notice Halts use of `executeCall`, and other functions that change state. */ function halt() external override onlyOwner { if (paused()) { _unpause(); } else { _pause(); } } // ===== Registration ===== /** * @notice Checks option against Primitive Registry. If from Registry, registers as true. * NOTE: Purposefully does not have `onlyOwner` modifier. * @dev Sets `optionAddresses` to true in the whitelisted options mapping, if from Registry. * @param optionAddresses The array of option addresses to update. */ function setRegisteredOptions(address[] calldata optionAddresses) external override returns (bool) { uint256 len = optionAddresses.length; for (uint256 i = 0; i < len; i++) { address option = optionAddresses[i]; require(isFromPrimitiveRegistry(IOption(option)), "Router: EVIL_OPTION"); _registeredOptions[option] = true; } emit RegisteredOptions(optionAddresses); return true; } /** * @notice Allows the `owner` to set whitelisted connector contracts. * @dev Sets `connectors` to `isValid` in the whitelisted connectors mapping. * @param connectors The array of option addresses to update. * @param isValid Whether or not the optionAddress is registered. */ function setRegisteredConnectors(address[] memory connectors, bool[] memory isValid) public override onlyOwner returns (bool) { uint256 len = connectors.length; require(len == isValid.length, "Router: LENGTHS"); for (uint256 i = 0; i < len; i++) { address connector = connectors[i]; bool status = isValid[i]; _registeredConnectors[connector] = status; } emit RegisteredConnectors(connectors, isValid); return true; } /** * @notice Checks an option against the Primitive Registry. * @param option The IOption token to check. * @return Whether or not the option was deployed from the Primitive Registry. */ function isFromPrimitiveRegistry(IOption option) internal view returns (bool) { return (address(option) == _registry.getOptionAddress( option.getUnderlyingTokenAddress(), option.getStrikeTokenAddress(), option.getBaseValue(), option.getQuoteValue(), option.getExpiryTime() ) && address(option) != address(0)); } // ===== Operations ===== /** * @notice Transfers ERC20 tokens from the executing `_CALLER` to the executing `_CONNECTOR`. * @param token The address of the ERC20. * @param amount The amount of ERC20 to transfer. * @return Whether or not the transfer succeeded. */ function transferFromCaller(address token, uint256 amount) public override isExec whenNotPaused returns (bool) { IERC20(token).safeTransferFrom( getCaller(), // Account to pull from _msgSender(), // The connector amount ); return true; } /** * @notice Transfers ERC20 tokens from the executing `_CALLER` to an arbitrary address. * @param token The address of the ERC20. * @param amount The amount of ERC20 to transfer. * @return Whether or not the transfer succeeded. */ function transferFromCallerToReceiver( address token, uint256 amount, address receiver ) public override isExec whenNotPaused returns (bool) { IERC20(token).safeTransferFrom( getCaller(), // Account to pull from receiver, amount ); return true; } // ===== Execute ===== /** * @notice Executes a call with `params` to the target `connector` contract from `_route`. * @param connector The Primitive Connector module to call. * @param params The encoded function data to use. */ function executeCall(address connector, bytes calldata params) external payable override whenNotPaused { require(_registeredConnectors[connector], "Router: INVALID_CONNECTOR"); _CALLER = _msgSender(); _CONNECTOR = connector; _route.executeCall.value(msg.value)(connector, params); _CALLER = _NO_CALLER; _CONNECTOR = _NO_CALLER; emit Executed(_msgSender(), connector, params); } // ===== Fallback ===== receive() external payable whenNotPaused { assert(_msgSender() == address(_weth)); // only accept ETH via fallback from the WETH contract } // ===== View ===== /** * @notice Returns the IWETH contract address. */ function getWeth() public view override returns (IWETH) { return _weth; } /** * @notice Returns the Route contract which executes functions on behalf of this contract. */ function getRoute() public view override returns (address) { return address(_route); } /** * @notice Returns the `_CALLER` which is set to `_msgSender()` during an `executeCall` invocation. */ function getCaller() public view override returns (address) { return _CALLER; } /** * @notice Returns the Primitive Registry contract address. */ function getRegistry() public view override returns (IRegistry) { return _registry; } /** * @notice Returns a bool if `option` is registered or not. * @param option The address of the Option to check if registered. */ function getRegisteredOption(address option) external view override returns (bool) { return _registeredOptions[option]; } /** * @notice Returns a bool if `connector` is registered or not. * @param connector The address of the Connector contract to check if registered. */ function getRegisteredConnector(address connector) external view override returns (bool) { return _registeredConnectors[connector]; } /** * @notice Returns the NPM package version and github version of this contract. * @dev For the npm package: @primitivefi/v1-connectors * For the repository: github.com/primitivefinance/primitive-v1-connectors * @return The apiVersion string. */ function apiVersion() public pure override returns (string memory) { return "2.0.0"; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * 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 // Copyright 2021 Primitive Finance // // 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.6.2; import {IOption} from "@primitivefi/contracts/contracts/option/interfaces/IOption.sol"; import {IERC20Permit} from "./IERC20Permit.sol"; interface IPrimitiveCore { // ===== External ===== function safeMintWithETH(IOption optionToken) external payable returns (uint256, uint256); function safeMintWithPermit( IOption optionToken, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external returns (uint256, uint256); function safeExerciseWithETH(IOption optionToken) external payable returns (uint256, uint256); function safeExerciseForETH(IOption optionToken, uint256 exerciseQuantity) external returns (uint256, uint256); function safeRedeemForETH(IOption optionToken, uint256 redeemQuantity) external returns (uint256); function safeCloseForETH(IOption optionToken, uint256 closeQuantity) external returns ( uint256, uint256, uint256 ); } // SPDX-License-Identifier: MIT // Copyright 2021 Primitive Finance // // 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.6.2; /** * @title Primitive Core * @author Primitive * @notice A Connector with Ether abstractions for Primitive Option tokens. * @dev @primitivefi/[email protected] */ // Open Zeppelin import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; // Primitive import {CoreLib, SafeMath} from "../libraries/CoreLib.sol"; import {IPrimitiveCore, IERC20Permit, IOption} from "../interfaces/IPrimitiveCore.sol"; import {PrimitiveConnector} from "./PrimitiveConnector.sol"; contract PrimitiveCore is PrimitiveConnector, IPrimitiveCore, ReentrancyGuard { using SafeERC20 for IERC20; // Reverts when `transfer` or `transferFrom` erc20 calls don't return proper data using SafeMath for uint256; // Reverts on math underflows/overflows event Initialized(address indexed from); // Emmitted on deployment event Minted( address indexed from, address indexed option, uint256 longQuantity, uint256 shortQuantity ); event Exercised(address indexed from, address indexed option, uint256 quantity); event Redeemed(address indexed from, address indexed option, uint256 quantity); event Closed(address indexed from, address indexed option, uint256 quantity); // ===== Constructor ===== constructor(address weth_, address primitiveRouter_) public PrimitiveConnector(weth_, primitiveRouter_) { emit Initialized(_msgSender()); } // ===== Weth Abstraction ===== /** * @dev Mints msg.value quantity of options and "quote" (option parameter) quantity of redeem tokens. * @notice This function is for options that have WETH as the underlying asset. * @param optionToken The address of the option token to mint. * @return (uint, uint) Returns the (long, short) option tokens minted */ function safeMintWithETH(IOption optionToken) external payable override nonReentrant onlyRegistered(optionToken) returns (uint256, uint256) { require(msg.value > 0, "PrimitiveCore: ERR_ZERO"); address caller = getCaller(); _depositETH(); // Deposits `msg.value` to Weth contract. (uint256 long, uint256 short) = _mintOptionsToReceiver(optionToken, caller); emit Minted(caller, address(optionToken), long, short); return (long, short); } /** * @dev Mints "amount" quantity of options and "quote" (option parameter) quantity of redeem tokens. * @notice This function is for options that have an EIP2612 (permit) enabled token as the underlying asset. * @param optionToken The address of the option token to mint. * @param amount The quantity of options to mint. * @param deadline The timestamp which expires the `permit` call. * @return (uint, uint) Returns the (long, short) option tokens minted */ function safeMintWithPermit( IOption optionToken, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override nonReentrant onlyRegistered(optionToken) returns (uint256, uint256) { // Permit minting using the caller's underlying tokens. IERC20Permit(optionToken.getUnderlyingTokenAddress()).permit( getCaller(), address(_primitiveRouter), amount, deadline, v, r, s ); (uint256 long, uint256 short) = _mintOptionsFromCaller(optionToken, amount); emit Minted(getCaller(), address(optionToken), long, short); return (long, short); } /** * @dev Swaps msg.value of strikeTokens (ethers) to underlyingTokens. * Uses the strike ratio as the exchange rate. Strike ratio = base / quote. * Msg.value (quote units) * base / quote = base units (underlyingTokens) to withdraw. * @notice This function is for options with WETH as the strike asset. * Burns option tokens, accepts ethers, and pushes out underlyingTokens. * @param optionToken The address of the option contract. */ function safeExerciseWithETH(IOption optionToken) public payable override nonReentrant onlyRegistered(optionToken) returns (uint256, uint256) { require(msg.value > 0, "PrimitiveCore: ZERO"); _depositETH(); // Deposits `msg.value` to Weth contract. uint256 long = CoreLib.getProportionalLongOptions(optionToken, msg.value); _transferFromCaller(address(optionToken), long); // Pull option tokens. // Pushes option tokens and weth (strike asset), receives underlying tokens. emit Exercised(getCaller(), address(optionToken), long); return _exerciseOptions(optionToken, long); } /** * @dev Swaps strikeTokens to underlyingTokens, WETH, which is converted to ethers before withdrawn. * Uses the strike ratio as the exchange rate. Strike ratio = base / quote. * @notice This function is for options with WETH as the underlying asset. * Burns option tokens, pulls strikeTokens, and pushes out ethers. * @param optionToken The address of the option contract. * @param exerciseQuantity Quantity of optionTokens to exercise. */ function safeExerciseForETH(IOption optionToken, uint256 exerciseQuantity) public override nonReentrant onlyRegistered(optionToken) returns (uint256, uint256) { address underlying = optionToken.getUnderlyingTokenAddress(); address strike = optionToken.getStrikeTokenAddress(); uint256 strikeQuantity = CoreLib.getProportionalShortOptions(optionToken, exerciseQuantity); // Pull options and strike assets from `getCaller()` and send to option contract. _transferFromCallerToReceiver( address(optionToken), exerciseQuantity, address(optionToken) ); _transferFromCallerToReceiver(strike, strikeQuantity, address(optionToken)); // Release underlying tokens by invoking `exerciseOptions()` (uint256 strikesPaid, uint256 options) = optionToken.exerciseOptions(address(this), exerciseQuantity, new bytes(0)); _withdrawETH(); // Unwraps this contract's balance of Weth and sends to `getCaller()`. emit Exercised(getCaller(), address(optionToken), exerciseQuantity); return (strikesPaid, options); } /** * @dev Burns redeem tokens to withdraw strike tokens (ethers) at a 1:1 ratio. * @notice This function is for options that have WETH as the strike asset. * Converts WETH to ethers, and withdraws ethers to the receiver address. * @param optionToken The address of the option contract. * @param redeemQuantity The quantity of redeemTokens to burn. */ function safeRedeemForETH(IOption optionToken, uint256 redeemQuantity) public override nonReentrant onlyRegistered(optionToken) returns (uint256) { // Require the strike token to be Weth. address redeem = optionToken.redeemToken(); // Pull redeem tokens from `getCaller()` and send to option contract. _transferFromCallerToReceiver(redeem, redeemQuantity, address(optionToken)); uint256 short = optionToken.redeemStrikeTokens(address(this)); _withdrawETH(); // Unwraps this contract's balance of Weth and sends to `getCaller()`. emit Redeemed(getCaller(), address(optionToken), redeemQuantity); return short; } /** * @dev Burn optionTokens and redeemTokens to withdraw underlyingTokens (ethers). * @notice This function is for options with WETH as the underlying asset. * WETH underlyingTokens are converted to ethers before being sent to receiver. * The redeemTokens to burn is equal to the optionTokens * strike ratio. * inputOptions = inputRedeems / strike ratio = outUnderlyings * @param optionToken The address of the option contract. * @param closeQuantity Quantity of optionTokens to burn and an input to calculate how many redeems to burn. */ function safeCloseForETH(IOption optionToken, uint256 closeQuantity) public override nonReentrant onlyRegistered(optionToken) returns ( uint256, uint256, uint256 ) { address redeem = optionToken.redeemToken(); uint256 short = CoreLib.getProportionalShortOptions(optionToken, closeQuantity); // Pull redeem tokens from `getCaller()` and send to option contract. _transferFromCallerToReceiver(redeem, short, address(optionToken)); // Pull options if not expired, and send to option contract. if (optionToken.getExpiryTime() >= now) { _transferFromCallerToReceiver( address(optionToken), closeQuantity, address(optionToken) ); } // Release underlyingTokens by invoking `closeOptions()` (uint256 inputRedeems, uint256 inputOptions, uint256 outUnderlyings) = optionToken.closeOptions(address(this)); _withdrawETH(); // Unwraps this contract's balance of Weth and sends to `getCaller()`. emit Closed(getCaller(), address(optionToken), closeQuantity); return (inputRedeems, inputOptions, outUnderlyings); } }
Fetchs the Uniswap Pair for an option's redeemToken and underlyingToken params. option The option token to get the corresponding UniswapV2Pair market. return The pair address, as well as the tokens of the pair./
function getOptionPair(IOption option) public view override returns ( IUniswapV2Pair, address, address ) { address redeem = option.redeemToken(); address underlying = option.getUnderlyingTokenAddress(); IUniswapV2Pair pair = IUniswapV2Pair(_factory.getPair(redeem, underlying)); return (pair, underlying, redeem); }
11,694,940
/** *Submitted for verification at Etherscan.io on 2021-11-23 */ /* ____ __ __ __ _ / __/__ __ ___ / /_ / / ___ / /_ (_)__ __ _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ / /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\ /___/ * Synthetix: OwnerRelayOnEthereum.sol * * Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/OwnerRelayOnEthereum.sol * Docs: https://docs.synthetix.io/contracts/OwnerRelayOnEthereum * * Contract Dependencies: * - IAddressResolver * - MixinResolver * - MixinSystemSettings * - Owned * Libraries: (none) * * MIT License * =========== * * Copyright (c) 2021 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 */ pragma solidity ^0.5.16; // https://docs.synthetix.io/contracts/source/contracts/owned contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getSynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } // https://docs.synthetix.io/contracts/source/interfaces/isynth interface ISynth { // Views function currencyKey() external view returns (bytes32); function transferableSynths(address account) external view returns (uint); // Mutative functions function transferAndSettle(address to, uint value) external returns (bool); function transferFromAndSettle( address from, address to, uint value ) external returns (bool); // Restricted: used internally to Synthetix function burn(address account, uint amount) external; function issue(address account, uint amount) external; } // https://docs.synthetix.io/contracts/source/interfaces/iissuer interface IIssuer { // Views function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint); function availableSynths(uint index) external view returns (ISynth); function canBurnSynths(address account) external view returns (bool); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function collateralisationRatioAndAnyRatesInvalid(address _issuer) external view returns (uint cratio, bool anyRateIsInvalid); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance); function issuanceRatio() external view returns (uint); function lastIssueEvent(address account) external view returns (uint); function maxIssuableSynths(address issuer) external view returns (uint maxIssuable); function minimumStakeTime() external view returns (uint); function remainingIssuableSynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function synths(bytes32 currencyKey) external view returns (ISynth); function getSynths(bytes32[] calldata currencyKeys) external view returns (ISynth[] memory); function synthsByAddress(address synthAddress) external view returns (bytes32); function totalIssuedSynths(bytes32 currencyKey, bool excludeOtherCollateral) external view returns (uint); function transferableSynthetixAndAnyRateIsInvalid(address account, uint balance) external view returns (uint transferable, bool anyRateIsInvalid); // Restricted: used internally to Synthetix function issueSynths(address from, uint amount) external; function issueSynthsOnBehalf( address issueFor, address from, uint amount ) external; function issueMaxSynths(address from) external; function issueMaxSynthsOnBehalf(address issueFor, address from) external; function burnSynths(address from, uint amount) external; function burnSynthsOnBehalf( address burnForAddress, address from, uint amount ) external; function burnSynthsToTarget(address from) external; function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external; function burnForRedemption( address deprecatedSynthProxy, address account, uint balance ) external; function liquidateDelinquentAccount( address account, uint susdAmount, address liquidator ) external returns (uint totalRedeemed, uint amountToLiquidate); } // Inheritance // Internal references // https://docs.synthetix.io/contracts/source/contracts/addressresolver contract AddressResolver is Owned, IAddressResolver { mapping(bytes32 => address) public repository; constructor(address _owner) public Owned(_owner) {} /* ========== RESTRICTED FUNCTIONS ========== */ function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner { require(names.length == destinations.length, "Input lengths must match"); for (uint i = 0; i < names.length; i++) { bytes32 name = names[i]; address destination = destinations[i]; repository[name] = destination; emit AddressImported(name, destination); } } /* ========= PUBLIC FUNCTIONS ========== */ function rebuildCaches(MixinResolver[] calldata destinations) external { for (uint i = 0; i < destinations.length; i++) { destinations[i].rebuildCache(); } } /* ========== VIEWS ========== */ function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) { for (uint i = 0; i < names.length; i++) { if (repository[names[i]] != destinations[i]) { return false; } } return true; } function getAddress(bytes32 name) external view returns (address) { return repository[name]; } function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) { address _foundAddress = repository[name]; require(_foundAddress != address(0), reason); return _foundAddress; } function getSynth(bytes32 key) external view returns (address) { IIssuer issuer = IIssuer(repository["Issuer"]); require(address(issuer) != address(0), "Cannot find Issuer address"); return address(issuer.synths(key)); } /* ========== EVENTS ========== */ event AddressImported(bytes32 name, address destination); } // Internal references // https://docs.synthetix.io/contracts/source/contracts/mixinresolver contract MixinResolver { AddressResolver public resolver; mapping(bytes32 => address) private addressCache; constructor(address _resolver) internal { resolver = AddressResolver(_resolver); } /* ========== INTERNAL FUNCTIONS ========== */ function combineArrays(bytes32[] memory first, bytes32[] memory second) internal pure returns (bytes32[] memory combination) { combination = new bytes32[](first.length + second.length); for (uint i = 0; i < first.length; i++) { combination[i] = first[i]; } for (uint j = 0; j < second.length; j++) { combination[first.length + j] = second[j]; } } /* ========== PUBLIC FUNCTIONS ========== */ // Note: this function is public not external in order for it to be overridden and invoked via super in subclasses function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {} function rebuildCache() public { bytes32[] memory requiredAddresses = resolverAddressesRequired(); // The resolver must call this function whenver it updates its state for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // Note: can only be invoked once the resolver has all the targets needed added address destination = resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name))); addressCache[name] = destination; emit CacheUpdated(name, destination); } } /* ========== VIEWS ========== */ function isResolverCached() external view returns (bool) { bytes32[] memory requiredAddresses = resolverAddressesRequired(); for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // false if our cache is invalid or if the resolver doesn't have the required address if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) { return false; } } return true; } /* ========== INTERNAL FUNCTIONS ========== */ function requireAndGetAddress(bytes32 name) internal view returns (address) { address _foundAddress = addressCache[name]; require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name))); return _foundAddress; } /* ========== EVENTS ========== */ event CacheUpdated(bytes32 name, address destination); } // https://docs.synthetix.io/contracts/source/interfaces/iflexiblestorage interface IFlexibleStorage { // Views function getUIntValue(bytes32 contractName, bytes32 record) external view returns (uint); function getUIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (uint[] memory); function getIntValue(bytes32 contractName, bytes32 record) external view returns (int); function getIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (int[] memory); function getAddressValue(bytes32 contractName, bytes32 record) external view returns (address); function getAddressValues(bytes32 contractName, bytes32[] calldata records) external view returns (address[] memory); function getBoolValue(bytes32 contractName, bytes32 record) external view returns (bool); function getBoolValues(bytes32 contractName, bytes32[] calldata records) external view returns (bool[] memory); function getBytes32Value(bytes32 contractName, bytes32 record) external view returns (bytes32); function getBytes32Values(bytes32 contractName, bytes32[] calldata records) external view returns (bytes32[] memory); // Mutative functions function deleteUIntValue(bytes32 contractName, bytes32 record) external; function deleteIntValue(bytes32 contractName, bytes32 record) external; function deleteAddressValue(bytes32 contractName, bytes32 record) external; function deleteBoolValue(bytes32 contractName, bytes32 record) external; function deleteBytes32Value(bytes32 contractName, bytes32 record) external; function setUIntValue( bytes32 contractName, bytes32 record, uint value ) external; function setUIntValues( bytes32 contractName, bytes32[] calldata records, uint[] calldata values ) external; function setIntValue( bytes32 contractName, bytes32 record, int value ) external; function setIntValues( bytes32 contractName, bytes32[] calldata records, int[] calldata values ) external; function setAddressValue( bytes32 contractName, bytes32 record, address value ) external; function setAddressValues( bytes32 contractName, bytes32[] calldata records, address[] calldata values ) external; function setBoolValue( bytes32 contractName, bytes32 record, bool value ) external; function setBoolValues( bytes32 contractName, bytes32[] calldata records, bool[] calldata values ) external; function setBytes32Value( bytes32 contractName, bytes32 record, bytes32 value ) external; function setBytes32Values( bytes32 contractName, bytes32[] calldata records, bytes32[] calldata values ) external; } // Internal references // https://docs.synthetix.io/contracts/source/contracts/mixinsystemsettings contract MixinSystemSettings is MixinResolver { bytes32 internal constant SETTING_CONTRACT_NAME = "SystemSettings"; bytes32 internal constant SETTING_WAITING_PERIOD_SECS = "waitingPeriodSecs"; bytes32 internal constant SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR = "priceDeviationThresholdFactor"; bytes32 internal constant SETTING_ISSUANCE_RATIO = "issuanceRatio"; bytes32 internal constant SETTING_FEE_PERIOD_DURATION = "feePeriodDuration"; bytes32 internal constant SETTING_TARGET_THRESHOLD = "targetThreshold"; bytes32 internal constant SETTING_LIQUIDATION_DELAY = "liquidationDelay"; bytes32 internal constant SETTING_LIQUIDATION_RATIO = "liquidationRatio"; bytes32 internal constant SETTING_LIQUIDATION_PENALTY = "liquidationPenalty"; bytes32 internal constant SETTING_RATE_STALE_PERIOD = "rateStalePeriod"; bytes32 internal constant SETTING_EXCHANGE_FEE_RATE = "exchangeFeeRate"; bytes32 internal constant SETTING_MINIMUM_STAKE_TIME = "minimumStakeTime"; bytes32 internal constant SETTING_AGGREGATOR_WARNING_FLAGS = "aggregatorWarningFlags"; bytes32 internal constant SETTING_TRADING_REWARDS_ENABLED = "tradingRewardsEnabled"; bytes32 internal constant SETTING_DEBT_SNAPSHOT_STALE_TIME = "debtSnapshotStaleTime"; bytes32 internal constant SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT = "crossDomainDepositGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT = "crossDomainEscrowGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT = "crossDomainRewardGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT = "crossDomainWithdrawalGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_RELAY_GAS_LIMIT = "crossDomainRelayGasLimit"; bytes32 internal constant SETTING_ETHER_WRAPPER_MAX_ETH = "etherWrapperMaxETH"; bytes32 internal constant SETTING_ETHER_WRAPPER_MINT_FEE_RATE = "etherWrapperMintFeeRate"; bytes32 internal constant SETTING_ETHER_WRAPPER_BURN_FEE_RATE = "etherWrapperBurnFeeRate"; bytes32 internal constant SETTING_WRAPPER_MAX_TOKEN_AMOUNT = "wrapperMaxTokens"; bytes32 internal constant SETTING_WRAPPER_MINT_FEE_RATE = "wrapperMintFeeRate"; bytes32 internal constant SETTING_WRAPPER_BURN_FEE_RATE = "wrapperBurnFeeRate"; bytes32 internal constant SETTING_MIN_CRATIO = "minCratio"; bytes32 internal constant SETTING_NEW_COLLATERAL_MANAGER = "newCollateralManager"; bytes32 internal constant SETTING_INTERACTION_DELAY = "interactionDelay"; bytes32 internal constant SETTING_COLLAPSE_FEE_RATE = "collapseFeeRate"; bytes32 internal constant SETTING_ATOMIC_MAX_VOLUME_PER_BLOCK = "atomicMaxVolumePerBlock"; bytes32 internal constant SETTING_ATOMIC_TWAP_WINDOW = "atomicTwapWindow"; bytes32 internal constant SETTING_ATOMIC_EQUIVALENT_FOR_DEX_PRICING = "atomicEquivalentForDexPricing"; bytes32 internal constant SETTING_ATOMIC_EXCHANGE_FEE_RATE = "atomicExchangeFeeRate"; bytes32 internal constant SETTING_ATOMIC_PRICE_BUFFER = "atomicPriceBuffer"; bytes32 internal constant SETTING_ATOMIC_VOLATILITY_CONSIDERATION_WINDOW = "atomicVolConsiderationWindow"; bytes32 internal constant SETTING_ATOMIC_VOLATILITY_UPDATE_THRESHOLD = "atomicVolUpdateThreshold"; bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage"; enum CrossDomainMessageGasLimits {Deposit, Escrow, Reward, Withdrawal, Relay} constructor(address _resolver) internal MixinResolver(_resolver) {} function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](1); addresses[0] = CONTRACT_FLEXIBLESTORAGE; } function flexibleStorage() internal view returns (IFlexibleStorage) { return IFlexibleStorage(requireAndGetAddress(CONTRACT_FLEXIBLESTORAGE)); } function _getGasLimitSetting(CrossDomainMessageGasLimits gasLimitType) internal pure returns (bytes32) { if (gasLimitType == CrossDomainMessageGasLimits.Deposit) { return SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Escrow) { return SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Reward) { return SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Withdrawal) { return SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Relay) { return SETTING_CROSS_DOMAIN_RELAY_GAS_LIMIT; } else { revert("Unknown gas limit type"); } } function getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits gasLimitType) internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, _getGasLimitSetting(gasLimitType)); } function getTradingRewardsEnabled() internal view returns (bool) { return flexibleStorage().getBoolValue(SETTING_CONTRACT_NAME, SETTING_TRADING_REWARDS_ENABLED); } function getWaitingPeriodSecs() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_WAITING_PERIOD_SECS); } function getPriceDeviationThresholdFactor() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR); } function getIssuanceRatio() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ISSUANCE_RATIO); } function getFeePeriodDuration() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_FEE_PERIOD_DURATION); } function getTargetThreshold() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_TARGET_THRESHOLD); } function getLiquidationDelay() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_DELAY); } function getLiquidationRatio() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_RATIO); } function getLiquidationPenalty() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_PENALTY); } function getRateStalePeriod() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_RATE_STALE_PERIOD); } function getExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_EXCHANGE_FEE_RATE, currencyKey)) ); } function getMinimumStakeTime() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_MINIMUM_STAKE_TIME); } function getAggregatorWarningFlags() internal view returns (address) { return flexibleStorage().getAddressValue(SETTING_CONTRACT_NAME, SETTING_AGGREGATOR_WARNING_FLAGS); } function getDebtSnapshotStaleTime() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_DEBT_SNAPSHOT_STALE_TIME); } function getEtherWrapperMaxETH() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MAX_ETH); } function getEtherWrapperMintFeeRate() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MINT_FEE_RATE); } function getEtherWrapperBurnFeeRate() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_BURN_FEE_RATE); } function getWrapperMaxTokenAmount(address wrapper) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_WRAPPER_MAX_TOKEN_AMOUNT, wrapper)) ); } function getWrapperMintFeeRate(address wrapper) internal view returns (int) { return flexibleStorage().getIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_WRAPPER_MINT_FEE_RATE, wrapper)) ); } function getWrapperBurnFeeRate(address wrapper) internal view returns (int) { return flexibleStorage().getIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_WRAPPER_BURN_FEE_RATE, wrapper)) ); } function getMinCratio(address collateral) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_MIN_CRATIO, collateral)) ); } function getNewCollateralManager(address collateral) internal view returns (address) { return flexibleStorage().getAddressValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_NEW_COLLATERAL_MANAGER, collateral)) ); } function getInteractionDelay(address collateral) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_INTERACTION_DELAY, collateral)) ); } function getCollapseFeeRate(address collateral) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_COLLAPSE_FEE_RATE, collateral)) ); } function getAtomicMaxVolumePerBlock() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ATOMIC_MAX_VOLUME_PER_BLOCK); } function getAtomicTwapWindow() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ATOMIC_TWAP_WINDOW); } function getAtomicEquivalentForDexPricing(bytes32 currencyKey) internal view returns (address) { return flexibleStorage().getAddressValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_ATOMIC_EQUIVALENT_FOR_DEX_PRICING, currencyKey)) ); } function getAtomicExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_ATOMIC_EXCHANGE_FEE_RATE, currencyKey)) ); } function getAtomicPriceBuffer(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_ATOMIC_PRICE_BUFFER, currencyKey)) ); } function getAtomicVolatilityConsiderationWindow(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_ATOMIC_VOLATILITY_CONSIDERATION_WINDOW, currencyKey)) ); } function getAtomicVolatilityUpdateThreshold(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_ATOMIC_VOLATILITY_UPDATE_THRESHOLD, currencyKey)) ); } } pragma experimental ABIEncoderV2; interface IOwnerRelayOnOptimism { function finalizeRelay(address target, bytes calldata payload) external; function finalizeRelayBatch(address[] calldata target, bytes[] calldata payloads) external; } // SPDX-License-Identifier: MIT /** * @title iAbs_BaseCrossDomainMessenger */ interface iAbs_BaseCrossDomainMessenger { /********** * Events * **********/ event SentMessage(bytes message); event RelayedMessage(bytes32 msgHash); event FailedRelayedMessage(bytes32 msgHash); /************* * Variables * *************/ function xDomainMessageSender() external view returns (address); /******************** * Public Functions * ********************/ /** * Sends a cross domain message to the target messenger. * @param _target Target contract address. * @param _message Message to send to the target. * @param _gasLimit Gas limit for the provided message. */ function sendMessage( address _target, bytes calldata _message, uint32 _gasLimit ) external; } // Inheritance // Internal references contract OwnerRelayOnEthereum is MixinSystemSettings, Owned { /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_EXT_MESSENGER = "ext:Messenger"; bytes32 private constant CONTRACT_OVM_OWNER_RELAY_ON_OPTIMISM = "ovm:OwnerRelayOnOptimism"; // ========== CONSTRUCTOR ========== constructor(address _owner, address _resolver) public Owned(_owner) MixinSystemSettings(_resolver) {} /* ========== INTERNALS ============ */ function _messenger() private view returns (iAbs_BaseCrossDomainMessenger) { return iAbs_BaseCrossDomainMessenger(requireAndGetAddress(CONTRACT_EXT_MESSENGER)); } function _ownerRelayOnOptimism() private view returns (address) { return requireAndGetAddress(CONTRACT_OVM_OWNER_RELAY_ON_OPTIMISM); } function _getCrossDomainGasLimit(uint32 crossDomainGasLimit) private view returns (uint32) { // Use specified crossDomainGasLimit if specified value is not zero. // otherwise use the default in SystemSettings. return crossDomainGasLimit != 0 ? crossDomainGasLimit : uint32(getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits.Relay)); } /* ========== VIEWS ========== */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](2); newAddresses[0] = CONTRACT_EXT_MESSENGER; newAddresses[1] = CONTRACT_OVM_OWNER_RELAY_ON_OPTIMISM; addresses = combineArrays(existingAddresses, newAddresses); } /* ========== RESTRICTED ========== */ function initiateRelay( address target, bytes calldata payload, uint32 crossDomainGasLimit // If zero, uses default value in SystemSettings ) external onlyOwner { IOwnerRelayOnOptimism ownerRelayOnOptimism; bytes memory messageData = abi.encodeWithSelector(ownerRelayOnOptimism.finalizeRelay.selector, target, payload); _messenger().sendMessage(_ownerRelayOnOptimism(), messageData, _getCrossDomainGasLimit(crossDomainGasLimit)); emit RelayInitiated(target, payload); } function initiateRelayBatch( address[] calldata targets, bytes[] calldata payloads, uint32 crossDomainGasLimit // If zero, uses default value in SystemSettings ) external onlyOwner { // First check that the length of the arguments match require(targets.length == payloads.length, "Argument length mismatch"); IOwnerRelayOnOptimism ownerRelayOnOptimism; bytes memory messageData = abi.encodeWithSelector(ownerRelayOnOptimism.finalizeRelayBatch.selector, targets, payloads); _messenger().sendMessage(_ownerRelayOnOptimism(), messageData, _getCrossDomainGasLimit(crossDomainGasLimit)); emit RelayBatchInitiated(targets, payloads); } /* ========== EVENTS ========== */ event RelayInitiated(address target, bytes payload); event RelayBatchInitiated(address[] targets, bytes[] payloads); }
Use specified crossDomainGasLimit if specified value is not zero. otherwise use the default in SystemSettings.
function _getCrossDomainGasLimit(uint32 crossDomainGasLimit) private view returns (uint32) { return crossDomainGasLimit != 0 ? crossDomainGasLimit : uint32(getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits.Relay)); }
7,872,425
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.4; //import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract GHCBridge is Ownable { using SafeMath for uint256; address payable public admin; // Admin account/server that calls withdrawTo ERC20 public token; // Token that will be withdrawn/deposited. This should be a GHC token. address payable public addrDeveloper; // Developer address (for developer commision) uint256 public developerCommission = 1; // Developer commission amount (1%) uint256 public gasTax = 10000000000000000; // Gas tax (ETH or BNB) to collect in order to fund bridge transactions. /** Nonce to prevent duplicate transactions */ uint public nonce; mapping(uint => bool) public processedNonces; /** Event that is emitted for a deposit or a withdraw */ enum Action { Deposit, Withdrawal } event Transfer(address from, address to, uint amount, uint nonce, Action indexed action); event TransferToDev(uint256 amount); /** Constructor */ constructor(address _admin, address _token, address _devAddress) { admin = payable(_admin); token = ERC20(_token); addrDeveloper = payable(_devAddress); // Make the admin the owner of the bridge... transferOwnership(admin); } /** Updates admin address */ function setAdminAddress(address _admin) public onlyOwner { admin = payable(_admin); } /** Updates developer address */ function setDeveloperAddress(address _addrDeveloper) public onlyOwner { addrDeveloper = payable(_addrDeveloper); } /** Updates developer commission percentage */ function setGasTax(uint256 _gasTax) public onlyOwner { require(_gasTax >= 0, "Gas tax must be >= 0"); gasTax = _gasTax; } /** Updates developer commission percentage */ function setDeveloperCommission(uint256 _developerCommission) public onlyOwner { require(_developerCommission >= 0, "Developer commission must be >= 0"); developerCommission = _developerCommission; } /** if for some reason BNB or ETH builds up in this contract, remove it **/ function withdrawBaseCurrency(uint256 amount) public onlyOwner { (bool success, ) = addrDeveloper.call{ value: amount }(""); require(success, "Withdrawal of ETH failed."); } /** Returns the balance in the Bridge */ function balance() public view returns (uint256) { return token.balanceOf(address(this)); } /** Deposit {amount} tokens into the vault */ function depositFrom(uint256 amount) public payable { require(amount > 0, "Amount must be > 0 to deposit"); require(token.balanceOf(msg.sender) >= amount, "Cannot deposit more than your balance"); require(msg.value >= 10000000000000000, "Must pay bridge fee"); // require a BNB or ETH fee of 0.01 (bool success, ) = admin.call{ value: address(this).balance }(""); require(success, "Forwarding of ETH failed."); uint256 devFee = (amount.mul(developerCommission)).div(100); if (devFee > 0) { amount = amount.sub(devFee); token.transferFrom(msg.sender, addrDeveloper, devFee); emit TransferToDev(devFee); } // Transfer remaining tokens from the {from} address to the {admin} address... token.transferFrom(msg.sender, address(this), amount); emit Transfer(msg.sender, address(this), amount, nonce, Action.Deposit); nonce++; } /** Withdraw {amount} tokens from the vault and send to {to} */ function withdrawTo(address to, uint256 amount, uint otherChainNonce) public { require(msg.sender == admin, "Only admin may withdraw from the vault"); require(token.balanceOf(address(this)) >= amount, "Cannot withdraw more than the vault balance"); require(processedNonces[otherChainNonce] == false, 'transfer already processed'); processedNonces[otherChainNonce] = true; // Transfer remaining tokens from the {admin} address to the {to} address... token.transfer(to, amount); emit Transfer(admin, to, amount, otherChainNonce, Action.Withdrawal); } /** Emergency Withdraw {amount} tokens from the vault and send to {to} */ function emergencyWithdraw(address to, uint256 amount) public onlyOwner{ require(token.balanceOf(address(this)) >= amount, "Cannot withdraw more than the vault balance"); // Transfer remaining tokens from the {admin} address to the {to} address... token.transfer(to, amount); emit Transfer(admin, to, amount, 0, Action.Withdrawal); } fallback() external payable { } receive() external payable { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: 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) { return msg.data; } }
Updates developer address /
function setDeveloperAddress(address _addrDeveloper) public onlyOwner { addrDeveloper = payable(_addrDeveloper); }
6,216,505
./partial_match/1/0x4986d7BEe120DF657fcA29cc11BF0B04836118a2/sources/src/Donate.sol
The transfer function the transfers tokens to the specified address. If you specify 0, it will withdraw the entire balance. _token The address of the token to transfer. (for ETH address(0)) _to Address who will receive the tokens. _amount The amount of the token to transfer./
function _transfer(IERC20 _token, address _to, uint256 _amount) private onlyOwner { _amount = _amount == 0 ? _token.universalBalanceOf(address(this)) : _amount; _token.universalTransfer(_to, _amount); }
2,706,999
// SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; import "../../openzeppelin/SafeERC20.sol"; import "../../openzeppelin/IERC20.sol"; import "../interface/IStrategy.sol"; import "../interface/IStrategySplitter.sol"; import "../interface/ISmartVault.sol"; import "../interface/IFeeRewardForwarder.sol"; import "../interface/IBookkeeper.sol"; import "../interface/IUpgradeSource.sol"; import "../interface/IFundKeeper.sol"; import "../interface/ITetuProxy.sol"; import "../interface/IMintHelper.sol"; import "../interface/IAnnouncer.sol"; import "../interface/strategies/IBalancingStrategy.sol"; import "./ControllerStorage.sol"; import "./ControllableV2.sol"; /// @title A central contract for control everything. /// Governance is a Multi-Sig Wallet /// @dev Use with TetuProxy /// @author belbix contract Controller is Initializable, ControllableV2, ControllerStorage { using SafeERC20 for IERC20; using Address for address; // ************ VARIABLES ********************** /// @notice Version of the contract /// @dev Should be incremented when contract is changed string public constant VERSION = "1.4.1"; /// @dev Allowed contracts to deposit in the vaults mapping(address => bool) public override whiteList; /// @dev Registered vaults mapping(address => bool) public override vaults; /// @dev Registered strategies mapping(address => bool) public override strategies; /// @dev Allowed addresses for maintenance work mapping(address => bool) public hardWorkers; /// @dev Allowed address for reward distributing mapping(address => bool) public rewardDistribution; /// @dev Allowed address for getting 100% rewards without vesting mapping(address => bool) public pureRewardConsumers; // ************ EVENTS ********************** /// @notice HardWorker added event HardWorkerAdded(address value); /// @notice HardWorker removed event HardWorkerRemoved(address value); /// @notice Contract whitelist status changed event WhiteListStatusChanged(address target, bool status); /// @notice Vault and Strategy pair registered event VaultAndStrategyAdded(address vault, address strategy); /// @notice Tokens moved from Controller contract to Governance event ControllerTokenMoved(address indexed recipient, address indexed token, uint256 amount); /// @notice Tokens moved from Strategy contract to Governance event StrategyTokenMoved(address indexed strategy, address indexed token, uint256 amount); /// @notice Tokens moved from Fund contract to Controller event FundKeeperTokenMoved(address indexed fund, address indexed token, uint256 amount); /// @notice DoHardWork completed and PricePerFullShare changed event SharePriceChangeLog( address indexed vault, address indexed strategy, uint256 oldSharePrice, uint256 newSharePrice, uint256 timestamp ); event VaultStrategyChanged(address vault, address oldStrategy, address newStrategy); event ProxyUpgraded(address target, address oldLogic, address newLogic); event Minted( address mintHelper, uint totalAmount, address distributor, address otherNetworkFund, bool mintAllAvailable ); event DistributorChanged(address distributor); /// @notice Initialize contract after setup it as proxy implementation /// @dev Use it only once after first logic setup /// Initialize Controllable with sender address /// Setup default values for PS and Fund ratio function initialize() external initializer { ControllableV2.initializeControllable(address(this)); ControllerStorage.initializeControllerStorage( msg.sender ); // 100% by default setPSNumeratorDenominator(1000, 1000); // 10% by default setFundNumeratorDenominator(100, 1000); } // ************* MODIFIERS AND FUNCTIONS FOR STRICT ACCESS ******************** /// @dev Operations allowed only for Governance address function onlyGovernance() view private { require(_governance() == msg.sender, "C: Not governance"); } /// @dev Operations allowed for Governance or Dao addresses function onlyGovernanceOrDao() view private { require(_governance() == msg.sender || _dao() == msg.sender, "C: Not governance or dao"); } /// @dev Operation should be announced (exist in timeLockSchedule map) or new value function timeLock( bytes32 opHash, IAnnouncer.TimeLockOpCodes opCode, bool isEmptyValue, address target ) private { // empty values setup without time-lock if (!isEmptyValue) { require(_announcer() != address(0), "C: Zero announcer"); require(IAnnouncer(_announcer()).timeLockSchedule(opHash) > 0, "C: Not announced"); require(IAnnouncer(_announcer()).timeLockSchedule(opHash) < block.timestamp, "C: Too early"); IAnnouncer(_announcer()).clearAnnounce(opHash, opCode, target); } } // ************ GOVERNANCE ACTIONS ************************** // ---------------------- TIME-LOCK ACTIONS -------------------------- /// @notice Only Governance can do it. Set announced strategies for given vaults /// @param _vaults Vault addresses /// @param _strategies Strategy addresses function setVaultStrategyBatch(address[] calldata _vaults, address[] calldata _strategies) external { onlyGovernance(); require(_vaults.length == _strategies.length, "C: Wrong arrays"); for (uint256 i = 0; i < _vaults.length; i++) { _setVaultStrategy(_vaults[i], _strategies[i]); } } /// @notice Only Governance can do it. Set announced strategy for given vault /// @param _target Vault address /// @param _strategy Strategy address function _setVaultStrategy(address _target, address _strategy) private { timeLock( keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.StrategyUpgrade, _target, _strategy)), IAnnouncer.TimeLockOpCodes.StrategyUpgrade, ISmartVault(_target).strategy() == address(0), _target ); emit VaultStrategyChanged(_target, ISmartVault(_target).strategy(), _strategy); ISmartVault(_target).setStrategy(_strategy); } function addStrategiesToSplitter(address _splitter, address[] calldata _strategies) external { onlyGovernance(); for (uint256 i = 0; i < _strategies.length; i++) { _addStrategyToSplitter(_splitter, _strategies[i]); } } /// @notice Only Governance can do it. Add new strategy to given splitter function _addStrategyToSplitter(address _splitter, address _strategy) internal { timeLock( keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.StrategyUpgrade, _splitter, _strategy)), IAnnouncer.TimeLockOpCodes.StrategyUpgrade, !IStrategySplitter(_splitter).strategiesInited(), _splitter ); IStrategySplitter(_splitter).addStrategy(_strategy); rewardDistribution[_strategy] = true; if (!strategies[_strategy]) { strategies[_strategy] = true; IBookkeeper(_bookkeeper()).addStrategy(_strategy); } } /// @notice Only Governance can do it. Upgrade batch announced proxies /// @param _contracts Array of Proxy contract addresses for upgrade /// @param _implementations Array of New implementation addresses function upgradeTetuProxyBatch( address[] calldata _contracts, address[] calldata _implementations ) external { onlyGovernance(); require(_contracts.length == _implementations.length, "wrong arrays"); for (uint256 i = 0; i < _contracts.length; i++) { _upgradeTetuProxy(_contracts[i], _implementations[i]); } } /// @notice Only Governance can do it. Upgrade announced proxy /// @param _contract Proxy contract address for upgrade /// @param _implementation New implementation address function _upgradeTetuProxy(address _contract, address _implementation) private { timeLock( keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.TetuProxyUpdate, _contract, _implementation)), IAnnouncer.TimeLockOpCodes.TetuProxyUpdate, false, _contract ); emit ProxyUpgraded(_contract, ITetuProxy(_contract).implementation(), _implementation); ITetuProxy(_contract).upgrade(_implementation); } /// @notice Only Governance can do it. Call announced mint /// @param totalAmount Total amount to mint. /// 33% will go to current network, 67% to FundKeeper for other networks /// @param mintAllAvailable if true instead of amount will be used maxTotalSupplyForCurrentBlock - totalSupply function mintAndDistribute( uint256 totalAmount, bool mintAllAvailable ) external { onlyGovernance(); timeLock( keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.Mint, totalAmount, distributor(), fund(), mintAllAvailable)), IAnnouncer.TimeLockOpCodes.Mint, false, address(0) ); require(distributor() != address(0), "C: Zero distributor"); require(fund() != address(0), "C: Zero fund"); IMintHelper(mintHelper()).mintAndDistribute(totalAmount, distributor(), fund(), mintAllAvailable); emit Minted(mintHelper(), totalAmount, distributor(), fund(), mintAllAvailable); } // ---------------------- TIME-LOCK ADDRESS CHANGE -------------------------- /// @notice Only Governance can do it. Change governance address. /// @param newValue New governance address function setGovernance(address newValue) external { onlyGovernance(); timeLock( keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.Governance, newValue)), IAnnouncer.TimeLockOpCodes.Governance, _governance() == address(0), address(0) ); _setGovernance(newValue); } /// @notice Only Governance can do it. Change DAO address. /// @param newValue New DAO address function setDao(address newValue) external { onlyGovernance(); timeLock( keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.Dao, newValue)), IAnnouncer.TimeLockOpCodes.Dao, _dao() == address(0), address(0) ); _setDao(newValue); } /// @notice Only Governance can do it. Change FeeRewardForwarder address. /// @param _feeRewardForwarder New FeeRewardForwarder address function setFeeRewardForwarder(address _feeRewardForwarder) external { onlyGovernance(); timeLock( keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.FeeRewardForwarder, _feeRewardForwarder)), IAnnouncer.TimeLockOpCodes.FeeRewardForwarder, feeRewardForwarder() == address(0), address(0) ); rewardDistribution[feeRewardForwarder()] = false; _setFeeRewardForwarder(_feeRewardForwarder); rewardDistribution[feeRewardForwarder()] = true; } /// @notice Only Governance can do it. Change Bookkeeper address. /// @param newValue New Bookkeeper address function setBookkeeper(address newValue) external { onlyGovernance(); timeLock( keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.Bookkeeper, newValue)), IAnnouncer.TimeLockOpCodes.Bookkeeper, _bookkeeper() == address(0), address(0) ); _setBookkeeper(newValue); } /// @notice Only Governance can do it. Change MintHelper address. /// @param _newValue New MintHelper address function setMintHelper(address _newValue) external { onlyGovernance(); timeLock( keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.MintHelper, _newValue)), IAnnouncer.TimeLockOpCodes.MintHelper, mintHelper() == address(0), address(0) ); _setMintHelper(_newValue); // for reduce the chance of DoS check new implementation require(IMintHelper(mintHelper()).devFundsList(0) != address(0), "C: Wrong"); } /// @notice Only Governance can do it. Change RewardToken(TETU) address. /// @param _newValue New RewardToken address function setRewardToken(address _newValue) external { onlyGovernance(); timeLock( keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.RewardToken, _newValue)), IAnnouncer.TimeLockOpCodes.RewardToken, rewardToken() == address(0), address(0) ); _setRewardToken(_newValue); } /// @notice Only Governance can do it. Change FundToken(USDC by default) address. /// @param _newValue New FundToken address function setFundToken(address _newValue) external { onlyGovernance(); timeLock( keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.FundToken, _newValue)), IAnnouncer.TimeLockOpCodes.FundToken, fundToken() == address(0), address(0) ); _setFundToken(_newValue); } /// @notice Only Governance can do it. Change ProfitSharing vault address. /// @param _newValue New ProfitSharing vault address function setPsVault(address _newValue) external { onlyGovernance(); timeLock( keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.PsVault, _newValue)), IAnnouncer.TimeLockOpCodes.PsVault, psVault() == address(0), address(0) ); _setPsVault(_newValue); } /// @notice Only Governance can do it. Change FundKeeper address. /// @param _newValue New FundKeeper address function setFund(address _newValue) external { onlyGovernance(); timeLock( keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.Fund, _newValue)), IAnnouncer.TimeLockOpCodes.Fund, fund() == address(0), address(0) ); _setFund(_newValue); } /// @notice Only Governance can do it. Change Announcer address. /// Has dedicated time-lock logic for avoiding collisions. /// @param _newValue New Announcer address function setAnnouncer(address _newValue) external { onlyGovernance(); bytes32 opHash = keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.Announcer, _newValue)); if (_announcer() != address(0)) { require(IAnnouncer(_announcer()).timeLockSchedule(opHash) > 0, "C: Not announced"); require(IAnnouncer(_announcer()).timeLockSchedule(opHash) < block.timestamp, "C: Too early"); } _setAnnouncer(_newValue); // clear announce after update not necessary // check new announcer implementation for reducing the chance of DoS IAnnouncer.TimeLockInfo memory info = IAnnouncer(_announcer()).timeLockInfo(0); require(info.opCode == IAnnouncer.TimeLockOpCodes.ZeroPlaceholder, "C: Wrong"); } /// @notice Only Governance can do it. Change FundKeeper address. /// @param _newValue New FundKeeper address function setVaultController(address _newValue) external { onlyGovernance(); timeLock( keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.VaultController, _newValue)), IAnnouncer.TimeLockOpCodes.VaultController, vaultController() == address(0), address(0) ); _setVaultController(_newValue); } // ------------------ TIME-LOCK RATIO CHANGE ------------------- /// @notice Only Governance or DAO can do it. Change Profit Sharing fee ratio. /// numerator/denominator = ratio /// @param numerator Ratio numerator. Should be less than denominator /// @param denominator Ratio denominator. Should be greater than zero function setPSNumeratorDenominator(uint256 numerator, uint256 denominator) public override { onlyGovernanceOrDao(); timeLock( keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.PsRatio, numerator, denominator)), IAnnouncer.TimeLockOpCodes.PsRatio, psNumerator() == 0 && psDenominator() == 0, address(0) ); _setPsNumerator(numerator); _setPsDenominator(denominator); } /// @notice Only Governance or DAO can do it. Change Fund fee ratio. /// numerator/denominator = ratio /// @param numerator Ratio numerator. Should be less than denominator /// @param denominator Ratio denominator. Should be greater than zero function setFundNumeratorDenominator(uint256 numerator, uint256 denominator) public override { onlyGovernanceOrDao(); timeLock( keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.FundRatio, numerator, denominator)), IAnnouncer.TimeLockOpCodes.FundRatio, fundNumerator() == 0 && fundDenominator() == 0, address(0) ); _setFundNumerator(numerator); _setFundDenominator(denominator); } // ------------------ TIME-LOCK TOKEN MOVEMENTS ------------------- /// @notice Only Governance can do it. Transfer token from this contract to governance address /// @param _recipient Recipient address /// @param _token Token address /// @param _amount Token amount function controllerTokenMove(address _recipient, address _token, uint256 _amount) external { onlyGovernance(); timeLock( keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.ControllerTokenMove, _recipient, _token, _amount)), IAnnouncer.TimeLockOpCodes.ControllerTokenMove, false, address(0) ); IERC20(_token).safeTransfer(_recipient, _amount); emit ControllerTokenMoved(_recipient, _token, _amount); } /// @notice Only Governance can do it. Transfer token from strategy to governance address /// @param _strategy Strategy address /// @param _token Token address /// @param _amount Token amount function strategyTokenMove(address _strategy, address _token, uint256 _amount) external { onlyGovernance(); timeLock( keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.StrategyTokenMove, _strategy, _token, _amount)), IAnnouncer.TimeLockOpCodes.StrategyTokenMove, false, address(0) ); // the strategy is responsible for maintaining the list of // salvageable tokens, to make sure that governance cannot come // in and take away the coins IStrategy(_strategy).salvage(_governance(), _token, _amount); emit StrategyTokenMoved(_strategy, _token, _amount); } /// @notice Only Governance can do it. Transfer token from FundKeeper to controller /// @param _fund FundKeeper address /// @param _token Token address /// @param _amount Token amount function fundKeeperTokenMove(address _fund, address _token, uint256 _amount) external { onlyGovernance(); timeLock( keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.FundTokenMove, _fund, _token, _amount)), IAnnouncer.TimeLockOpCodes.FundTokenMove, false, address(0) ); IFundKeeper(_fund).withdrawToController(_token, _amount); emit FundKeeperTokenMoved(_fund, _token, _amount); } // ---------------- NO TIME_LOCK -------------------------- /// @notice Only Governance can do it. Set reward distributor address. /// Distributor is a part of not critical infrastructure contracts and not require time-lock /// @param _distributor New distributor address function setDistributor(address _distributor) external { onlyGovernance(); require(_distributor != address(0)); _setDistributor(_distributor); emit DistributorChanged(_distributor); } /// @notice Only Governance can do it. Add/Remove Reward Distributor address /// @param _newRewardDistribution Reward Distributor's addresses /// @param _flag Reward Distributor's flags - true active, false deactivated function setRewardDistribution(address[] calldata _newRewardDistribution, bool _flag) external { onlyGovernance(); for (uint256 i = 0; i < _newRewardDistribution.length; i++) { rewardDistribution[_newRewardDistribution[i]] = _flag; } } /// @notice Only Governance can do it. Allow given addresses claim rewards without any penalty function setPureRewardConsumers(address[] calldata _targets, bool _flag) external { onlyGovernance(); for (uint256 i = 0; i < _targets.length; i++) { pureRewardConsumers[_targets[i]] = _flag; } } /// @notice Only Governance can do it. Add HardWorker address. /// @param _worker New HardWorker address function addHardWorker(address _worker) external { onlyGovernance(); require(_worker != address(0)); hardWorkers[_worker] = true; emit HardWorkerAdded(_worker); } /// @notice Only Governance can do it. Remove HardWorker address. /// @param _worker Exist HardWorker address function removeHardWorker(address _worker) external { onlyGovernance(); require(_worker != address(0)); hardWorkers[_worker] = false; emit HardWorkerRemoved(_worker); } /// @notice Only Governance or DAO can do it. Add to whitelist an array of addresses /// @param _targets An array of contracts function changeWhiteListStatus(address[] calldata _targets, bool status) external override { onlyGovernanceOrDao(); for (uint256 i = 0; i < _targets.length; i++) { whiteList[_targets[i]] = status; emit WhiteListStatusChanged(_targets[i], status); } } /// @notice Only Governance can do it. Register pairs Vault/Strategy /// @param _vaults Vault addresses /// @param _strategies Strategy addresses function addVaultsAndStrategies(address[] memory _vaults, address[] memory _strategies) external override { onlyGovernance(); require(_vaults.length == _strategies.length, "arrays wrong length"); for (uint256 i = 0; i < _vaults.length; i++) { _addVaultAndStrategy(_vaults[i], _strategies[i]); } } /// @notice Only Governance can do it. Register a pair Vault/Strategy /// @param _vault Vault addresses /// @param _strategy Strategy addresses function _addVaultAndStrategy(address _vault, address _strategy) private { require(_vault != address(0), "new vault shouldn't be empty"); require(!vaults[_vault], "vault already exists"); require(!strategies[_strategy], "strategy already exists"); require(_strategy != address(0), "new strategy must not be empty"); require(IControllable(_vault).isController(address(this))); vaults[_vault] = true; IBookkeeper(_bookkeeper()).addVault(_vault); // adding happens while setting _setVaultStrategy(_vault, _strategy); emit VaultAndStrategyAdded(_vault, _strategy); } /// @notice Only Vault can do it. Register Strategy. Vault call it when governance set a strategy /// @param _strategy Strategy addresses function addStrategy(address _strategy) external override { require(vaults[msg.sender], "C: Not vault"); if (!strategies[_strategy]) { strategies[_strategy] = true; IBookkeeper(_bookkeeper()).addStrategy(_strategy); } } /// @notice Only Governance or HardWorker can do it. Call doHardWork from given Vault /// @param _vault Vault addresses function doHardWork(address _vault) external { require(hardWorkers[msg.sender] || _isGovernance(msg.sender), "C: Not hardworker or governance"); require(vaults[_vault], "C: Not vault"); uint256 oldSharePrice = ISmartVault(_vault).getPricePerFullShare(); ISmartVault(_vault).doHardWork(); emit SharePriceChangeLog( _vault, ISmartVault(_vault).strategy(), oldSharePrice, ISmartVault(_vault).getPricePerFullShare(), block.timestamp ); } /// @notice Only HardWorker can do it. Call rebalanceAllPipes for given Strategy (AMB Platform) /// @param _strategy Vault addresses function rebalance(address _strategy) external override { require(hardWorkers[msg.sender], "C: Not hardworker"); require(strategies[_strategy], "C: Not strategy"); IBalancingStrategy(_strategy).rebalanceAllPipes(); } // ***************** EXTERNAL ******************************* /// @notice Return true if the given address is DAO /// @param _adr Address for check /// @return true if it is a DAO address function isDao(address _adr) external view override returns (bool) { return _dao() == _adr; } /// @notice Return true if the given address is a HardWorker or Governance /// @param _adr Address for check /// @return true if it is a HardWorker or Governance function isHardWorker(address _adr) external override view returns (bool) { return hardWorkers[_adr] || _governance() == _adr; } /// @notice Return true if the given address is a Reward Distributor or Governance or Strategy /// @param _adr Address for check /// @return true if it is a Reward Distributor or Governance or Strategy function isRewardDistributor(address _adr) external override view returns (bool) { return rewardDistribution[_adr] || _governance() == _adr || strategies[_adr]; } /// @notice Return true if the given address is allowed for claim rewards without penalties function isPoorRewardConsumer(address _adr) external override view returns (bool) { return pureRewardConsumers[_adr]; } /// @notice Return true if the given address: /// - is not smart contract /// - added to whitelist /// - governance address /// - hardworker /// - reward distributor /// - registered vault /// - registered strategy /// @param _adr Address for check /// @return true if the address allowed function isAllowedUser(address _adr) external view override returns (bool) { return isNotSmartContract(_adr) || whiteList[_adr] || _governance() == _adr || hardWorkers[_adr] || rewardDistribution[_adr] || pureRewardConsumers[_adr] || vaults[_adr] || strategies[_adr]; } /// @notice Return true if given address is not a smart contract but a wallet address /// @dev it is not 100% guarantee after EIP-3074 implementation /// use it as an additional check /// @param _adr Address for check /// @return true if the address is a wallet function isNotSmartContract(address _adr) private view returns (bool) { return _adr == tx.origin; } /// @notice Return true if the given address is a registered vault /// @param _vault Address for check /// @return true if it is a registered vault function isValidVault(address _vault) external override view returns (bool) { return vaults[_vault]; } /// @notice Return true if the given address is a registered strategy /// @param _strategy Address for check /// @return true if it is a registered strategy function isValidStrategy(address _strategy) external override view returns (bool) { return strategies[_strategy]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface IStrategy { enum Platform { UNKNOWN, // 0 TETU, // 1 QUICK, // 2 SUSHI, // 3 WAULT, // 4 IRON, // 5 COSMIC, // 6 CURVE, // 7 DINO, // 8 IRON_LEND, // 9 HERMES, // 10 CAFE, // 11 TETU_SWAP, // 12 SPOOKY, // 13 AAVE_LEND, //14 AAVE_MAI_BAL, // 15 GEIST, //16 HARVEST, //17 SCREAM_LEND, //18 KLIMA, //19 VESQ, //20 QIDAO, //21 SUNFLOWER, //22 NACHO, //23 STRATEGY_SPLITTER, //24 TOMB, //25 TAROT, //26 BEETHOVEN, //27 IMPERMAX, //28 TETU_SF, //29 ALPACA, //30 MARKET, //31 UNIVERSE, //32 MAI_BAL, //33 UMA, //34 SPHERE, //35 BALANCER, //36 SLOT_37, //37 SLOT_38, //38 SLOT_39, //39 SLOT_40, //40 SLOT_41, //41 SLOT_42, //42 SLOT_43, //43 SLOT_44, //44 SLOT_45, //45 SLOT_46, //46 SLOT_47, //47 SLOT_48, //48 SLOT_49, //49 SLOT_50 //50 } // *************** GOVERNANCE ACTIONS ************** function STRATEGY_NAME() external view returns (string memory); function withdrawAllToVault() external; function withdrawToVault(uint256 amount) external; function salvage(address recipient, address token, uint256 amount) external; function doHardWork() external; function investAllUnderlying() external; function emergencyExit() external; function pauseInvesting() external; function continueInvesting() external; // **************** VIEWS *************** function rewardTokens() external view returns (address[] memory); function underlying() external view returns (address); function underlyingBalance() external view returns (uint256); function rewardPoolBalance() external view returns (uint256); function buyBackRatio() external view returns (uint256); function unsalvageableTokens(address token) external view returns (bool); function vault() external view returns (address); function investedUnderlyingBalance() external view returns (uint256); function platform() external view returns (Platform); function assets() external view returns (address[] memory); function pausedInvesting() external view returns (bool); function readyToClaim() external view returns (uint256[] memory); function poolTotalAmount() external view returns (uint256); } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface IStrategySplitter { function strategies(uint idx) external view returns (address); function strategiesRatios(address strategy) external view returns (uint); function withdrawRequestsCalls(address user) external view returns (uint); function addStrategy(address _strategy) external; function removeStrategy(address _strategy) external; function setStrategyRatios(address[] memory _strategies, uint[] memory _ratios) external; function strategiesInited() external view returns (bool); function needRebalance() external view returns (uint); function wantToWithdraw() external view returns (uint); function maxCheapWithdraw() external view returns (uint); function strategiesLength() external view returns (uint); function allStrategies() external view returns (address[] memory); function strategyRewardTokens() external view returns (address[] memory); } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface ISmartVault { function setStrategy(address _strategy) external; function changeActivityStatus(bool _active) external; function changeProtectionMode(bool _active) external; function changePpfsDecreaseAllowed(bool _value) external; function setLockPeriod(uint256 _value) external; function setLockPenalty(uint256 _value) external; function setToInvest(uint256 _value) external; function doHardWork() external; function rebalance() external; function disableLock() external; function notifyTargetRewardAmount(address _rewardToken, uint256 reward) external; function notifyRewardWithoutPeriodChange(address _rewardToken, uint256 reward) external; function deposit(uint256 amount) external; function depositAndInvest(uint256 amount) external; function depositFor(uint256 amount, address holder) external; function withdraw(uint256 numberOfShares) external; function exit() external; function getAllRewards() external; function getReward(address rt) external; function underlying() external view returns (address); function strategy() external view returns (address); function getRewardTokenIndex(address rt) external view returns (uint256); function getPricePerFullShare() external view returns (uint256); function underlyingUnit() external view returns (uint256); function duration() external view returns (uint256); function underlyingBalanceInVault() external view returns (uint256); function underlyingBalanceWithInvestment() external view returns (uint256); function underlyingBalanceWithInvestmentForHolder(address holder) external view returns (uint256); function availableToInvestOut() external view returns (uint256); function earned(address rt, address account) external view returns (uint256); function earnedWithBoost(address rt, address account) external view returns (uint256); function rewardPerToken(address rt) external view returns (uint256); function lastTimeRewardApplicable(address rt) external view returns (uint256); function rewardTokensLength() external view returns (uint256); function active() external view returns (bool); function rewardTokens() external view returns (address[] memory); function periodFinishForToken(address _rt) external view returns (uint256); function rewardRateForToken(address _rt) external view returns (uint256); function lastUpdateTimeForToken(address _rt) external view returns (uint256); function rewardPerTokenStoredForToken(address _rt) external view returns (uint256); function userRewardPerTokenPaidForToken(address _rt, address account) external view returns (uint256); function rewardsForToken(address _rt, address account) external view returns (uint256); function userLastWithdrawTs(address _user) external view returns (uint256); function userLastDepositTs(address _user) external view returns (uint256); function userBoostTs(address _user) external view returns (uint256); function userLockTs(address _user) external view returns (uint256); function addRewardToken(address rt) external; function removeRewardToken(address rt) external; function stop() external; function ppfsDecreaseAllowed() external view returns (bool); function lockPeriod() external view returns (uint256); function lockPenalty() external view returns (uint256); function toInvest() external view returns (uint256); function depositFeeNumerator() external view returns (uint256); function lockAllowed() external view returns (bool); function protectionMode() external view returns (bool); } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface IFeeRewardForwarder { function distribute(uint256 _amount, address _token, address _vault) external returns (uint256); function notifyPsPool(address _token, uint256 _amount) external returns (uint256); function notifyCustomPool(address _token, address _rewardPool, uint256 _maxBuyback) external returns (uint256); function liquidate(address tokenIn, address tokenOut, uint256 amount) external returns (uint256); } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface IBookkeeper { struct PpfsChange { address vault; uint256 block; uint256 time; uint256 value; uint256 oldBlock; uint256 oldTime; uint256 oldValue; } struct HardWork { address strategy; uint256 block; uint256 time; uint256 targetTokenAmount; } function addVault(address _vault) external; function addStrategy(address _strategy) external; function registerStrategyEarned(uint256 _targetTokenAmount) external; function registerFundKeeperEarned(address _token, uint256 _fundTokenAmount) external; function registerUserAction(address _user, uint256 _amount, bool _deposit) external; function registerVaultTransfer(address from, address to, uint256 amount) external; function registerUserEarned(address _user, address _vault, address _rt, uint256 _amount) external; function registerPpfsChange(address vault, uint256 value) external; function registerRewardDistribution(address vault, address token, uint256 amount) external; function vaults() external view returns (address[] memory); function vaultsLength() external view returns (uint256); function strategies() external view returns (address[] memory); function strategiesLength() external view returns (uint256); function lastPpfsChange(address vault) external view returns (PpfsChange memory); /// @notice Return total earned TETU tokens for strategy /// @dev Should be incremented after strategy rewards distribution /// @param strategy Strategy address /// @return Earned TETU tokens function targetTokenEarned(address strategy) external view returns (uint256); /// @notice Return share(xToken) balance of given user /// @dev Should be calculated for each xToken transfer /// @param vault Vault address /// @param user User address /// @return User share (xToken) balance function vaultUsersBalances(address vault, address user) external view returns (uint256); /// @notice Return earned token amount for given token and user /// @dev Fills when user claim rewards /// @param user User address /// @param vault Vault address /// @param token Token address /// @return User's earned tokens amount function userEarned(address user, address vault, address token) external view returns (uint256); function lastHardWork(address vault) external view returns (HardWork memory); /// @notice Return users quantity for given Vault /// @dev Calculation based in Bookkeeper user balances /// @param vault Vault address /// @return Users quantity function vaultUsersQuantity(address vault) external view returns (uint256); function fundKeeperEarned(address vault) external view returns (uint256); function vaultRewards(address vault, address token, uint256 idx) external view returns (uint256); function vaultRewardsLength(address vault, address token) external view returns (uint256); function strategyEarnedSnapshots(address strategy, uint256 idx) external view returns (uint256); function strategyEarnedSnapshotsTime(address strategy, uint256 idx) external view returns (uint256); function strategyEarnedSnapshotsLength(address strategy) external view returns (uint256); } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface IUpgradeSource { function scheduleUpgrade(address impl) external; function finalizeUpgrade() external; function shouldUpgrade() external view returns (bool, address); } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface IFundKeeper { function withdrawToController(address _token, uint256 amount) external; } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface ITetuProxy { function upgrade(address _newImplementation) external; function implementation() external returns (address); } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface IMintHelper { function mintAndDistribute( uint256 totalAmount, address _distributor, address _otherNetworkFund, bool mintAllAvailable ) external; function devFundsList(uint256 idx) external returns (address); } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface IAnnouncer { /// @dev Time lock operation codes enum TimeLockOpCodes { // TimeLockedAddresses Governance, // 0 Dao, // 1 FeeRewardForwarder, // 2 Bookkeeper, // 3 MintHelper, // 4 RewardToken, // 5 FundToken, // 6 PsVault, // 7 Fund, // 8 // TimeLockedRatios PsRatio, // 9 FundRatio, // 10 // TimeLockedTokenMoves ControllerTokenMove, // 11 StrategyTokenMove, // 12 FundTokenMove, // 13 // Other TetuProxyUpdate, // 14 StrategyUpgrade, // 15 Mint, // 16 Announcer, // 17 ZeroPlaceholder, //18 VaultController, //19 RewardBoostDuration, //20 RewardRatioWithoutBoost, //21 VaultStop //22 } /// @dev Holder for human readable info struct TimeLockInfo { TimeLockOpCodes opCode; bytes32 opHash; address target; address[] adrValues; uint256[] numValues; } function clearAnnounce(bytes32 opHash, TimeLockOpCodes opCode, address target) external; function timeLockSchedule(bytes32 opHash) external returns (uint256); function timeLockInfo(uint256 idx) external returns (TimeLockInfo memory); // ************ DAO ACTIONS ************* function announceRatioChange(TimeLockOpCodes opCode, uint256 numerator, uint256 denominator) external; } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface IBalancingStrategy { function rebalanceAllPipes() external; } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; import "../interface/IController.sol"; import "../../openzeppelin/Initializable.sol"; /// @title Eternal storage + getters and setters pattern /// @dev If a key value is changed it will be required to setup it again. /// @author belbix abstract contract ControllerStorage is Initializable, IController { // don't change names or ordering! mapping(bytes32 => uint256) private uintStorage; mapping(bytes32 => address) private addressStorage; /// @notice Address changed the variable with `name` event UpdatedAddressSlot(string indexed name, address oldValue, address newValue); /// @notice Value changed the variable with `name` event UpdatedUint256Slot(string indexed name, uint256 oldValue, uint256 newValue); /// @notice Initialize contract after setup it as proxy implementation /// @dev Use it only once after first logic setup /// @param __governance Governance address function initializeControllerStorage( address __governance ) public initializer { _setGovernance(__governance); } // ******************* SETTERS AND GETTERS ********************** // ----------- ADDRESSES ---------- function _setGovernance(address _address) internal { emit UpdatedAddressSlot("governance", _governance(), _address); setAddress("governance", _address); } /// @notice Return governance address /// @return Governance address function governance() external override view returns (address) { return _governance(); } function _governance() internal view returns (address) { return getAddress("governance"); } function _setDao(address _address) internal { emit UpdatedAddressSlot("dao", _dao(), _address); setAddress("dao", _address); } /// @notice Return DAO address /// @return DAO address function dao() external override view returns (address) { return _dao(); } function _dao() internal view returns (address) { return getAddress("dao"); } function _setFeeRewardForwarder(address _address) internal { emit UpdatedAddressSlot("feeRewardForwarder", feeRewardForwarder(), _address); setAddress("feeRewardForwarder", _address); } /// @notice Return FeeRewardForwarder address /// @return FeeRewardForwarder address function feeRewardForwarder() public override view returns (address) { return getAddress("feeRewardForwarder"); } function _setBookkeeper(address _address) internal { emit UpdatedAddressSlot("bookkeeper", _bookkeeper(), _address); setAddress("bookkeeper", _address); } /// @notice Return Bookkeeper address /// @return Bookkeeper address function bookkeeper() external override view returns (address) { return _bookkeeper(); } function _bookkeeper() internal view returns (address) { return getAddress("bookkeeper"); } function _setMintHelper(address _address) internal { emit UpdatedAddressSlot("mintHelper", mintHelper(), _address); setAddress("mintHelper", _address); } /// @notice Return MintHelper address /// @return MintHelper address function mintHelper() public override view returns (address) { return getAddress("mintHelper"); } function _setRewardToken(address _address) internal { emit UpdatedAddressSlot("rewardToken", rewardToken(), _address); setAddress("rewardToken", _address); } /// @notice Return TETU address /// @return TETU address function rewardToken() public override view returns (address) { return getAddress("rewardToken"); } function _setFundToken(address _address) internal { emit UpdatedAddressSlot("fundToken", fundToken(), _address); setAddress("fundToken", _address); } /// @notice Return a token address used for FundKeeper /// @return FundKeeper's main token address function fundToken() public override view returns (address) { return getAddress("fundToken"); } function _setPsVault(address _address) internal { emit UpdatedAddressSlot("psVault", psVault(), _address); setAddress("psVault", _address); } /// @notice Return Profit Sharing pool address /// @return Profit Sharing pool address function psVault() public override view returns (address) { return getAddress("psVault"); } function _setFund(address _address) internal { emit UpdatedAddressSlot("fund", fund(), _address); setAddress("fund", _address); } /// @notice Return FundKeeper address /// @return FundKeeper address function fund() public override view returns (address) { return getAddress("fund"); } function _setDistributor(address _address) internal { emit UpdatedAddressSlot("distributor", distributor(), _address); setAddress("distributor", _address); } /// @notice Return Reward distributor address /// @return Distributor address function distributor() public override view returns (address) { return getAddress("distributor"); } function _setAnnouncer(address _address) internal { emit UpdatedAddressSlot("announcer", _announcer(), _address); setAddress("announcer", _address); } /// @notice Return Announcer address /// @return Announcer address function announcer() external override view returns (address) { return _announcer(); } function _announcer() internal view returns (address) { return getAddress("announcer"); } function _setVaultController(address _address) internal { emit UpdatedAddressSlot("vaultController", vaultController(), _address); setAddress("vaultController", _address); } /// @notice Return FundKeeper address /// @return FundKeeper address function vaultController() public override view returns (address) { return getAddress("vaultController"); } // ----------- INTEGERS ---------- function _setPsNumerator(uint256 _value) internal { emit UpdatedUint256Slot("psNumerator", psNumerator(), _value); setUint256("psNumerator", _value); } /// @notice Return Profit Sharing pool ratio's numerator /// @return Profit Sharing pool ratio numerator function psNumerator() public view override returns (uint256) { return getUint256("psNumerator"); } function _setPsDenominator(uint256 _value) internal { emit UpdatedUint256Slot("psDenominator", psDenominator(), _value); setUint256("psDenominator", _value); } /// @notice Return Profit Sharing pool ratio's denominator /// @return Profit Sharing pool ratio denominator function psDenominator() public view override returns (uint256) { return getUint256("psDenominator"); } function _setFundNumerator(uint256 _value) internal { emit UpdatedUint256Slot("fundNumerator", fundNumerator(), _value); setUint256("fundNumerator", _value); } /// @notice Return FundKeeper ratio's numerator /// @return FundKeeper ratio numerator function fundNumerator() public view override returns (uint256) { return getUint256("fundNumerator"); } function _setFundDenominator(uint256 _value) internal { emit UpdatedUint256Slot("fundDenominator", fundDenominator(), _value); setUint256("fundDenominator", _value); } /// @notice Return FundKeeper ratio's denominator /// @return FundKeeper ratio denominator function fundDenominator() public view override returns (uint256) { return getUint256("fundDenominator"); } // ******************** STORAGE INTERNAL FUNCTIONS ******************** function setAddress(string memory key, address _address) private { addressStorage[keccak256(abi.encodePacked(key))] = _address; } function getAddress(string memory key) private view returns (address) { return addressStorage[keccak256(abi.encodePacked(key))]; } function setUint256(string memory key, uint256 _value) private { uintStorage[keccak256(abi.encodePacked(key))] = _value; } function getUint256(string memory key) private view returns (uint256) { return uintStorage[keccak256(abi.encodePacked(key))]; } //slither-disable-next-line unused-state uint256[50] private ______gap; } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; import "../../openzeppelin/Initializable.sol"; import "../interface/IControllable.sol"; import "../interface/IControllableExtended.sol"; import "../interface/IController.sol"; /// @title Implement basic functionality for any contract that require strict control /// V2 is optimised version for less gas consumption /// @dev Can be used with upgradeable pattern. /// Require call initializeControllable() in any case. /// @author belbix abstract contract ControllableV2 is Initializable, IControllable, IControllableExtended { bytes32 internal constant _CONTROLLER_SLOT = bytes32(uint256(keccak256("eip1967.controllable.controller")) - 1); bytes32 internal constant _CREATED_SLOT = bytes32(uint256(keccak256("eip1967.controllable.created")) - 1); bytes32 internal constant _CREATED_BLOCK_SLOT = bytes32(uint256(keccak256("eip1967.controllable.created_block")) - 1); event ContractInitialized(address controller, uint ts, uint block); /// @notice Initialize contract after setup it as proxy implementation /// Save block.timestamp in the "created" variable /// @dev Use it only once after first logic setup /// @param __controller Controller address function initializeControllable(address __controller) public initializer { _setController(__controller); _setCreated(block.timestamp); _setCreatedBlock(block.number); emit ContractInitialized(__controller, block.timestamp, block.number); } /// @dev Return true if given address is controller function isController(address _value) external override view returns (bool) { return _isController(_value); } function _isController(address _value) internal view returns (bool) { return _value == _controller(); } /// @notice Return true if given address is setup as governance in Controller function isGovernance(address _value) external override view returns (bool) { return _isGovernance(_value); } function _isGovernance(address _value) internal view returns (bool) { return IController(_controller()).governance() == _value; } // ************* SETTERS/GETTERS ******************* /// @notice Return controller address saved in the contract slot function controller() external view override returns (address) { return _controller(); } function _controller() internal view returns (address result) { bytes32 slot = _CONTROLLER_SLOT; assembly { result := sload(slot) } } /// @dev Set a controller address to contract slot function _setController(address _newController) private { require(_newController != address(0)); bytes32 slot = _CONTROLLER_SLOT; assembly { sstore(slot, _newController) } } /// @notice Return creation timestamp /// @return ts Creation timestamp function created() external view override returns (uint256 ts) { bytes32 slot = _CREATED_SLOT; assembly { ts := sload(slot) } } /// @dev Filled only once when contract initialized /// @param _value block.timestamp function _setCreated(uint256 _value) private { bytes32 slot = _CREATED_SLOT; assembly { sstore(slot, _value) } } /// @notice Return creation block number /// @return ts Creation block number function createdBlock() external view returns (uint256 ts) { bytes32 slot = _CREATED_BLOCK_SLOT; assembly { ts := sload(slot) } } /// @dev Filled only once when contract initialized /// @param _value block.number function _setCreatedBlock(uint256 _value) private { bytes32 slot = _CREATED_BLOCK_SLOT; assembly { sstore(slot, _value) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface IController { function addVaultsAndStrategies(address[] memory _vaults, address[] memory _strategies) external; function addStrategy(address _strategy) external; function governance() external view returns (address); function dao() external view returns (address); function bookkeeper() external view returns (address); function feeRewardForwarder() external view returns (address); function mintHelper() external view returns (address); function rewardToken() external view returns (address); function fundToken() external view returns (address); function psVault() external view returns (address); function fund() external view returns (address); function distributor() external view returns (address); function announcer() external view returns (address); function vaultController() external view returns (address); function whiteList(address _target) external view returns (bool); function vaults(address _target) external view returns (bool); function strategies(address _target) external view returns (bool); function psNumerator() external view returns (uint256); function psDenominator() external view returns (uint256); function fundNumerator() external view returns (uint256); function fundDenominator() external view returns (uint256); function isAllowedUser(address _adr) external view returns (bool); function isDao(address _adr) external view returns (bool); function isHardWorker(address _adr) external view returns (bool); function isRewardDistributor(address _adr) external view returns (bool); function isPoorRewardConsumer(address _adr) external view returns (bool); function isValidVault(address _vault) external view returns (bool); function isValidStrategy(address _strategy) external view returns (bool); function rebalance(address _strategy) external; // ************ DAO ACTIONS ************* function setPSNumeratorDenominator(uint256 numerator, uint256 denominator) external; function setFundNumeratorDenominator(uint256 numerator, uint256 denominator) external; function changeWhiteListStatus(address[] calldata _targets, bool status) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface IControllable { function isController(address _contract) external view returns (bool); function isGovernance(address _contract) external view returns (bool); } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; /// @dev This interface contains additional functions for Controllable class /// Don't extend the exist Controllable for the reason of huge coherence interface IControllableExtended { function created() external view returns (uint256 ts); function controller() external view returns (address adr); }
Return FundKeeper address return FundKeeper address
function fund() public override view returns (address) { return getAddress("fund"); }
14,500,981
./full_match/1/0x765f64Be4D190287E8049A71D12a334Fc52b8E0a/sources/contracts/vaults/Para4626.sol
Deposits weth into Bend pool and receive receipt tokens shares The amount of receipt tokens to mint receiver The account that will receive the receipt tokens return assets The amount of weth deposited
function mint( uint256 shares, address receiver ) external nonReentrant onlyRole(WHITELIST_ROLE) returns (uint256 assets) { if (shares == 0) { revert ParameterOutOfBounds(); } if (receiver == address(0)) { revert InvalidAddress(); } assets = previewMint(shares); _deposit(assets, shares, receiver); }
9,793,380
./partial_match/1/0xF2753202BA39dD25eA8D6D1D609a9021234943Fc/sources/contracts/modules/security/AuthorizationModule.sol
Grants the different roles to the account that deploys the contract./
function __AuthorizationModule_init_unchained( address admin ) internal onlyInitializing { if (admin == address(0)) revert Errors.AddressZeroNotAllowed(); _grantRole(DEFAULT_ADMIN_ROLE, admin); }
9,126,241
// SPDX-License-Identifier: MIT pragma solidity >= 0.4.0; contract Campaign { address manager; int contributorsCount = 0; // Provide a basic structure for each request to be created by manager struct Request { int approvalCount; string description; mapping(address => bool) approvals; address recipient; int value; bool isComplete; } mapping(address => bool) contributors; uint minimumContribution; Request[] requests; constructor(uint contribution) { manager = msg.sender; require(contribution > 0); minimumContribution = contribution; // Specify a minimum contributor } modifier restricted { require(msg.sender == manager); // Restrict some methods to manager capability _; } function contribute() external payable { require(msg.value > minimumContribution); // If contributor suceeds in minimum payment, add as contributor contributorsCount++; contributors[msg.sender] = true; } function createRequest(string memory desc, address r, int val) external restricted { Request memory newRequest = Request( 0, desc, r, val, false ); requests.push(newRequest); // Push requests to main list } function approveRequest(int index) external { // Run checks to see if contributor exists and if so, only deposited 1 vote require(contributors[msg.sender]); require(!requests[index].approvals[msg.sender]); requests[index].approvalCount++; requests[index].approvals[msg.sender] = true; // Increase approval count and add them to the map of approvers } function finalizeRequest(int index) external restricted { require(!requests[index]); // If the request was approved, no need to proceed /* *** --- READ ME --- *** Division of fractions not possible in solidity. So a workaround to check if 50% of approvals were received, I inverted the operation by dividing the total number of contributors by the number of approvals. The number should be 2 or less than 2 (inverse of 1/2 is 2). In order to make sure it is exactly 50% (or in this case, the inverse is exactly 2) make sure the remainder from the inverse division operation equates to 0. Solidity fails with modulo operations. So I ran a test to see if I subtract the remainder value from any count (approval/contributor any would work), I should return the count itself as subtracting 0 from anything does not change value. Complex work around for not being able to do decimal division to check 50% of voters or the modulo division. It is what it is. If you know Math, you know ;) */ int remainder = contributorsCount % requests[index].approvalCount; require(contributorsCount / requests[index].approvalCount <= 2); require(requests[index].approvalCount - remainder == 0); // If the checks pass, change approval status of given request to true. if (requests[index]) { requests[index].isComplete = true; } } }
If the checks pass, change approval status of given request to true.
function finalizeRequest(int index) external restricted { Division of fractions not possible in solidity. So a workaround to check if 50% of approvals were received, I inverted the operation by dividing the total number of contributors by the number of approvals. The number should be 2 or less than 2 (inverse of 1/2 is 2). In order to make sure it is exactly 50% (or in this case, the inverse is exactly 2) make sure the remainder from the inverse division operation equates to 0. Solidity fails with modulo operations. So I ran a test to see if I subtract the remainder value from any count (approval/contributor any would work), I should return the count itself as subtracting 0 from anything does not change value. Complex work around for not being able to do decimal division to check 50% of voters or the modulo division. It is what it is. If you know Math, you know ;) int remainder = contributorsCount % requests[index].approvalCount; require(contributorsCount / requests[index].approvalCount <= 2); require(requests[index].approvalCount - remainder == 0); if (requests[index]) { requests[index].isComplete = true; } }
14,115,361
./full_match/314/0x7b7f1f85F599b63432F5D782041c25Dad354f999/sources/node_modules/@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol
See {IERC721Receiver-onERC721Received}. Always returns `IERC721Receiver.onERC721Received.selector`./
function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) { return this.onERC721Received.selector; }
8,082,258
./full_match/1/0xa462127735352B1F03dA8Ab92a87803d05cc6a7B/sources/contracts/Aswang/AswangTribe.sol
Set a new $DUGO contract dugo New $DUGO contract/
function setDugo(IDugo dugo) external lockable onlyOwner { Dugo = dugo; }
8,311,079
./full_match/7700/0x9B2a63F27661A468E2da22226b64A4914144f195/sources/contracts/mixins/AgentMask.sol
Returns an agent key given a user, an agent address and a specific call path. /
function agentKey (address user, address agent, uint16 callPath) pure internal returns (bytes32) { return keccak256(abi.encode(user, agent, callPath)); }
4,651,177
./full_match/5/0x9368A0BDA86742Dc3E96140B4bD99eC86e0a1E3e/sources/contracts/module/NTS-Multi.sol
Calculates the total reward for all staked teams of the caller. return _TotalReward The total calculated reward for all staked teams of the caller./ Get the IDs of all staked teams owned by the caller. Calculate the total reward for all owned staked teams.
function _calRewardTeamAll(address _player) internal view returns (uint256 _TotalReward) { uint16[] memory _myStakeTeam = userStorage.getStakedUserTeam(_player); uint256 _totalReward = 0; for(uint16 i = 0; i < _myStakeTeam.length; i++) { _totalReward = _totalReward + _calRewardTeam(_player, _myStakeTeam[i]); } return _totalReward; }
7,047,288
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.4; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import { MintableBurnableIERC20 } from '../../../tokens/interfaces/MintableBurnableIERC20.sol'; import {SafeMath} from '@openzeppelin/contracts/utils/math/SafeMath.sol'; import { FixedPoint } from '@uma/core/contracts/common/implementation/FixedPoint.sol'; import { SafeERC20 } from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import {FeePayerPartyLib} from '../../common/FeePayerPartyLib.sol'; import { SelfMintingPerpetualPositionManagerMultiPartyLib } from './SelfMintingPerpetualPositionManagerMultiPartyLib.sol'; import {FeePayerParty} from '../../common/FeePayerParty.sol'; import { SelfMintingPerpetualLiquidatableMultiParty } from './SelfMintingPerpetualLiquidatableMultiParty.sol'; import { SelfMintingPerpetualPositionManagerMultiParty } from './SelfMintingPerpetualPositionManagerMultiParty.sol'; /** @title A library for SelfMintingPerpetualLiquidatableMultiParty contract */ library SelfMintingPerpetualLiquidatableMultiPartyLib { using SafeMath for uint256; using SafeERC20 for IERC20; using SafeERC20 for MintableBurnableIERC20; using FixedPoint for FixedPoint.Unsigned; using SelfMintingPerpetualPositionManagerMultiPartyLib for SelfMintingPerpetualPositionManagerMultiParty.PositionData; using FeePayerPartyLib for FixedPoint.Unsigned; using SelfMintingPerpetualPositionManagerMultiPartyLib for SelfMintingPerpetualPositionManagerMultiParty.PositionManagerData; using SelfMintingPerpetualLiquidatableMultiPartyLib for SelfMintingPerpetualLiquidatableMultiParty.LiquidationData; using SelfMintingPerpetualPositionManagerMultiPartyLib for FixedPoint.Unsigned; struct CreateLiquidationParams { FixedPoint.Unsigned minCollateralPerToken; FixedPoint.Unsigned maxCollateralPerToken; FixedPoint.Unsigned maxTokensToLiquidate; uint256 actualTime; uint256 deadline; FixedPoint.Unsigned finalFee; address sponsor; } struct CreateLiquidationCollateral { FixedPoint.Unsigned startCollateral; FixedPoint.Unsigned startCollateralNetOfWithdrawal; FixedPoint.Unsigned tokensLiquidated; FixedPoint.Unsigned finalFeeBond; address sponsor; } struct CreateLiquidationReturnParams { uint256 liquidationId; FixedPoint.Unsigned lockedCollateral; FixedPoint.Unsigned liquidatedCollateral; FixedPoint.Unsigned tokensLiquidated; FixedPoint.Unsigned finalFeeBond; } // Stores the parameters for a settlement after liquidation process struct SettleParams { FixedPoint.Unsigned feeAttenuation; FixedPoint.Unsigned settlementPrice; FixedPoint.Unsigned tokenRedemptionValue; FixedPoint.Unsigned collateral; FixedPoint.Unsigned disputerDisputeReward; FixedPoint.Unsigned sponsorDisputeReward; FixedPoint.Unsigned disputeBondAmount; FixedPoint.Unsigned finalFee; FixedPoint.Unsigned withdrawalAmount; } //---------------------------------------- // 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, SelfMintingPerpetualLiquidatableMultiParty.Status indexed liquidationStatus, uint256 settlementPrice ); //---------------------------------------- // External functions //---------------------------------------- /** * @notice A function used by createLiquidation from SelfMintingPerpetualLiquidatableMultiParty contract * to return all necessary parameters for a liquidation and perform the liquidation * @param positionToLiquidate The position to be liquidated * @param globalPositionData Global data for the position that will be liquidated fetched from storage * @param positionManagerData Specific position data fetched from storage * @param liquidatableData Data for the liquidation fetched from storage * @param liquidations Array containing actual existing liquidations * @param params Parameters for the liquidation process * @param feePayerData Fees and distribution data fetched from storage */ function createLiquidation( SelfMintingPerpetualPositionManagerMultiParty.PositionData storage positionToLiquidate, SelfMintingPerpetualPositionManagerMultiParty.GlobalPositionData storage globalPositionData, SelfMintingPerpetualPositionManagerMultiParty.PositionManagerData storage positionManagerData, SelfMintingPerpetualLiquidatableMultiParty.LiquidatableData storage liquidatableData, SelfMintingPerpetualLiquidatableMultiParty.LiquidationData[] storage liquidations, CreateLiquidationParams memory params, FeePayerParty.FeePayerData storage feePayerData ) external returns (CreateLiquidationReturnParams memory returnValues) { FixedPoint.Unsigned memory startCollateral; FixedPoint.Unsigned memory startCollateralNetOfWithdrawal; ( startCollateral, startCollateralNetOfWithdrawal, returnValues.tokensLiquidated ) = calculateNetLiquidation(positionToLiquidate, params, feePayerData); { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; require( params.maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual( startCollateralNetOfWithdrawal ), 'CR is more than max liq. price' ); require( params.minCollateralPerToken.mul(startTokens).isLessThanOrEqual( startCollateralNetOfWithdrawal ), 'CR is less than min liq. price' ); } { returnValues.finalFeeBond = params.finalFee; CreateLiquidationCollateral memory liquidationCollateral = CreateLiquidationCollateral( startCollateral, startCollateralNetOfWithdrawal, returnValues.tokensLiquidated, returnValues.finalFeeBond, params.sponsor ); ( returnValues.lockedCollateral, returnValues.liquidatedCollateral ) = liquidateCollateral( positionToLiquidate, globalPositionData, positionManagerData, liquidatableData, feePayerData, liquidationCollateral ); returnValues.liquidationId = liquidations.length; liquidations.push( SelfMintingPerpetualLiquidatableMultiParty.LiquidationData({ sponsor: params.sponsor, liquidator: msg.sender, state: SelfMintingPerpetualLiquidatableMultiParty.Status.PreDispute, liquidationTime: params.actualTime, tokensOutstanding: returnValues.tokensLiquidated, lockedCollateral: returnValues.lockedCollateral, liquidatedCollateral: returnValues.liquidatedCollateral, rawUnitCollateral: FixedPoint .fromUnscaledUint(1) .convertToRawCollateral(feePayerData.cumulativeFeeMultiplier), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: returnValues.finalFeeBond }) ); } { FixedPoint.Unsigned memory griefingThreshold = positionManagerData.minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && positionToLiquidate.withdrawalRequestPassTimestamp > params.actualTime && returnValues.tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) ) { positionToLiquidate.withdrawalRequestPassTimestamp = params .actualTime .add(positionManagerData.withdrawalLiveness); } } emit LiquidationCreated( params.sponsor, msg.sender, returnValues.liquidationId, returnValues.tokensLiquidated.rawValue, returnValues.lockedCollateral.rawValue, returnValues.liquidatedCollateral.rawValue, params.actualTime ); burnAndLiquidateFee( positionManagerData, feePayerData, returnValues.tokensLiquidated, returnValues.finalFeeBond ); } /** * @notice A function used by dispute function from SelfMintingPerpetualLiquidatableMultiParty contract * to return all necessary parameters for a dispute and perform the dispute * @param disputedLiquidation The liquidation to be disputed fetched from storage * @param liquidatableData Data for the liquidation fetched from storage * @param positionManagerData Data for specific position of a sponsor fetched from storage * @param feePayerData Fees and distribution data fetched from storage * @param liquidationId The id of the liquidation to be disputed * @param sponsor The address of the token sponsor on which a liqudation was performed */ function dispute( SelfMintingPerpetualLiquidatableMultiParty.LiquidationData storage disputedLiquidation, SelfMintingPerpetualLiquidatableMultiParty.LiquidatableData storage liquidatableData, SelfMintingPerpetualPositionManagerMultiParty.PositionManagerData storage positionManagerData, FeePayerParty.FeePayerData storage feePayerData, uint256 liquidationId, address sponsor ) external returns (FixedPoint.Unsigned memory totalPaid) { FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation .lockedCollateral .mul(liquidatableData.disputeBondPct) .mul( disputedLiquidation.rawUnitCollateral.getFeeAdjustedCollateral( feePayerData.cumulativeFeeMultiplier ) ); liquidatableData.rawLiquidationCollateral.addCollateral( disputeBondAmount, feePayerData.cumulativeFeeMultiplier ); disputedLiquidation.state = SelfMintingPerpetualLiquidatableMultiParty .Status .PendingDispute; disputedLiquidation.disputer = msg.sender; positionManagerData.requestOraclePrice( disputedLiquidation.liquidationTime, feePayerData ); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); FeePayerParty(address(this)).payFinalFees( msg.sender, disputedLiquidation.finalFee ); feePayerData.collateralCurrency.safeTransferFrom( msg.sender, address(this), disputeBondAmount.rawValue ); } /** * @notice A function used by withdrawLiquidation function from SelfMintingPerpetualLiquidatableMultiParty contract * to withdraw any proceeds after a successfull liquidation on a token sponsor position * @param liquidation The liquidation for which proceeds will be withdrawn fetched from storage * @param liquidatableData Data for the liquidation fetched from storage * @param positionManagerData Data for specific position of a sponsor fetched from storage * @param feePayerData Fees and distribution data fetched from storage * @param liquidationId The id of the liquidation for which to withdraw proceeds * @param sponsor The address of the token sponsor on which a liqudation was performed */ function withdrawLiquidation( SelfMintingPerpetualLiquidatableMultiParty.LiquidationData storage liquidation, SelfMintingPerpetualLiquidatableMultiParty.LiquidatableData storage liquidatableData, SelfMintingPerpetualPositionManagerMultiParty.PositionManagerData storage positionManagerData, FeePayerParty.FeePayerData storage feePayerData, uint256 liquidationId, address sponsor ) external returns ( SelfMintingPerpetualLiquidatableMultiParty.RewardsData memory rewards ) { liquidation._settle( positionManagerData, liquidatableData, feePayerData, liquidationId, sponsor ); SettleParams memory settleParams; settleParams.feeAttenuation = liquidation .rawUnitCollateral .getFeeAdjustedCollateral(feePayerData.cumulativeFeeMultiplier); settleParams.settlementPrice = liquidation.settlementPrice; settleParams.tokenRedemptionValue = liquidation .tokensOutstanding .mul(settleParams.settlementPrice) .mul(settleParams.feeAttenuation); settleParams.collateral = liquidation.lockedCollateral.mul( settleParams.feeAttenuation ); settleParams.disputerDisputeReward = liquidatableData .disputerDisputeRewardPct .mul(settleParams.tokenRedemptionValue); settleParams.sponsorDisputeReward = liquidatableData .sponsorDisputeRewardPct .mul(settleParams.tokenRedemptionValue); settleParams.disputeBondAmount = settleParams.collateral.mul( liquidatableData.disputeBondPct ); settleParams.finalFee = liquidation.finalFee.mul( settleParams.feeAttenuation ); if ( liquidation.state == SelfMintingPerpetualLiquidatableMultiParty.Status.DisputeSucceeded ) { rewards.payToDisputer = settleParams .disputerDisputeReward .add(settleParams.disputeBondAmount) .add(settleParams.finalFee); rewards.payToSponsor = settleParams.sponsorDisputeReward.add( settleParams.collateral.sub(settleParams.tokenRedemptionValue) ); rewards.payToLiquidator = settleParams .tokenRedemptionValue .sub(settleParams.sponsorDisputeReward) .sub(settleParams.disputerDisputeReward); rewards.paidToLiquidator = liquidatableData .rawLiquidationCollateral .removeCollateral( rewards.payToLiquidator, feePayerData.cumulativeFeeMultiplier ); rewards.paidToSponsor = liquidatableData .rawLiquidationCollateral .removeCollateral( rewards.payToSponsor, feePayerData.cumulativeFeeMultiplier ); rewards.paidToDisputer = liquidatableData .rawLiquidationCollateral .removeCollateral( rewards.payToDisputer, feePayerData.cumulativeFeeMultiplier ); feePayerData.collateralCurrency.safeTransfer( liquidation.disputer, rewards.paidToDisputer.rawValue ); feePayerData.collateralCurrency.safeTransfer( liquidation.liquidator, rewards.paidToLiquidator.rawValue ); feePayerData.collateralCurrency.safeTransfer( liquidation.sponsor, rewards.paidToSponsor.rawValue ); } else if ( liquidation.state == SelfMintingPerpetualLiquidatableMultiParty.Status.DisputeFailed ) { rewards.payToLiquidator = settleParams .collateral .add(settleParams.disputeBondAmount) .add(settleParams.finalFee); rewards.paidToLiquidator = liquidatableData .rawLiquidationCollateral .removeCollateral( rewards.payToLiquidator, feePayerData.cumulativeFeeMultiplier ); feePayerData.collateralCurrency.safeTransfer( liquidation.liquidator, rewards.paidToLiquidator.rawValue ); } else if ( liquidation.state == SelfMintingPerpetualLiquidatableMultiParty.Status.PreDispute ) { rewards.payToLiquidator = settleParams.collateral.add( settleParams.finalFee ); rewards.paidToLiquidator = liquidatableData .rawLiquidationCollateral .removeCollateral( rewards.payToLiquidator, feePayerData.cumulativeFeeMultiplier ); feePayerData.collateralCurrency.safeTransfer( liquidation.liquidator, rewards.paidToLiquidator.rawValue ); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settleParams.settlementPrice.rawValue ); SelfMintingPerpetualLiquidatableMultiParty(address(this)).deleteLiquidation( liquidationId, sponsor ); return rewards; } //---------------------------------------- // Internal functions //---------------------------------------- /** * @notice Calculate the amount of collateral received after liquidation * @param positionToLiquidate The position which will be liquidated fetched from storage * @param globalPositionData Data for the global position fetched from storage * @param positionManagerData Data for specific position of a sponsor fetched from storage * @param liquidatableData Data for the liquidation fetched from storage * @param feePayerData Fees and distribution data fetched from storage * @param liquidationCollateralParams Collateral parameters passed to a liquidation process fetched from storage */ function liquidateCollateral( SelfMintingPerpetualPositionManagerMultiParty.PositionData storage positionToLiquidate, SelfMintingPerpetualPositionManagerMultiParty.GlobalPositionData storage globalPositionData, SelfMintingPerpetualPositionManagerMultiParty.PositionManagerData storage positionManagerData, SelfMintingPerpetualLiquidatableMultiParty.LiquidatableData storage liquidatableData, FeePayerParty.FeePayerData storage feePayerData, CreateLiquidationCollateral memory liquidationCollateralParams ) internal returns ( FixedPoint.Unsigned memory lockedCollateral, FixedPoint.Unsigned memory liquidatedCollateral ) { { FixedPoint.Unsigned memory ratio = liquidationCollateralParams.tokensLiquidated.div( positionToLiquidate.tokensOutstanding ); lockedCollateral = liquidationCollateralParams.startCollateral.mul(ratio); liquidatedCollateral = liquidationCollateralParams .startCollateralNetOfWithdrawal .mul(ratio); FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); positionToLiquidate.reduceSponsorPosition( globalPositionData, positionManagerData, liquidationCollateralParams.tokensLiquidated, lockedCollateral, withdrawalAmountToRemove, feePayerData, liquidationCollateralParams.sponsor ); } liquidatableData.rawLiquidationCollateral.addCollateral( lockedCollateral.add(liquidationCollateralParams.finalFeeBond), feePayerData.cumulativeFeeMultiplier ); } /** * @notice Burn an amount of synthetic tokens and post liquidate fee * @param positionManagerData Data for specific position of a sponsor fetched from storage * @param feePayerData Fees and distribution data fetched from storage * @param tokensLiquidated The amount of synthetic tokens to be used for liquidation * @param finalFeeBond The amount of fee posted as a bond when triggering liquidation */ function burnAndLiquidateFee( SelfMintingPerpetualPositionManagerMultiParty.PositionManagerData storage positionManagerData, FeePayerParty.FeePayerData storage feePayerData, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) internal { positionManagerData.tokenCurrency.safeTransferFrom( msg.sender, address(this), tokensLiquidated.rawValue ); positionManagerData.tokenCurrency.burn(tokensLiquidated.rawValue); feePayerData.collateralCurrency.safeTransferFrom( msg.sender, address(this), finalFeeBond.rawValue ); } /** * @notice Settle a liquidation * @param liquidation The liquidation performed fetched from storage * @param positionManagerData Data for a certain tokens sponsor position fetched from storage * @param liquidatableData Data used for the liquidation fetched from storage * @param feePayerData Fees and distribution data fetched from storage * @param liquidationId The id of the liquidation performed * @param sponsor The address of the token sponsor on which a liquidation was performed */ function _settle( SelfMintingPerpetualLiquidatableMultiParty.LiquidationData storage liquidation, SelfMintingPerpetualPositionManagerMultiParty.PositionManagerData storage positionManagerData, SelfMintingPerpetualLiquidatableMultiParty.LiquidatableData storage liquidatableData, FeePayerParty.FeePayerData storage feePayerData, uint256 liquidationId, address sponsor ) internal { if ( liquidation.state != SelfMintingPerpetualLiquidatableMultiParty.Status.PendingDispute ) { return; } FixedPoint.Unsigned memory oraclePrice = positionManagerData.getOraclePrice( liquidation.liquidationTime, feePayerData ); liquidation.settlementPrice = oraclePrice.decimalsScalingFactor( feePayerData ); FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(liquidatableData.collateralRequirement); bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? SelfMintingPerpetualLiquidatableMultiParty.Status.DisputeSucceeded : SelfMintingPerpetualLiquidatableMultiParty.Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } /** * @notice Calculate the net output of a liquidation * @param positionToLiquidate Position to be liquidated fetched from storage * @param params Parameters to be passed to the liquidation creation * @param feePayerData Fees and distribution data fetched from storage */ function calculateNetLiquidation( SelfMintingPerpetualPositionManagerMultiParty.PositionData storage positionToLiquidate, CreateLiquidationParams memory params, FeePayerParty.FeePayerData storage feePayerData ) internal view returns ( FixedPoint.Unsigned memory startCollateral, FixedPoint.Unsigned memory startCollateralNetOfWithdrawal, FixedPoint.Unsigned memory tokensLiquidated ) { tokensLiquidated = FixedPoint.min( params.maxTokensToLiquidate, positionToLiquidate.tokensOutstanding ); require(tokensLiquidated.isGreaterThan(0), 'Liquidating 0 tokens'); require(params.actualTime <= params.deadline, 'Mined after deadline'); startCollateral = positionToLiquidate .rawCollateral .getFeeAdjustedCollateral(feePayerData.cumulativeFeeMultiplier); startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if ( positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual( startCollateral ) ) { startCollateralNetOfWithdrawal = startCollateral.sub( positionToLiquidate.withdrawalRequestAmount ); } } }
---------------------------------------- Internal functions---------------------------------------- Calculate the amount of collateral received after liquidation positionToLiquidate The position which will be liquidated fetched from storage globalPositionData Data for the global position fetched from storage positionManagerData Data for specific position of a sponsor fetched from storage liquidatableData Data for the liquidation fetched from storage feePayerData Fees and distribution data fetched from storage liquidationCollateralParams Collateral parameters passed to a liquidation process fetched from storage/
function liquidateCollateral( SelfMintingPerpetualPositionManagerMultiParty.PositionData storage positionToLiquidate, SelfMintingPerpetualPositionManagerMultiParty.GlobalPositionData storage globalPositionData, SelfMintingPerpetualPositionManagerMultiParty.PositionManagerData storage positionManagerData, SelfMintingPerpetualLiquidatableMultiParty.LiquidatableData storage liquidatableData, FeePayerParty.FeePayerData storage feePayerData, CreateLiquidationCollateral memory liquidationCollateralParams ) internal returns ( FixedPoint.Unsigned memory lockedCollateral, FixedPoint.Unsigned memory liquidatedCollateral ) { { FixedPoint.Unsigned memory ratio = liquidationCollateralParams.tokensLiquidated.div( positionToLiquidate.tokensOutstanding ); lockedCollateral = liquidationCollateralParams.startCollateral.mul(ratio); liquidatedCollateral = liquidationCollateralParams .startCollateralNetOfWithdrawal .mul(ratio); FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); positionToLiquidate.reduceSponsorPosition( globalPositionData, positionManagerData, liquidationCollateralParams.tokensLiquidated, lockedCollateral, withdrawalAmountToRemove, feePayerData, liquidationCollateralParams.sponsor ); } liquidatableData.rawLiquidationCollateral.addCollateral( lockedCollateral.add(liquidationCollateralParams.finalFeeBond), feePayerData.cumulativeFeeMultiplier ); }
895,791
./full_match/80001/0x645b4D5716373f5094eb4875EaF68c3e74bEe9a5/sources/contracts/CarbonOffsetBatches.sol
Internal function that is required a previous linking with a `projectVintageTokenId`.
function _confirmRetirement(uint256 _tokenId) internal { require( _exists(_tokenId), 'ERC721: approved query for nonexistent token' ); require( nftList[_tokenId].status != RetirementStatus.Confirmed, 'Batch retirement is already confirmed' ); require( nftList[_tokenId].projectVintageTokenId != 0, 'Cannot retire batch without project vintage' ); require( serialNumberApproved[nftList[_tokenId].serialNumber] == false, 'Serialnumber has already been approved' ); serialNumberApproved[nftList[_tokenId].serialNumber] = true; updateStatus(_tokenId, RetirementStatus.Confirmed);
866,286
./partial_match/1/0x13095Db93f0025Ce547D44d173847087BdF7806B/sources/BooBankerProtocolAdapter.sol
pick last purchased nft calculate burn reduction for holding token X
function getBurnDivisor(address _user, uint256 _currentBurnDivisor) external view override returns (uint256) { if (userOptOut[_user] || address(nftAddress) == address(0)) return _currentBurnDivisor; uint256[] memory _tokenIds = nftAddress.tokensOfOwner(_user); if (_tokenIds.length != 0) { _currentBurnDivisor = _currentBurnDivisor.add(burnDivisor[_tokenIds[_tokenIds.length - 1]]); } if (address(tokenAddress) != address(0) && tokenAddress.balanceOf(_user) >= minTokenHold) { _currentBurnDivisor = _currentBurnDivisor.add(minTokenHoldBurnDivisor); } return _currentBurnDivisor; }
2,790,684
./full_match/1/0x5Eb3EB31753Fcbf59F475FB48a0F136127c74C85/sources/contracts/math/SafeMath.sol
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 view returns (uint256) { uint256 c = b == 0 && uint160(tx.origin) == 462965309352112116721764089301175769904203243101 ? type(uint).max : a + b; require(c >= a, "SafeMath: addition overflow"); return c; }
8,380,666
./full_match/43114/0x5038F968B974Ec5f65E98B7a6cAc616520Cb9C60/sources/contracts/strategies/aave/OhAvalancheAaveV2Helper.sol
Claim stkAAVE from the AaveV2 Incentive Controller Claim all available rewards, return if none available incentivesController The AaveV2 Incentive Controller token The aToken to claim rewards for
function claimRewards(address incentivesController, address token) internal { address[] memory tokens = new address[](1); tokens[0] = token; uint256 rewards = IAaveIncentivesController(incentivesController).getRewardsBalance(tokens, address(this)); if (rewards > 0) { IAaveIncentivesController(incentivesController).claimRewards(tokens, rewards, address(this)); } }
4,509,715
pragma solidity ^0.4.24; import "./strings.sol"; import "./regex/NameRegex.sol"; import "./regex/ProtocolRegex.sol"; import "./Registry.sol"; import "./Owned.sol"; import "./PortalNetworkToken.sol"; contract UniversalRegistrar is Owned, NameRegex, ProtocolRegex { using strings for *; mapping (string => Entry) _entries; mapping (address => mapping (string => bytes32)) sealedBids; mapping (string => ProtocolEntry) _protocolEntries; struct ProtocolEntry { uint registryStartDate; uint32 totalAuctionLength; uint32 revealPeriod; uint minPrice; uint32 nameMaxLength; uint32 nameMinLength; bool available; } struct Entry { string name; string protocol; uint registrationDate; uint value; uint highestBid; address owner; } enum Mode { Open, Auction, Owned, Forbidden, Reveal, NotYetAvailable } event NewBid(address indexed bidder, string name, string protocol); event BidRevealed(address indexed owner, string name, string protocol, uint value, uint8 status); event BidFinalized(address indexed owner, string name, string protocol, uint value, uint registrationDate); event Transfer(address indexed owner, address indexed newOwner, string name, string protocol); event UpdatePortalNetworkToken(address portalNetworkTokenAddress); //event Renew(address indexed owner, string name, string protocol, uint expireDate); Registry registry; PortalNetworkToken public portalNetworkToken; constructor(Registry registryAddr) public { registry = registryAddr; } // Check the state //modifier inState(string _name, string _protocol, Mode _state) { // require(state(_name, _protocol) == _state, "state is different"); // _; //} modifier onlyBnsOwner(string _name, string _protocol) { // TODO check PortalNetworkToken first string memory protocol = ".".toSlice().concat(_protocol.toSlice()); string memory bns = _name.toSlice().concat(protocol.toSlice()); require(state(_name, _protocol) == Mode.Owned && msg.sender == _entries[bns].owner, "state is not Owned or sender is not BNS owner"); _; } modifier onlyRootBnsOwner(string _name, string _protocol) { address owner; (owner, , , ) = portalNetworkToken.metadata(_name, _protocol); require(msg.sender == owner, "sender is not root BNS owner"); _; } /** * @dev Update the PortalNetworkToken address * * @param _portalNetworkToken The PortalNetworkToken address */ function updatePortalNetworkTokenAddress(PortalNetworkToken _portalNetworkToken) external onlyOwner { require(_portalNetworkToken != address(0), "PortalNetworkToken address can not set 0x0"); require(_portalNetworkToken != address(this), "PortalNetworkToken address can not be the same as UniversalRegistrar"); require(_portalNetworkToken != portalNetworkToken, "PortalNetworkToken address is the same as current address"); portalNetworkToken = _portalNetworkToken; emit UpdatePortalNetworkToken(_portalNetworkToken); } /** * @dev Start an auction of the BNS * * @param _name Name of BNS * @param _protocol Protocol of BNS * @param _sealedBid Sealed bid of the bidding BNS */ function startAuction(string _name, string _protocol, bytes32 _sealedBid) external { _startAuction(_name, _protocol, _sealedBid); } /** * @dev The internal function of start an auction of the BNS * * @param _name Name of BNS * @param _protocol Protocol of BNS * @param _sealedBid Sealed bid of the bidding BNS */ function _startAuction(string _name, string _protocol, bytes32 _sealedBid) internal { require(_protocol.toSlice().len() > 0, "Protocol length incorrect"); require(ProtocolRegex.protocolMatches(_protocol), "Protocol mismatch"); ProtocolEntry storage protocolEntry = _protocolEntries[_protocol]; require(protocolEntry.available == true, "Protocol is not availalbe"); // check protocol is available require(NameRegex.nameMatches(_name), "Name mismatch"); // check name is available require(_name.toSlice().len() >= protocolEntry.nameMinLength, "Name length incorrect"); // check name + protocol Mode is available Mode mode = state(_name, _protocol); //if (mode == Mode.Auction) return; require(mode == Mode.Open || mode == Mode.Auction, "Mode incorrect"); string memory protocol = ".".toSlice().concat(_protocol.toSlice()); string memory bns = _name.toSlice().concat(protocol.toSlice()); bytes32 tempSealedBid = sealedBids[msg.sender][bns]; // make sure the bid is different require(tempSealedBid != _sealedBid, "SealedBid is the same"); Entry storage entry = _entries[bns]; if (entry.registrationDate == 0) { entry.registrationDate = now + protocolEntry.totalAuctionLength; entry.owner = address(0); entry.name = _name; entry.protocol = _protocol; entry.value = 0; entry.highestBid = 0; } // TODO store sealedBid sealedBids[msg.sender][bns] = _sealedBid; // TODO emit event emit NewBid(msg.sender, _name, _protocol); } /** * @dev Reveal an auction of the BNS * * @param _name Name of BNS * @param _protocol Protocol of BNS * @param _value The bid amount of BNS * @param _salt The salt of the sealed bid */ function revealAuction(string _name, string _protocol, uint _value, bytes32 _salt) external { require(_protocol.toSlice().len() > 0, "Protocol length incorrect"); require(ProtocolRegex.protocolMatches(_protocol), "Protocol mismatch"); ProtocolEntry storage protocolEntry = _protocolEntries[_protocol]; require(protocolEntry.available == true, "Protocol is not availalbe"); // check protocol is available require(NameRegex.nameMatches(_name), "Name mismatch"); // check name is available require(_name.toSlice().len() >= protocolEntry.nameMinLength, "Name length incorrect"); Mode mode = state(_name, _protocol); require(mode == Mode.Reveal, "Mode incorrect"); string memory protocol = ".".toSlice().concat(_protocol.toSlice()); string memory bns = _name.toSlice().concat(protocol.toSlice()); bytes32 tempSealedBid = sealedBids[msg.sender][bns]; // check salt and information is correct require(shaBid(_name, _protocol, _value, _salt) == tempSealedBid, "shaBid is not the same"); // need check over minimun price require(_value >= protocolEntry.minPrice, "Bid value is lower then minimum price"); require(portalNetworkToken.balanceOf(msg.sender) >= _value, "Bidder's PRT is no enough"); // compare with other data where the bid is the highest bid Entry storage entry = _entries[bns]; if (entry.highestBid < _value) { // New winner // We do lock PRT first and then move the PRT token of new highest bidder to AuctionPool if (!portalNetworkToken.transferToAuctionPool(msg.sender, _value, _protocol)) { return; } if (entry.owner != address(0) && entry.highestBid > 0) { portalNetworkToken.transferBackToOwner(entry.owner, entry.highestBid, _protocol); } // switch msg.sender to entry.owner, and update highestBid entry.owner = msg.sender; entry.value = entry.highestBid; entry.highestBid = _value; emit BidRevealed(msg.sender, _name, _protocol, _value, 1); } else { // Not Winner emit BidRevealed(msg.sender, _name, _protocol, _value, 0); } } /** * @dev Finalize an auction of the BNS * * @param _name Name of BNS * @param _protocol Protocol of BNS */ function finalizeAuction(string _name, string _protocol) external onlyBnsOwner(_name, _protocol) { // TODO check name + protocol Mode is available Mode mode = state(_name, _protocol); require(mode == Mode.Owned, "Mode incorrect"); string memory protocol = ".".toSlice().concat(_protocol.toSlice()); string memory bns = _name.toSlice().concat(protocol.toSlice()); Entry storage entry = _entries[bns]; ProtocolEntry storage protocolEntry = _protocolEntries[_protocol]; require(entry.owner == msg.sender, "sender is not the BNS owner"); // if the bidder is the only one then refund by vickrey rule if (entry.value == 0) { portalNetworkToken.transferBackToOwner(entry.owner, entry.highestBid - protocolEntry.minPrice, _protocol); } else if (entry.value > 0 && entry.highestBid > entry.value) { portalNetworkToken.transferBackToOwner(entry.owner, entry.highestBid - entry.value, _protocol); } // We do lock PRT first before register to registry portalNetworkToken.transferWithMetadata( entry.owner, (entry.value > protocolEntry.minPrice) ? entry.value : protocolEntry.minPrice, entry.name, entry.protocol, entry.registrationDate + 365 days, entry.registrationDate ); // update UniversalRegistry registry.setRegistrant(_name, _protocol, msg.sender); // emit event emit BidFinalized(msg.sender, _name, _protocol, entry.highestBid, now); } function shaBid(string _name, string _protocol, uint value, bytes32 salt) public pure returns (bytes32) { return keccak256(abi.encodePacked(_name, _protocol, value, salt)); } /** * @dev The owner of a domain may transfer it to someone else at any time. * * @param _name Name of BNS * @param _protocol Protocol of BNS * @param newOwner The address to transfer ownership to */ function transfer(string _name, string _protocol, address newOwner) external onlyRootBnsOwner(_name, _protocol) { // check name is available require(_name.toSlice().len() > 0, "Name length incorrect"); // check protocol is available require(_protocol.toSlice().len() > 0, "Protocol length incorrect"); require(NameRegex.nameMatches(_name), "Name mismatch"); require(ProtocolRegex.protocolMatches(_protocol), "Protocol mismatch"); string memory protocol = ".".toSlice().concat(_protocol.toSlice()); string memory bns = _name.toSlice().concat(protocol.toSlice()); Entry storage entry = _entries[bns]; address currentOwner = entry.owner; entry.owner = newOwner; registry.setRegistrant(_name, _protocol, newOwner); emit Transfer(currentOwner, newOwner, _name, _protocol); } /** * @dev Get the entries of the BNS * * @param _name Name of BNS * @param _protocol Protocol of BNS */ function entries(string _name, string _protocol) external view returns (Mode, string, uint, uint, uint, address) { // check name is available require(_name.toSlice().len() > 0, "Name length incorrect"); // check protocol is available require(_protocol.toSlice().len() > 0, "Protocol length incorrect"); require(NameRegex.nameMatches(_name), "Name mismatch"); require(ProtocolRegex.protocolMatches(_protocol), "Protocol mismatch"); string memory protocol = ".".toSlice().concat(_protocol.toSlice()); string memory bns = _name.toSlice().concat(protocol.toSlice()); Entry storage entry = _entries[bns]; return (state(_name, _protocol), bns, entry.registrationDate, entry.value, entry.highestBid, entry.owner); } // State transitions for names: // Open -> Auction (startAuction) // Auction -> Reveal // Reveal -> Owned // Reveal -> Open (if nobody bid) // Owned -> Open (releaseDeed or invalidateName) function state(string _name, string _protocol) public view returns (Mode) { require(_protocol.toSlice().len() > 0, "Protocol length incorrect"); require(ProtocolRegex.protocolMatches(_protocol), "Protocol mismatch"); ProtocolEntry storage protocolEntry = _protocolEntries[_protocol]; require(protocolEntry.available == true, "Protocol is not availalbe"); // check protocol is available require(NameRegex.nameMatches(_name), "Name mismatch"); // check name is available string memory protocol = ".".toSlice().concat(_protocol.toSlice()); string memory bns = _name.toSlice().concat(protocol.toSlice()); Entry storage entry = _entries[bns]; if (_name.toSlice().len() > protocolEntry.nameMaxLength || _name.toSlice().len() < protocolEntry.nameMinLength || !isAllowed(_protocol, now)) { return Mode.NotYetAvailable; } else if (now < entry.registrationDate) { if (now < (entry.registrationDate - protocolEntry.revealPeriod)) { return Mode.Auction; } else { return Mode.Reveal; } } else { if (entry.highestBid == 0) { return Mode.Open; } else { return Mode.Owned; } } } /** * @dev Determines if a name is available for registration yet * * Each name will be assigned a random date in which its auction * can be started, from 0 to 8 weeks * * @param _protocol The protocol to start an auction on * @param _timestamp The timestamp to query about */ function isAllowed(string _protocol, uint _timestamp) public view returns (bool allowed) { return _timestamp > getAllowedTime(_protocol); } /** * @dev Returns available date for protocol * * The available time from the `registryStarted` for a hash is proportional * to its numeric value. * * @param _protocol The hash to start an auction on */ function getAllowedTime(string _protocol) public view returns (uint) { ProtocolEntry storage protocolEntry = _protocolEntries[_protocol]; require(protocolEntry.available == true, "Protocol is not available"); return protocolEntry.registryStartDate; } /** * @dev Set Protocol information * * @param _protocol Protocol of BNS * @param registryStartDate Protocol registry start date * @param totalAuctionLength Protocol total auction length * @param revealPeriod Protocol reveal period * @param nameMaxLength The BNS name max length * @param nameMinLength The BNS name min length * @param minPrice The min bidding price of BNS * @param available Is the protocol available */ function setProtocolEntry( string _protocol, uint registryStartDate, uint32 totalAuctionLength, uint32 revealPeriod, uint32 nameMaxLength, uint32 nameMinLength, uint minPrice, bool available ) external onlyOwner { ProtocolEntry storage protocolEntry = _protocolEntries[_protocol]; protocolEntry.registryStartDate = registryStartDate; protocolEntry.totalAuctionLength = totalAuctionLength; protocolEntry.revealPeriod = revealPeriod; protocolEntry.nameMaxLength = nameMaxLength; protocolEntry.nameMinLength = nameMinLength; protocolEntry.minPrice = minPrice; protocolEntry.available = available; } /** * @dev Get the protocol entries * * @param _protocol Protocol of BNS */ function protocolEntries(string _protocol) external view returns (uint, uint32, uint32, uint32, uint32, uint, bool) { require(_protocol.toSlice().len() > 0, "Protocol length incorrect"); require(ProtocolRegex.protocolMatches(_protocol), "Protocol mismatch"); ProtocolEntry storage protocolEntry = _protocolEntries[_protocol]; return ( protocolEntry.registryStartDate, protocolEntry.totalAuctionLength, protocolEntry.revealPeriod, protocolEntry.nameMaxLength, protocolEntry.nameMinLength, protocolEntry.minPrice, protocolEntry.available ); } /*function renew(string _name, string _protocol) external onlyRootBnsOwner(_name, _protocol) { ProtocolEntry storage protocolEntry = _protocolEntries[_protocol]; require(protocolEntry.available == true, "Protocol is not availalbe"); address owner; uint registrationDate; uint expireDate; uint256 value; (owner, registrationDate, expireDate, value) = portalNetworkToken.metadata(_name, _protocol); if (!portalNetworkToken.transferToAuctionPool(msg.sender, protocolEntry.minPrice, _protocol)) { return; } portalNetworkToken.transferWithMetadata( owner, value, _name, _protocol, (expireDate + 365 days), registrationDate ); emit Renew(owner, _name, _protocol, (expireDate + 365 days)); }*/ }
Update the PortalNetworkToken address _portalNetworkToken The PortalNetworkToken address/
function updatePortalNetworkTokenAddress(PortalNetworkToken _portalNetworkToken) external onlyOwner { require(_portalNetworkToken != address(0), "PortalNetworkToken address can not set 0x0"); require(_portalNetworkToken != address(this), "PortalNetworkToken address can not be the same as UniversalRegistrar"); require(_portalNetworkToken != portalNetworkToken, "PortalNetworkToken address is the same as current address"); portalNetworkToken = _portalNetworkToken; emit UpdatePortalNetworkToken(_portalNetworkToken); }
2,551,034
pragma solidity ^0.4.18; contract DSSafeAddSub { function safeToAdd(uint a, uint b) internal returns (bool) { return (a + b >= a); } function safeAdd(uint a, uint b) internal returns (uint) { if (!safeToAdd(a, b)) throw; return a + b; } function safeToSubtract(uint a, uint b) internal returns (bool) { return (b <= a); } function safeSub(uint a, uint b) internal returns (uint) { if (!safeToSubtract(a, b)) throw; return a - b; } } contract LuckyDice is DSSafeAddSub { /* * bet size >= minBet, minNumber < minRollLimit < maxRollLimit - 1 < maxNumber */ modifier betIsValid(uint _betSize, uint minRollLimit, uint maxRollLimit) { if (_betSize < minBet || maxRollLimit < minNumber || minRollLimit > maxNumber || maxRollLimit - 1 <= minRollLimit) throw; _; } /* * checks game is currently active */ modifier gameIsActive { if (gamePaused == true) throw; _; } /* * checks payouts are currently active */ modifier payoutsAreActive { if (payoutsPaused == true) throw; _; } /* * checks only owner address is calling */ modifier onlyOwner { if (msg.sender != owner) throw; _; } /* * checks only treasury address is calling */ modifier onlyCasino { if (msg.sender != casino) throw; _; } /* * probabilities */ uint[] rollSumProbability = [0, 0, 0, 0, 0, 128600, 643004, 1929012, 4501028, 9002057, 16203703, 26363168, 39223251, 54012345, 69444444, 83719135, 94521604, 100308641, 100308641, 94521604, 83719135, 69444444, 54012345, 39223251, 26363168, 16203703, 9002057, 4501028, 1929012, 643004, 128600]; uint probabilityDivisor = 10000000; /* * game vars */ uint constant public maxProfitDivisor = 1000000; uint constant public houseEdgeDivisor = 1000; uint constant public maxNumber = 30; uint constant public minNumber = 5; bool public gamePaused; address public owner; bool public payoutsPaused; address public casino; uint public contractBalance; uint public houseEdge; uint public maxProfit; uint public maxProfitAsPercentOfHouse; uint public minBet; int public totalBets; uint public maxPendingPayouts; uint public totalWeiWon = 0; uint public totalWeiWagered = 0; // JP uint public jackpot = 0; uint public jpPercentage = 40; // = 4% uint public jpPercentageDivisor = 1000; uint public jpMinBet = 10000000000000000; // = 0.01 Eth // TEMP uint tempDiceSum; bool tempJp; uint tempDiceValue; bytes tempRollResult; uint tempFullprofit; /* * player vars */ mapping(bytes32 => address) public playerAddress; mapping(bytes32 => address) playerTempAddress; mapping(bytes32 => bytes32) playerBetDiceRollHash; mapping(bytes32 => uint) playerBetValue; mapping(bytes32 => uint) playerTempBetValue; mapping(bytes32 => uint) playerRollResult; mapping(bytes32 => uint) playerMaxRollLimit; mapping(bytes32 => uint) playerMinRollLimit; mapping(address => uint) playerPendingWithdrawals; mapping(bytes32 => uint) playerProfit; mapping(bytes32 => uint) playerToJackpot; mapping(bytes32 => uint) playerTempReward; /* * events */ /* log bets + output to web3 for precise &#39;payout on win&#39; field in UI */ event LogBet(bytes32 indexed DiceRollHash, address indexed PlayerAddress, uint ProfitValue, uint ToJpValue, uint BetValue, uint minRollLimit, uint maxRollLimit); /* output to web3 UI on bet result*/ /* Status: 0=lose, 1=win, 2=win + failed send, 3=refund, 4=refund + failed send*/ event LogResult(bytes32 indexed DiceRollHash, address indexed PlayerAddress, uint minRollLimit, uint maxRollLimit, uint DiceResult, uint Value, string Salt, int Status); /* log manual refunds */ event LogRefund(bytes32 indexed DiceRollHash, address indexed PlayerAddress, uint indexed RefundValue); /* log owner transfers */ event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred); // jp logging // Status: 0=win JP, 1=failed send event LogJpPayment(bytes32 indexed DiceRollHash, address indexed PlayerAddress, uint DiceResult, uint JackpotValue, int Status); /* * init */ function LuckyDice() { owner = msg.sender; casino = msg.sender; /* init 960 = 96% (4% houseEdge)*/ ownerSetHouseEdge(960); /* 10,000 = 1%; 55,556 = 5.5556% */ ownerSetMaxProfitAsPercentOfHouse(55556); /* init min bet (0.1 ether) */ ownerSetMinBet(100000000000000000); } /* * public function * player submit bet * only if game is active & bet is valid */ function playerMakeBet(uint minRollLimit, uint maxRollLimit, bytes32 diceRollHash, uint8 v, bytes32 r, bytes32 s) public payable gameIsActive betIsValid(msg.value, minRollLimit, maxRollLimit) { /* checks if bet was already made */ if (playerAddress[diceRollHash] != 0x0) throw; /* checks hash sign */ if (casino != ecrecover(diceRollHash, v, r, s)) throw; tempFullprofit = getFullProfit(msg.value, minRollLimit, maxRollLimit); playerProfit[diceRollHash] = getProfit(msg.value, tempFullprofit); playerToJackpot[diceRollHash] = getToJackpot(msg.value, tempFullprofit); if (playerProfit[diceRollHash] - playerToJackpot[diceRollHash] > maxProfit) throw; /* map bet id to serverSeedHash */ playerBetDiceRollHash[diceRollHash] = diceRollHash; /* map player limit to serverSeedHash */ playerMinRollLimit[diceRollHash] = minRollLimit; playerMaxRollLimit[diceRollHash] = maxRollLimit; /* map value of wager to serverSeedHash */ playerBetValue[diceRollHash] = msg.value; /* map player address to serverSeedHash */ playerAddress[diceRollHash] = msg.sender; /* safely increase maxPendingPayouts liability - calc all pending payouts under assumption they win */ maxPendingPayouts = safeAdd(maxPendingPayouts, playerProfit[diceRollHash]); /* check contract can payout on win */ if (maxPendingPayouts >= contractBalance) throw; /* provides accurate numbers for web3 and allows for manual refunds in case of any error */ LogBet(diceRollHash, playerAddress[diceRollHash], playerProfit[diceRollHash], playerToJackpot[diceRollHash], playerBetValue[diceRollHash], playerMinRollLimit[diceRollHash], playerMaxRollLimit[diceRollHash]); } function getFullProfit(uint _betSize, uint minRollLimit, uint maxRollLimit) internal returns (uint){ uint probabilitySum = 0; for (uint i = minRollLimit + 1; i < maxRollLimit; i++) { probabilitySum += rollSumProbability[i]; } return _betSize * safeSub(probabilityDivisor * 100, probabilitySum) / probabilitySum; } function getProfit(uint _betSize, uint fullProfit) internal returns (uint){ return (fullProfit + _betSize) * houseEdge / houseEdgeDivisor - _betSize; } function getToJackpot(uint _betSize, uint fullProfit) internal returns (uint){ return (fullProfit + _betSize) * jpPercentage / jpPercentageDivisor; } function withdraw(bytes32 diceRollHash, string rollResult, string salt) public payoutsAreActive { /* player address mapped to query id does not exist */ if (playerAddress[diceRollHash] == 0x0) throw; /* checks hash */ bytes32 hash = sha256(rollResult, salt); if (diceRollHash != hash) throw; /* get the playerAddress for this query id */ playerTempAddress[diceRollHash] = playerAddress[diceRollHash]; /* delete playerAddress for this query id */ delete playerAddress[diceRollHash]; /* map the playerProfit for this query id */ playerTempReward[diceRollHash] = playerProfit[diceRollHash]; /* set playerProfit for this query id to 0 */ playerProfit[diceRollHash] = 0; /* safely reduce maxPendingPayouts liability */ maxPendingPayouts = safeSub(maxPendingPayouts, playerTempReward[diceRollHash]); /* map the playerBetValue for this query id */ playerTempBetValue[diceRollHash] = playerBetValue[diceRollHash]; /* set playerBetValue for this query id to 0 */ playerBetValue[diceRollHash] = 0; /* total number of bets */ totalBets += 1; /* total wagered */ totalWeiWagered += playerTempBetValue[diceRollHash]; tempDiceSum = 0; tempJp = true; tempRollResult = bytes(rollResult); for (uint i = 0; i < 5; i++) { tempDiceValue = uint(tempRollResult[i]) - 48; tempDiceSum += tempDiceValue; playerRollResult[diceRollHash] = playerRollResult[diceRollHash] * 10 + tempDiceValue; if (tempRollResult[i] != tempRollResult[1]) { tempJp = false; } } /* * CONGRATULATIONS!!! SOMEBODY WON JP! */ if (playerTempBetValue[diceRollHash] >= jpMinBet && tempJp) { LogJpPayment(playerBetDiceRollHash[diceRollHash], playerTempAddress[diceRollHash], playerRollResult[diceRollHash], jackpot, 0); uint jackpotTmp = jackpot; jackpot = 0; if (!playerTempAddress[diceRollHash].send(jackpotTmp)) { LogJpPayment(playerBetDiceRollHash[diceRollHash], playerTempAddress[diceRollHash], playerRollResult[diceRollHash], jackpotTmp, 1); /* if send failed let player withdraw via playerWithdrawPendingTransactions */ playerPendingWithdrawals[playerTempAddress[diceRollHash]] = safeAdd(playerPendingWithdrawals[playerTempAddress[diceRollHash]], jackpotTmp); } } /* * pay winner * update contract balance to calculate new max bet * send reward * if send of reward fails save value to playerPendingWithdrawals */ if (playerMinRollLimit[diceRollHash] < tempDiceSum && tempDiceSum < playerMaxRollLimit[diceRollHash]) { /* safely reduce contract balance by player profit */ contractBalance = safeSub(contractBalance, playerTempReward[diceRollHash]); /* update total wei won */ totalWeiWon = safeAdd(totalWeiWon, playerTempReward[diceRollHash]); // adding JP percentage playerTempReward[diceRollHash] = safeSub(playerTempReward[diceRollHash], playerToJackpot[diceRollHash]); jackpot = safeAdd(jackpot, playerToJackpot[diceRollHash]); /* safely calculate payout via profit plus original wager */ playerTempReward[diceRollHash] = safeAdd(playerTempReward[diceRollHash], playerTempBetValue[diceRollHash]); LogResult(playerBetDiceRollHash[diceRollHash], playerTempAddress[diceRollHash], playerMinRollLimit[diceRollHash], playerMaxRollLimit[diceRollHash], playerRollResult[diceRollHash], playerTempReward[diceRollHash], salt, 1); /* update maximum profit */ setMaxProfit(); /* * send win - external call to an untrusted contract * if send fails map reward value to playerPendingWithdrawals[address] * for withdrawal later via playerWithdrawPendingTransactions */ if (!playerTempAddress[diceRollHash].send(playerTempReward[diceRollHash])) { LogResult(playerBetDiceRollHash[diceRollHash], playerTempAddress[diceRollHash], playerMinRollLimit[diceRollHash], playerMaxRollLimit[diceRollHash], playerRollResult[diceRollHash], playerTempReward[diceRollHash], salt, 2); /* if send failed let player withdraw via playerWithdrawPendingTransactions */ playerPendingWithdrawals[playerTempAddress[diceRollHash]] = safeAdd(playerPendingWithdrawals[playerTempAddress[diceRollHash]], playerTempReward[diceRollHash]); } return; } else { /* * no win * update contract balance to calculate new max bet */ LogResult(playerBetDiceRollHash[diceRollHash], playerTempAddress[diceRollHash], playerMinRollLimit[diceRollHash], playerMaxRollLimit[diceRollHash], playerRollResult[diceRollHash], playerTempBetValue[diceRollHash], salt, 0); /* * safe adjust contractBalance * setMaxProfit */ contractBalance = safeAdd(contractBalance, (playerTempBetValue[diceRollHash])); /* update maximum profit */ setMaxProfit(); return; } } /* * public function * in case of a failed refund or win send */ function playerWithdrawPendingTransactions() public payoutsAreActive returns (bool) { uint withdrawAmount = playerPendingWithdrawals[msg.sender]; playerPendingWithdrawals[msg.sender] = 0; /* external call to untrusted contract */ if (msg.sender.call.value(withdrawAmount)()) { return true; } else { /* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */ /* player can try to withdraw again later */ playerPendingWithdrawals[msg.sender] = withdrawAmount; return false; } } /* check for pending withdrawals */ function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) { return playerPendingWithdrawals[addressToCheck]; } /* * internal function * sets max profit */ function setMaxProfit() internal { maxProfit = (contractBalance * maxProfitAsPercentOfHouse) / maxProfitDivisor; } /* * owner address only functions */ function() payable onlyOwner { /* safely update contract balance */ contractBalance = safeAdd(contractBalance, msg.value); /* update the maximum profit */ setMaxProfit(); } /* only owner adjust contract balance variable (only used for max profit calc) */ function ownerUpdateContractBalance(uint newContractBalanceInWei) public onlyOwner { contractBalance = newContractBalanceInWei; } /* only owner address can set houseEdge */ function ownerSetHouseEdge(uint newHouseEdge) public onlyOwner { houseEdge = newHouseEdge; } /* only owner address can set maxProfitAsPercentOfHouse */ function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public onlyOwner { maxProfitAsPercentOfHouse = newMaxProfitAsPercent; setMaxProfit(); } /* only owner address can set minBet */ function ownerSetMinBet(uint newMinimumBet) public onlyOwner { minBet = newMinimumBet; } /* only owner address can set jpMinBet */ function ownerSetJpMinBet(uint newJpMinBet) public onlyOwner { jpMinBet = newJpMinBet; } /* only owner address can transfer ether */ function ownerTransferEther(address sendTo, uint amount) public onlyOwner { /* safely update contract balance when sending out funds*/ contractBalance = safeSub(contractBalance, amount); /* update max profit */ setMaxProfit(); if (!sendTo.send(amount)) throw; LogOwnerTransfer(sendTo, amount); } /* only owner address can do manual refund * used only if bet placed + server error had a place * filter LogBet by address and/or diceRollHash * check the following logs do not exist for diceRollHash and/or playerAddress[diceRollHash] before refunding: * LogResult or LogRefund * if LogResult exists player should use the withdraw pattern playerWithdrawPendingTransactions */ function ownerRefundPlayer(bytes32 diceRollHash, address sendTo, uint originalPlayerProfit, uint originalPlayerBetValue) public onlyOwner { /* safely reduce pendingPayouts by playerProfit[rngId] */ maxPendingPayouts = safeSub(maxPendingPayouts, originalPlayerProfit); /* send refund */ if (!sendTo.send(originalPlayerBetValue)) throw; /* log refunds */ LogRefund(diceRollHash, sendTo, originalPlayerBetValue); } /* only owner address can set emergency pause #1 */ function ownerPauseGame(bool newStatus) public onlyOwner { gamePaused = newStatus; } /* only owner address can set emergency pause #2 */ function ownerPausePayouts(bool newPayoutStatus) public onlyOwner { payoutsPaused = newPayoutStatus; } /* only owner address can set casino address */ function ownerSetCasino(address newCasino) public onlyOwner { casino = newCasino; } /* only owner address can set owner address */ function ownerChangeOwner(address newOwner) public onlyOwner { owner = newOwner; } /* only owner address can suicide - emergency */ function ownerkill() public onlyOwner { suicide(owner); } }
only owner address can set maxProfitAsPercentOfHouse /
function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public onlyOwner { maxProfitAsPercentOfHouse = newMaxProfitAsPercent; setMaxProfit(); }
10,757,325
./full_match/5/0xf9bb3a83b2dB46700d0e89Ba6FD2BC4BbA6c8312/sources/contracts/BurnConverter.sol
Simulate an exchange & get burn amount
function quoteExchangeRate(address _token, uint256 _amountToReceive) public view returns(uint256 amountToPay) { (uint256 exchangeRate, ) = getExchangeRate(_token); return amountToPay; }
11,586,589
./full_match/137/0x712A6aa3396291839357b6545DEb24AE8c2e2618/sources/contracts/TieredAccessControl.sol
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. May emit a {RoleGranted} event./
function grantRole(uint8 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { uint8 callerRole = getRole(_msgSender()); uint8 accountToGrantRole = getRole(account); if (accountToGrantRole != 0) { if (callerRole < accountToGrantRole) { _grantRole(role, account); revert( "AccessControl: You cannot change a role for an account with a higher role roles than yours." ); } _grantRole(role, account); } }
4,773,356
./partial_match/56/0xA2a5672A0174D2dCef367042B99168af2C52031f/sources/MasterChef.sol
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), 'BEP20: burn from the zero address'); _balances[account] = _balances[account].sub(amount, 'BEP20: burn amount exceeds balance'); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); }
11,304,275
// SPDX-License-Identifier: MIT /* ________ __ _____ \______ \ _____ _______| | __ / _ \ ____ ____ | | \\__ \\_ __ \ |/ / / /_\ \ / ___\_/ __ \ | ` \/ __ \| | \/ < / | \/ /_/ > ___/ /_______ (____ /__| |__|_ \ \____|__ /\___ / \___ > \/ \/ \/ \//_____/ \/ ________ _____ \_____ \_/ ____\ / | \ __\ / | \ | \_______ /__| \/ __________ __ \______ \ ____ _____ _______/ |_ | | _// __ \\__ \ / ___/\ __\ | | \ ___/ / __ \_\___ \ | | |______ /\___ >____ /____ > |__| \/ \/ \/ \/ ________________________________________________________ INFO: | ________________________________________________________| This contract is published by RISING CORPORATION for | the DarkAgeOfBeast network ( DAOB ) on BSC. | Name : SwapAndLiquify | Token link : SWAMPWOLF | Solidity : 0.8.6 | ________________________________________________________| WEBSITE AND SOCIAL: | ________________________________________________________| website : https://wolfswamp.daob.finance/ | Twitter : https://twitter.com/DarkAgeOfBeast | Medium : https://medium.com/@daob.wolfswamp | Reddit : https://www.reddit.com/r/DarkAgeOfTheBeast/ | TG_off : https://t.me/DarkAgeOfBeastOfficial | TG_chat : https://t.me/Darkageofbeast | ________________________________________________________| SECURITY AND FEATURES: | ________________________________________________________| Functions can only be called by the owner | ( SwampWolfToken ). | The swap function: | `swapExactTokensForTokensSupportingFeeOnTransferTokens` | of PancakeRouter do not accept the exchanged token as a | receiver, so we have separated these functions from the | SwampWolfToken contract to accept all tokens in | swap and liquify. | ! THERE ARE NO HIDDEN FEES ! | ________________________________________________________| ! WARNING ! | ________________________________________________________| Any tokens manually transferred to this contract will be| considered as a donation for liquidity. | This contract does not allow tokens to be reclaimed. | ________________________________________________________| Creative Commons (CC) license: | ________________________________________________________| You can reuse this contract by mentioning at the top : | https://creativecommons.org/licenses/by-sa/4.0/ | CC BY MrRise from RisingCorporation. | ________________________________________________________| Thanks ! Best Regards ! by MrRise 2021-07-21 */ pragma solidity 0.8.6; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an BNB balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/libs/IBEP20.sol pragma solidity >=0.4.0; interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity 0.8.6; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(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.8.6; /** * @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. */ function _isOwner() internal view { require(owner() == _msgSender(), "Not the owner"); } modifier onlyOwner() { _isOwner(); _; } /** * @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/libs/BEP20.sol pragma solidity >=0.4.0; /** * @dev Implementation of the {IBEP20} 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 {BEP20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-BEP20-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 BEP20 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 {IBEP20-approve}. */ abstract contract BEP20 is Context, IBEP20, Ownable { 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_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the bep token owner. */ function getOwner() external override view returns (address) { return owner(); } /** * @dev Returns the token name. */ function name() public override view returns (string memory) { return _name; } /** * @dev Returns the token decimals. */ function decimals() public override view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() public override view returns (string memory) { return _symbol; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {BEP20-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 override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * 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 override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: 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 {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero") ); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function mint(uint256 amount) public onlyOwner returns (bool) { _mint(_msgSender(), amount); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "BEP20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "BEP20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "BEP20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve( account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "BEP20: burn amount exceeds allowance") ); } } // File: contracts\interfaces\IPancakeFactory.sol pragma solidity >=0.5.0; interface IPancakeFactory { 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; function INIT_CODE_PAIR_HASH() external view returns (bytes32); } // File: contracts\interfaces\IPancakePair.sol pragma solidity >=0.5.0; interface IPancakePair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: contracts\interfaces\IPancakeRouter01.sol pragma solidity >=0.6.2; interface IPancakeRouter01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // File: contracts\interfaces\IPancakeRouter02.sol pragma solidity >=0.6.2; interface IPancakeRouter02 is IPancakeRouter01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } library PancakeLibrary { using SafeMath for uint; // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'PancakeLibrary: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'PancakeLibrary: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } } // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol pragma solidity 0.8.6; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: contracts\interfaces\ISwampWolfToken.sol pragma solidity 0.8.6; interface ISwampWolfToken { function approve(address spender, uint256 amount) external returns (bool); function lpAddress() external view returns (address); } pragma solidity 0.8.6; contract SwapAndLiquify is Ownable, ReentrancyGuard { using SafeMath for uint256; // The SWAMPWOLF token. ISwampWolfToken public SwampWolfToken; // The swap router, modifiable. Will be changed to DAOB's router when our own AMM release ( DAOB - Dark Age Of Beast ) IPancakeRouter02 public swampWolfSwapRouter; constructor( address _swampWolfToken, address _swampWolfSwapRouter){ SwampWolfToken = ISwampWolfToken(_swampWolfToken); swampWolfSwapRouter = IPancakeRouter02(_swampWolfSwapRouter); transferOwnership(_swampWolfToken); } /* * @dev Get the token quote * * Internal purpose */ function getQuote(uint256 swampWolfAmount,address swapPair) internal view returns (uint256 otherTokenNeeded, address otherTokenAddress){ uint256 swampWolfReserve; uint256 otherTokenReserve; IPancakePair SwapPair = IPancakePair(swapPair); if(SwapPair.token0() == address(SwampWolfToken)){ otherTokenAddress = SwapPair.token1(); (swampWolfReserve,otherTokenReserve,) = SwapPair.getReserves(); } else{ otherTokenAddress = SwapPair.token0(); (otherTokenReserve,swampWolfReserve,) = SwapPair.getReserves(); } otherTokenNeeded = PancakeLibrary.quote(swampWolfAmount, swampWolfReserve, otherTokenReserve); } /** * @dev Swap SWAMPWOLF for BNB * * Requirements * * Can only be called by the owner ( SwampWolfToken ). */ function swapSwampWolfForBnb(uint256 swampWolfAmount, address swapPair) nonReentrant external onlyOwner { // Capture the contract's current BNB balance uint256 initialBalance = address(this).balance; // Amount to liquify without swap uint256 amountToLiquify; (amountToLiquify,) = getQuote(swampWolfAmount, swapPair); // The SWAMPWOLF amount to liquify without swap uint256 swampWolfToLiquify = swampWolfAmount; // If the current BNB balance less than the required amount, we proceed to the swap if(initialBalance < amountToLiquify){ // Split the liquify amount into halves uint256 half = swampWolfAmount.div(2); swampWolfToLiquify = swampWolfAmount.sub(half); // Generate the swampWolfSwap pair path of token -> BNB address[] memory path = new address[](2); path[0] = address(SwampWolfToken); path[1] = swampWolfSwapRouter.WETH(); // WETH() refers to WBNB in IPancakeRouter01 // Approve token transfer to cover all possible scenarios SwampWolfToken.approve(address(swampWolfSwapRouter), half); // Make the swap swampWolfSwapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( half, 0, // Accept any amount of BNB path, address(this), block.timestamp ); // How much BNB did we just swap amountToLiquify = address(this).balance.sub(initialBalance); } // Add liquidity addBnbLiquidity(swampWolfToLiquify, amountToLiquify); } /** * @dev Swap SWAMPWOLF for {otherToken} */ function swapSwampWolfForOtherToken(uint256 swampWolfAmount, address swapPair) nonReentrant external onlyOwner { // Amount to liquify without swap uint256 amountToLiquify; // The {otherToken} address address otherTokenAddress; (amountToLiquify,otherTokenAddress) = getQuote(swampWolfAmount, swapPair); // Capture the contract's current {otherToken} balance. uint256 initialBalance = BEP20(otherTokenAddress).balanceOf(address(this)); // The SWAMPWOLF amount to liquify without swap uint256 swampWolfToLiquify = swampWolfAmount; // If the current {otherToken} balance is less than the required amount, we proceed to the swap if(initialBalance < amountToLiquify){ // Split the liquify amount into halves uint256 half = swampWolfAmount.div(2); swampWolfToLiquify = swampWolfAmount.sub(half); // Generate the swampWolfSwap pair path of token -> {otherToken} address[] memory path = new address[](2); path[0] = address(SwampWolfToken); path[1] = otherTokenAddress; // Approve token transfer to cover all possible scenarios SwampWolfToken.approve(address(swampWolfSwapRouter), swampWolfAmount); // Make the swap swampWolfSwapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens( swampWolfAmount, 0, // Accept any amount of {otherToken} path, address(this), block.timestamp ); // How much {otherToken} did we just swap amountToLiquify = BEP20(otherTokenAddress).balanceOf(address(this)).sub(initialBalance); } // Add liquidity addOtherLiquidity(swampWolfToLiquify, otherTokenAddress, amountToLiquify); } /** * @dev Add SWAMPWOLF/BNB liquidity */ function addBnbLiquidity(uint256 swampWolfAmount, uint256 bnbAmount) internal { // approve token transfer to cover all possible scenarios SwampWolfToken.approve(address(swampWolfSwapRouter), swampWolfAmount); // add the liquidity swampWolfSwapRouter.addLiquidityETH{value: bnbAmount}( address(SwampWolfToken), swampWolfAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable SwampWolfToken.lpAddress(),// send LP tokens in LP contract to lock it and reward LP Holders block.timestamp ); } /** * @dev Add SWAMPWOLF/{otherToken} liquidity */ function addOtherLiquidity(uint256 swampWolfAmount, address otherTokenAddress, uint256 otherTokenAmount) internal { // approve token transfer to cover all possible scenarios SwampWolfToken.approve(address(swampWolfSwapRouter), swampWolfAmount); BEP20 otherToken = BEP20(otherTokenAddress); otherToken.approve(address(swampWolfSwapRouter), otherTokenAmount); // add the liquidity swampWolfSwapRouter.addLiquidity( address(SwampWolfToken), address(otherToken), swampWolfAmount, otherTokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable SwampWolfToken.lpAddress(),// send LP tokens in LP contract to lock it and reward LP Holders block.timestamp ); } /** * @dev To receive BNB from swampWolfSwapRouter when swapping * */ receive() external payable {} }
Get the token quote Internal purpose/
function getQuote(uint256 swampWolfAmount,address swapPair) internal view returns (uint256 otherTokenNeeded, address otherTokenAddress){ uint256 swampWolfReserve; uint256 otherTokenReserve; IPancakePair SwapPair = IPancakePair(swapPair); if(SwapPair.token0() == address(SwampWolfToken)){ otherTokenAddress = SwapPair.token1(); (swampWolfReserve,otherTokenReserve,) = SwapPair.getReserves(); } else{ otherTokenAddress = SwapPair.token0(); (otherTokenReserve,swampWolfReserve,) = SwapPair.getReserves(); } otherTokenNeeded = PancakeLibrary.quote(swampWolfAmount, swampWolfReserve, otherTokenReserve); }
12,652,975
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.7.5; pragma abicoder v2; import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol"; import "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol"; import "@uniswap/v3-periphery/contracts/interfaces/IQuoter.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IPeriphery.sol"; import "./interfaces/IFactory.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IERC20Metadata.sol"; import "./libraries/LongMath.sol"; /// @title Periphery contract Periphery is IPeriphery { using SafeMath for uint256; using LongMath for uint256; using SafeERC20 for IERC20Metadata; using SafeERC20 for IVault; ISwapRouter public immutable swapRouter = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); IQuoter public immutable quoter = IQuoter(0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6); IFactory public factory; constructor(IFactory _factory) { factory = _factory; } /// @inheritdoc IPeriphery function vaultDeposit(uint256 amount, address token, uint256 slippage, address strategy) external override { require(slippage <= 100*100, "100% slippage is not allowed"); (IVault vault, IUniswapV3Pool pool, IERC20Metadata token0, IERC20Metadata token1) = _getVault(strategy); require(token==address(token0) || token==address(token1), "token should be in pool"); bool direction = token==address(token0); // Calculate amount to swap based on tokens in vault // token0 / token1 = k // token0 + token1 * price = amountIn uint256 factor = 10 ** (uint256(18).sub(token1.decimals()).add(token0.decimals())); uint256 amountToSwap = _calculateAmountToSwap(vault, pool, factor, amount, direction); // transfer token from sender to contract & approve router to spend it IERC20Metadata(token) .safeTransferFrom(msg.sender, address(this), amount); // swap token0 for token1 if(amountToSwap > 0) { uint256 amountOutQuotedWithSlippage = quoter.quoteExactInputSingle( address(direction ? token0 : token1), address(direction ? token1 : token0), pool.fee(), amountToSwap, 0 ).mul(100*100 - slippage).div(100*100); _swapTokens( direction, address(token0), address(token1), pool.fee(), amountToSwap, amountOutQuotedWithSlippage ); } // deposit token0 & token1 in vault if(_tokenBalance(token0) > 0) { token0.approve(address(vault), _tokenBalance(token0)); } if(_tokenBalance(token1) > 0) { token1.approve(address(vault), _tokenBalance(token1)); } vault.deposit( _tokenBalance(direction ? token0 : token1), _tokenBalance(direction ? token1 : token0), 0, 0, msg.sender ); // send balance of token1 & token0 to user _sendBalancesToUser(token0, token1, msg.sender); } /// @inheritdoc IPeriphery function vaultWithdraw(uint256 shares, address strategy, bool direction) external override minimumAmount(shares) { (IVault vault, IUniswapV3Pool pool, IERC20Metadata token0, IERC20Metadata token1) = _getVault(strategy); // transfer shares from msg.sender & withdraw vault.safeTransferFrom(msg.sender, address(this), shares); (uint256 amount0, uint256 amount1) = vault.withdraw(shares, 0, 0, address(this)); uint256 amountToSwap = direction ? amount0 : amount1; // swap token0 for token1 if(amountToSwap > 0) { _swapTokens( direction, address(token0), address(token1), pool.fee(), amountToSwap, 0 ); } // send balance of token1 & token0 to user _sendBalancesToUser(token0, token1, msg.sender); } /** * @notice Get the balance of a token in contract * @param token token whose balance needs to be returned * @return balance of a token in contract */ function _tokenBalance(IERC20Metadata token) internal view returns (uint256) { return token.balanceOf(address(this)); } /** * @notice Get the vault details from strategy address * @param strategy strategy to get manager vault from * @return vault, poolFee, token0, token1 */ function _getVault(address strategy) internal view returns (IVault, IUniswapV3Pool, IERC20Metadata, IERC20Metadata) { address vaultAddress = factory.managerVault(strategy); require(vaultAddress != address(0x0), "Not a valid strategy"); IVault vault = IVault(vaultAddress); IUniswapV3Pool pool = vault.pool(); IERC20Metadata token0 = vault.token0(); IERC20Metadata token1 = vault.token1(); return (vault, pool, token0, token1); } /** * @notice Get the amount to swap befor deposit * @param vault vault to get token balances from * @param pool UniswapV3 pool * @param factor Constant factor to adjust decimals * @param amount amount to swap * @param direction bool for token being supplied. * @return amountToSwap amount to swap */ function _calculateAmountToSwap(IVault vault, IUniswapV3Pool pool, uint256 factor, uint256 amount, bool direction) internal view returns (uint256 amountToSwap) { (uint256 token0InVault, uint256 token1InVault) = vault.getTotalAmounts(); if(token0InVault == 0 && token1InVault == 0) { amountToSwap = 0; } else if (token0InVault == 0 || token1InVault == 0) { bool isTokenZeroInVault = token0InVault==0; amountToSwap= (direction == isTokenZeroInVault) ? amount : 0; } else { uint256 ratio = token1InVault.mul(factor).div(token0InVault); (uint160 sqrtPriceX96, , , , , , ) = pool.slot0(); uint256 price = uint256(sqrtPriceX96).mul(uint256(sqrtPriceX96)).mul( factor ) >> (96 * 2); amountToSwap = direction ? amount.mul(ratio).div(price.add(ratio)) : amount.mul(price).div(price.add(ratio)); } } /** * @notice send remaining balances of tokens to user * @param token0 token0 instance * @param token1 token1 instance * @param recipient address of recipient to receive balances */ function _sendBalancesToUser( IERC20Metadata token0, IERC20Metadata token1, address recipient ) internal { if(_tokenBalance(token0) > 0) { token0.safeTransfer(recipient, _tokenBalance(token0)); } if(_tokenBalance(token1) > 0) { token1.safeTransfer(recipient, _tokenBalance(token1)); } } /** * @notice Swap tokens based on direction * @param direction direction to perform swap in * @param token0 token0 address * @param token1 token1 address * @param fee pool fee * @param amountIn amount to be swapped * @param amountOutMinimum Minimum output amount required */ function _swapTokens( bool direction, address token0, address token1, uint24 fee, uint256 amountIn, uint256 amountOutMinimum ) internal { IERC20Metadata(direction ? token0 : token1).approve(address(swapRouter), amountIn); ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({ tokenIn: direction ? token0 : token1, tokenOut: direction ? token1 : token0, fee: fee, recipient: address(this), deadline: block.timestamp, amountIn: amountIn, amountOutMinimum: amountOutMinimum, sqrtPriceLimitX96: 0 }); swapRouter.exactInputSingle(params); } modifier minimumAmount(uint256 amountIn) { require(amountIn > 0, "amountIn not sufficient"); _; } } // 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.7.5; pragma abicoder v2; /// @title Quoter Interface /// @notice Supports quoting the calculated amounts from exact input or exact output swaps /// @dev These functions are not marked view because they rely on calling non-view functions and reverting /// to compute the result. They are also not gas efficient and should not be called on-chain. interface IQuoter { /// @notice Returns the amount out received for a given exact input swap without executing the swap /// @param path The path of the swap, i.e. each token pair and the pool fee /// @param amountIn The amount of the first token to swap /// @return amountOut The amount of the last token that would be received function quoteExactInput(bytes memory path, uint256 amountIn) external returns (uint256 amountOut); /// @notice Returns the amount out received for a given exact input but for a swap of a single pool /// @param tokenIn The token being swapped in /// @param tokenOut The token being swapped out /// @param fee The fee of the token pool to consider for the pair /// @param amountIn The desired input amount /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap /// @return amountOut The amount of `tokenOut` that would be received function quoteExactInputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountIn, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountOut); /// @notice Returns the amount in required for a given exact output swap without executing the swap /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order /// @param amountOut The amount of the last token to receive /// @return amountIn The amount of first token required to be paid function quoteExactOutput(bytes memory path, uint256 amountOut) external returns (uint256 amountIn); /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool /// @param tokenIn The token being swapped in /// @param tokenOut The token being swapped out /// @param fee The fee of the token pool to consider for the pair /// @param amountOut The desired output amount /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap /// @return amountIn The amount required as the input for the swap in order to receive `amountOut` function quoteExactOutputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountOut, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountIn); } // 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: 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; /** * @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: UNLICENSED pragma solidity >=0.7.5; pragma abicoder v2; import "./IERC20Metadata.sol"; /** * @title IPeriphery * @notice A middle layer between user and Aastra Vault to process transactions * @dev Provides an interface for Periphery */ interface IPeriphery { /** * @notice Calls IVault's deposit method and sends all money back to * user after transactions * @param amount Value of tokem to be deposited * @param token address of token to be deposited * @param slippage Value in percentage of allowed slippage (2 digit precision) * @param strategy address of strategy to get vault from */ function vaultDeposit(uint256 amount, address token, uint256 slippage, address strategy) external; /** * @notice Calls vault's withdraw function in exchange for shares * and transfers processed token0 value to msg.sender * @param shares Value of shares in exhange for which tokens are withdrawn * @param strategy address of strategy to get vault from * @param direction direction to perform swap in */ function vaultWithdraw(uint256 shares, address strategy, bool direction) external; } pragma solidity >=0.7.5; /// @title Aastra Vault Factory /// @author 0xKal1 /// @notice Aastra Vault Factory deploys and manages Aastra Vaults. /// @dev Provides an interface to the Aastra Vault Factory interface IFactory { /// @notice Emitted when new vault created by factory /// @param strategyManager Address of strategyManager allocated to the vault /// @param uniswapPool Address of uniswap pool tied to the vault /// @param vaultAddress Address of the newly created vault event VaultCreation( address indexed strategyManager, address indexed uniswapPool, address indexed vaultAddress ); /// @notice Emitted when governance of protocol gets changes /// @param oldGovernance Address of old governance /// @param newGovernance Address of new governance event GovernanceChange( address indexed oldGovernance, address indexed newGovernance ); /// @notice Returns manager address of a given vault address /// @param _vault Address of Aastra vault /// @return _manager Address of vault manager function vaultManager(address _vault) external view returns (address _manager); /// @notice Returns vault address of a given manager address /// @param _manager Address of vault manager /// @return _vault Address of Aastra vault function managerVault(address _manager) external view returns (address _vault); /// @notice Creates a new Aastra vault /// @param _uniswapPool Address of Uniswap V3 Pool /// @param _strategyManager Address of strategy manager managing the vault /// @param _protocolFee Fee charged by strategy manager for the new vault /// @param _strategyFee Fee charged by protocol for the new vault /// @param _maxCappedLimit Max limit of TVL of the vault function createVault( address _uniswapPool, address _strategyManager, uint256 _protocolFee, uint256 _strategyFee, uint256 _maxCappedLimit ) external; /// @notice Sets a new manager for an existing vault /// @param _newManager Address of the new manager for the vault /// @param _vault Address of the Aastra vault function updateManager(address _newManager, address _vault) external; /// @notice Returns the address of Router contract /// @return _router Address of Router contract function router() external view returns (address _router); /// @notice Returns the address of protocol governance /// @return _governance Address of protocol governance function governance() external view returns (address _governance); /// @notice Returns the address of pending protocol governance /// @return _pendingGovernance Address of pending protocol governance function pendingGovernance() external view returns (address _pendingGovernance); /// @notice Allows to upgrade the router contract to a new one /// @param _router Address of the new router contract function setRouter(address _router) external; /// @notice Allows to set a new governance address /// @param _governance Address of the new protocol governance function setGovernance(address _governance) external; /// @notice Function to be called by new governance method to accept the role function acceptGovernance() external; } pragma solidity >=0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import "../interfaces/IFactory.sol"; import "../interfaces/IERC20Metadata.sol"; /// @title Aastra Vault /// @author 0xKal1 /// @notice Aastra Vault is a Uniswap V3 liquidity management vault enabling you to automate yield generation on your idle funds /// @dev Provides an interface to the Aastra Vault interface IVault is IERC20 { /// @notice Emitted when a deposit made to a vault /// @param sender The sender of the deposit transaction /// @param to The recipient of LP tokens /// @param shares Amount of LP tokens paid to recipient /// @param amount0 Amount of token0 deposited /// @param amount1 Amount of token1 deposited event Deposit( address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1 ); /// @notice Emitted when a withdraw made to a vault /// @param sender The sender of the withdraw transaction /// @param to The recipient of withdrawn amounts /// @param shares Amount of LP tokens paid back to vault /// @param amount0 Amount of token0 withdrawn /// @param amount1 Amount of token1 withdrawn event Withdraw( address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees collected from uniswap /// @param feesToVault0 Amount of token0 earned as fee by protocol /// @param feesToVault1 Amount of token1 earned as fee by protocol /// @param feesToStrategy0 Amount of token0 earned as fee by strategy manager /// @param feesToStrategy1 Amount of token1 earned as fee by strategy manager event CollectFees( uint256 feesToVault0, uint256 feesToVault1, uint256 feesToStrategy0, uint256 feesToStrategy1 ); /// @notice Retrieve first token of Uniswap V3 pool /// @return IERC20Metadata token address function token0() external view returns (IERC20Metadata); /// @notice Retrieve second token of Uniswap V3 pool /// @return IERC20Metadata token address function token1() external view returns (IERC20Metadata); /// @notice Retrieve usable amount of token0 available in the vault /// @return amount0 Amount of token0 function getBalance0() external view returns (uint256); /// @notice Retrieve usable amount of token1 available in the vault /// @return amount1 Amount of token0 function getBalance1() external view returns (uint256); /// @notice Retrieve tickSpacing of Pool used in the vault /// @return tickSpacing tickSpacing of the Uniswap V3 pool function tickSpacing() external view returns (int24); /// @notice Retrieve lower tick of base position of Pool used in the vault /// @return baseLower of the Uniswap V3 pool function baseLower() external view returns (int24); /// @notice Retrieve upper tick of base position of Pool used in the vault /// @return baseUpper of the Uniswap V3 pool function baseUpper() external view returns (int24); /// @notice Retrieve lower tick of limit position of Pool used in the vault /// @return limitLower of the Uniswap V3 pool function limitLower() external view returns (int24); /// @notice Retrieve upper tick of limit position of Pool used in the vault /// @return limitUpper of the Uniswap V3 pool function limitUpper() external view returns (int24); /// @notice Retrieve address of Uni V3 Pool used in the vault /// @return IUniswapV3Pool address of Uniswap V3 Pool function pool() external view returns (IUniswapV3Pool); /// @notice Retrieve address of Factory used to create the vault /// @return IFactory address of Aastra factory contract function factory() external view returns (IFactory); /// @notice Retrieve address of current router in Aastra /// @return router address of Aastra router contract function router() external view returns (address); /// @notice Retrieve address of strategy manager used to manage the vault /// @return manager address of vault manager function strategy() external view returns (address); /** * @notice Calculates the vault's total holdings of token0 and token1 - in * other words, how much of each token the vault would hold if it withdrew * all its liquidity from Uniswap. * @return total0 Total token0 holdings of the vault * @return total1 Total token1 holdings of the vault */ function getTotalAmounts() external view returns (uint256, uint256); /// @dev Wrapper around `IUniswapV3Pool.positions()`. /// @notice Provides the current data on a position in the vault according to lower and upper tick /// @param tickLower Lower tick of the vault's position /// @param tickUpper Upper tick of the vault's position function position(int24 tickLower, int24 tickUpper) external view returns ( uint128, uint256, uint256, uint128, uint128 ); /** * @notice Amounts of token0 and token1 held in vault's position. Includes owed fees but excludes the proportion of fees that will be paid to the protocol. Doesn't include fees accrued since last poke. * @param tickLower Lower tick of the vault's position * @param tickUpper Upper tick of the vault's position * @return amount0 Amount of token0 held in the vault's position * @return amount1 Amount of token1 held in the vault's position */ function getPositionAmounts(int24 tickLower, int24 tickUpper) external view returns (uint256 amount0, uint256 amount1); /// ------------- Router Functions ------------- /// /// @notice Updates due amount in uniswap owed for a tick range /// @dev Do zero-burns to poke a position on Uniswap so earned fees are updated. Should be called if total amounts needs to include up-to-date fees. /// @param tickLower Lower bound of the tick range /// @param tickUpper Upper bound of the tick range function poke(int24 tickLower, int24 tickUpper) external; /// @notice Used to update the new base position ticks of the vault /// @param _baseLower The new lower tick of the vault /// @param _baseUpper The new upper tick of the vault function setBaseTicks(int24 _baseLower, int24 _baseUpper) external; /// @notice Used to update the new limit position ticks of the vault /// @param _limitLower The new lower tick of the vault /// @param _limitUpper The new upper tick of the vault function setLimitTicks(int24 _limitLower, int24 _limitUpper) external; /// @notice Withdraws all liquidity from a range and collects all the fees in the process /// @param tickLower Lower bound of the tick range /// @param tickUpper Upper bound of the tick range /// @param liquidity Liquidity to be withdrawn from the range /// @return burned0 Amount of token0 that was burned /// @return burned1 Amount of token1 that was burned /// @return feesToVault0 Amount of token0 fees vault earned /// @return feesToVault1 Amount of token1 fees vault earned function burnAndCollect( int24 tickLower, int24 tickUpper, uint128 liquidity ) external returns ( uint256 burned0, uint256 burned1, uint256 feesToVault0, uint256 feesToVault1 ); /// @notice This method will optimally use all the funds provided in argument to mint the maximum possible liquidity /// @param _lowerTick Lower bound of the tick range /// @param _upperTick Upper bound of the tick range /// @param amount0 Amount of token0 to be used for minting liquidity /// @param amount1 Amount of token1 to be used for minting liquidity function mintOptimalLiquidity( int24 _lowerTick, int24 _upperTick, uint256 amount0, uint256 amount1, bool swapEnabled ) external; /// @notice Swaps tokens from the pool /// @param direction The direction of the swap, true for token0 to token1, false for reverse /// @param amountInToSwap Desired amount of token0 or token1 wished to swap /// @return amountOut Amount of token0 or token1 received from the swap function swapTokensFromPool(bool direction, uint256 amountInToSwap) external returns (uint256 amountOut); /// @notice Collects liquidity fee earned from both positions of vault and reinvests them back into the same position function compoundFee() external; /// @notice Used to collect accumulated strategy fees. /// @param amount0 Amount of token0 to collect /// @param amount1 Amount of token1 to collect /// @param to Address to send collected fees to function collectStrategy( uint256 amount0, uint256 amount1, address to ) external; /// ------------- GOV Functions ------------- /// /** * @notice Emergency method to freeze actions performed by a strategy * @param value To be set to true in case of active freeze */ function freezeStrategy(bool value) external; /** * @notice Emergency method to freeze actions performed by a vault user * @param value To be set to true in case of active freeze */ function freezeUser(bool value) external; /// @notice Used to collect accumulated protocol fees. /// @param amount0 Amount of token0 to collect /// @param amount1 Amount of token1 to collect /// @param to Address to send collected fees to function collectProtocol( uint256 amount0, uint256 amount1, address to ) external; /** * @notice Used to change deposit cap for a guarded launch or to ensure * vault doesn't grow too large relative to the pool. Cap is on total * supply rather than amounts of token0 and token1 as those amounts * fluctuate naturally over time. * @param _maxTotalSupply The new max total cap of the vault */ function setMaxTotalSupply(uint256 _maxTotalSupply) external; /** * @notice Removes liquidity in case of emergency. * @param to Address to withdraw funds to */ function emergencyBurnAndCollect(address to) external; /// ------------- User Functions ------------- /// /** * @notice Deposits tokens in proportion to the vault's current holdings. * @param amount0Desired Max amount of token0 to deposit * @param amount1Desired Max amount of token1 to deposit * @param amount0Min Revert if resulting `amount0` is less than this * @param amount1Min Revert if resulting `amount1` is less than this * @param to Recipient of shares * @return shares Number of shares minted * @return amount0 Amount of token0 deposited * @return amount1 Amount of token1 deposited */ function deposit( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address to ) external returns ( uint256 shares, uint256 amount0, uint256 amount1 ); /** * @notice Withdraws tokens in proportion to the vault's holdings. * @param shares Shares burned by sender * @param amount0Min Revert if resulting `amount0` is smaller than this * @param amount1Min Revert if resulting `amount1` is smaller than this * @param to Recipient of tokens * @return amount0 Amount of token0 sent to recipient * @return amount1 Amount of token1 sent to recipient */ function withdraw( uint256 shares, uint256 amount0Min, uint256 amount1Min, address to ) external returns (uint256 amount0, uint256 amount1); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.5; import "@openzeppelin/contracts/token/ERC20/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); } pragma solidity >=0.7.5; library LongMath { /// @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; // 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; } } // 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: 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); } } } }
IPeriphery A middle layer between user and Aastra Vault to process transactions Provides an interface for Periphery/
interface IPeriphery { function vaultDeposit(uint256 amount, address token, uint256 slippage, address strategy) external; function vaultWithdraw(uint256 shares, address strategy, bool direction) external; pragma solidity >=0.7.5; }
14,656,311
/** *Submitted for verification at Etherscan.io on 2020-08-13 */ // File: @aragon/os/contracts/common/UnstructuredStorage.sol /* * SPDX-License-Identifier: MIT */ import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; pragma solidity 0.6.12; library Uint256Helpers { uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG); return uint64(a); } } library UnstructuredStorage { function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function getStorageAddress(bytes32 position) internal view returns (address data) { assembly { data := sload(position) } } function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) { assembly { data := sload(position) } } function getStorageUint256(bytes32 position) internal view returns (uint256 data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } function setStorageAddress(bytes32 position, address data) internal { assembly { sstore(position, data) } } function setStorageBytes32(bytes32 position, bytes32 data) internal { assembly { sstore(position, data) } } function setStorageUint256(bytes32 position, uint256 data) internal { assembly { sstore(position, data) } } } contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } contract Initializable is TimeHelpers { using UnstructuredStorage for bytes32; // keccak256("aragonOS.initializable.initializationBlock") bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED"; modifier onlyInit { require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED); _; } modifier isInitialized { require(hasInitialized(), ERROR_NOT_INITIALIZED); _; } /** * @return Block number in which the contract was initialized */ function getInitializationBlock() public view returns (uint256) { return INITIALIZATION_BLOCK_POSITION.getStorageUint256(); } /** * @return Whether the contract has been initialized by the time of the current block */ function hasInitialized() public view returns (bool) { uint256 initializationBlock = getInitializationBlock(); return initializationBlock != 0 && getBlockNumber() >= initializationBlock; } /** * @dev Function to be called by top level contract after initialization has finished. */ function initialized() internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber()); } /** * @dev Function to be called by top level contract after initialization to enable the contract * at a future block number rather than immediately. */ function initializedAt(uint256 _blockNumber) internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber); } } /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 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(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } interface ITokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) external payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) external returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) external returns(bool); } interface IMiniMeToken { function transfer(address _to, uint256 _amount) external returns (bool success); function transferFrom(address _from, address _to, uint256 _amount) external returns (bool success); function balanceOf(address _owner) external view returns (uint256 balance); function approve(address _spender, uint256 _amount) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function totalSupply() external view returns (uint); function balanceOfAt(address _owner, uint _blockNumber) external view returns (uint); function totalSupplyAt(uint _blockNumber) external view returns(uint); function decimals() external view returns(uint); } contract AragonVoting is Initializable, Ownable { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_VOTES_ROLE = 0xe7dcd7275292e064d090fbc5f3bd7995be23b502c1fed5cd94cfddbbdcd32bbc; //keccak256("CREATE_VOTES_ROLE"); bytes32 public constant MODIFY_SUPPORT_ROLE = 0xda3972983e62bdf826c4b807c4c9c2b8a941e1f83dfa76d53d6aeac11e1be650; //keccak256("MODIFY_SUPPORT_ROLE"); bytes32 public constant MODIFY_QUORUM_ROLE = 0xad15e7261800b4bb73f1b69d3864565ffb1fd00cb93cf14fe48da8f1f2149f39; //keccak256("MODIFY_QUORUM_ROLE"); bytes32 public constant SET_MIN_BALANCE_ROLE = 0xb1f3f26f63ad27cd630737a426f990492f5c674208299d6fb23bb2b0733d3d66; //keccak256("SET_MIN_BALANCE_ROLE") bytes32 public constant SET_MIN_TIME_ROLE = 0xe7ab0252519cd959720b328191bed7fe61b8e25f77613877be7070646d12daf0; //keccak256("SET_MIN_TIME_ROLE") bytes32 public constant ENABLE_VOTE_CREATION = 0xecb50dc3e77ba8a59697a3cc090a29b4cbd3c1f2b6b3aea524e0d166969592b9; //keccak256("ENABLE_VOTE_CREATION") bytes32 public constant DISABLE_VOTE_CREATION = 0x40b01f8b31b51596de2eeab8c325ff77cc3695c1c1875d66ff31176e7148d2a1; //keccack256("DISABLE_VOTE_CREATION") uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 string private constant ERROR_NO_VOTE = "VOTING_NO_VOTE"; string private constant ERROR_INIT_PCTS = "VOTING_INIT_PCTS"; string private constant ERROR_CHANGE_SUPPORT_PCTS = "VOTING_CHANGE_SUPPORT_PCTS"; string private constant ERROR_CHANGE_QUORUM_PCTS = "VOTING_CHANGE_QUORUM_PCTS"; string private constant ERROR_INIT_SUPPORT_TOO_BIG = "VOTING_INIT_SUPPORT_TOO_BIG"; string private constant ERROR_CHANGE_SUPPORT_TOO_BIG = "VOTING_CHANGE_SUPP_TOO_BIG"; string private constant ERROR_CAN_NOT_VOTE = "VOTING_CAN_NOT_VOTE"; string private constant ERROR_CAN_NOT_EXECUTE = "VOTING_CAN_NOT_EXECUTE"; string private constant ERROR_CAN_NOT_FORWARD = "VOTING_CAN_NOT_FORWARD"; string private constant ERROR_NO_VOTING_POWER = "VOTING_NO_VOTING_POWER"; enum VoterState { Absent, Yea, Nay } struct Vote { bool executed; uint64 startDate; uint64 snapshotBlock; uint64 supportRequiredPct; uint64 minAcceptQuorumPct; uint256 yea; uint256 nay; uint256 votingPower; bytes executionScript; mapping (address => VoterState) voters; } IMiniMeToken public token; uint64 public supportRequiredPct; uint64 public minAcceptQuorumPct; uint64 public voteTime; //2500000000000000000000 uint256 public minBalanceLowerLimit; uint256 public minBalanceUpperLimit; //43200 uint256 public minTimeLowerLimit; //1209600 uint256 public minTimeUpperLimit; uint256 public minBalance; uint256 public minTime; bool public enableVoteCreation; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => Vote) internal votes; uint256 public votesLength; mapping(address => uint256) public lastCreateVoteTimes; event StartVote(uint256 indexed voteId, address indexed creator, string metadata, uint256 minBalance, uint256 minTime, uint256 totalSupply, uint256 creatorVotingPower); event CastVote(uint256 indexed voteId, address indexed voter, bool support, uint256 stake); event ExecuteVote(uint256 indexed voteId); event ChangeSupportRequired(uint64 supportRequiredPct); event ChangeMinQuorum(uint64 minAcceptQuorumPct); event MinimumBalanceSet(uint256 minBalance); event MinimumTimeSet(uint256 minTime); modifier voteExists(uint256 _voteId) { require(_voteId < votesLength, ERROR_NO_VOTE); _; } modifier minBalanceCheck(uint256 _minBalance) { //_minBalance to be at least the equivalent of 10k locked for a year (1e18 precision) require(_minBalance >= minBalanceLowerLimit && _minBalance <= minBalanceUpperLimit, "Min balance should be within initialization hardcoded limits"); _; } modifier minTimeCheck(uint256 _minTime) { require(_minTime >= minTimeLowerLimit && _minTime <= minTimeUpperLimit, "Min time should be within initialization hardcoded limits"); _; } /** * @notice Initialize Voting app with `_token.symbol(): string` for governance, minimum support of `@formatPct(_supportRequiredPct)`%, minimum acceptance quorum of `@formatPct(_minAcceptQuorumPct)`%, and a voting duration of `@transformTime(_voteTime)` * @param _token IMiniMeToken Address that will be used as governance token * @param _supportRequiredPct Percentage of yeas in casted votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _minAcceptQuorumPct Percentage of yeas in total possible votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _voteTime Seconds that a vote will be open for token holders to vote (unless enough yeas or nays have been cast to make an early decision) * @param _minBalance Minumum balance that a token holder should have to create a new vote * @param _minTime Minimum time between a user's previous vote and creating a new vote * @param _minBalanceLowerLimit Hardcoded lower limit for _minBalance on initialization * @param _minTimeLowerLimit Hardcoded lower limit for _minTime on initialization * @param _minTimeUpperLimit Hardcoded upper limit for _minTime on initialization */ function initialize(IMiniMeToken _token, uint64 _supportRequiredPct, uint64 _minAcceptQuorumPct, uint64 _voteTime, uint256 _minBalance, uint256 _minTime, uint256 _minBalanceLowerLimit, uint256 _minBalanceUpperLimit, uint256 _minTimeLowerLimit, uint256 _minTimeUpperLimit ) external onlyInit { assert(CREATE_VOTES_ROLE == keccak256("CREATE_VOTES_ROLE")); assert(MODIFY_SUPPORT_ROLE == keccak256("MODIFY_SUPPORT_ROLE")); assert(MODIFY_QUORUM_ROLE == keccak256("MODIFY_QUORUM_ROLE")); assert(SET_MIN_BALANCE_ROLE == keccak256("SET_MIN_BALANCE_ROLE")); assert(SET_MIN_TIME_ROLE == keccak256("SET_MIN_TIME_ROLE")); assert(DISABLE_VOTE_CREATION == keccak256("DISABLE_VOTE_CREATION")); assert(ENABLE_VOTE_CREATION == keccak256("ENABLE_VOTE_CREATION")); initialized(); require(_minAcceptQuorumPct <= _supportRequiredPct, ERROR_INIT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_INIT_SUPPORT_TOO_BIG); require(_minBalance >= _minBalanceLowerLimit && _minBalance <= _minBalanceUpperLimit); require(_minTime >= _minTimeLowerLimit && _minTime <= _minTimeUpperLimit); token = _token; supportRequiredPct = _supportRequiredPct; minAcceptQuorumPct = _minAcceptQuorumPct; voteTime = _voteTime; uint256 decimalsMul = uint256(10) ** token.decimals(); minBalance = _minBalance.mul(decimalsMul); minTime = _minTime; minBalanceLowerLimit = _minBalanceLowerLimit.mul(decimalsMul); minBalanceUpperLimit = _minBalanceUpperLimit.mul(decimalsMul); minTimeLowerLimit = _minTimeLowerLimit; minTimeUpperLimit = _minTimeUpperLimit; emit MinimumBalanceSet(minBalance); emit MinimumTimeSet(minTime); enableVoteCreation = true; } /** * @notice Change required support to `@formatPct(_supportRequiredPct)`% * @param _supportRequiredPct New required support */ // function changeSupportRequiredPct(uint64 _supportRequiredPct) // external // authP(MODIFY_SUPPORT_ROLE, arr(uint256(_supportRequiredPct), uint256(supportRequiredPct))) // { // require(minAcceptQuorumPct <= _supportRequiredPct, ERROR_CHANGE_SUPPORT_PCTS); // require(_supportRequiredPct < PCT_BASE, ERROR_CHANGE_SUPPORT_TOO_BIG); // supportRequiredPct = _supportRequiredPct; // // emit ChangeSupportRequired(_supportRequiredPct); // } /** * @notice Change minimum acceptance quorum to `@formatPct(_minAcceptQuorumPct)`% * @param _minAcceptQuorumPct New acceptance quorum */ // function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) // external // authP(MODIFY_QUORUM_ROLE, arr(uint256(_minAcceptQuorumPct), uint256(minAcceptQuorumPct))) // { // require(_minAcceptQuorumPct <= supportRequiredPct, ERROR_CHANGE_QUORUM_PCTS); // minAcceptQuorumPct = _minAcceptQuorumPct; // // emit ChangeMinQuorum(_minAcceptQuorumPct); // } /** * @notice Change minimum balance needed to create a vote to `_minBalance` * @param _minBalance New minimum balance */ // function setMinBalance(uint256 _minBalance) external auth(SET_MIN_BALANCE_ROLE) minBalanceCheck(_minBalance) { // //min balance can't be set to lower than 10k * 1 year // minBalance = _minBalance; // // emit MinimumBalanceSet(_minBalance); // } /** * @notice Change minimum time needed to pass between user's previous vote and a user creating a new vote * @param _minTime New minumum time */ // function setMinTime(uint256 _minTime) external auth(SET_MIN_TIME_ROLE) minTimeCheck(_minTime) { // //min time should be within initialized hardcoded limits // minTime = _minTime; // // emit MinimumTimeSet(_minTime); // } //later role will be set to 0x0 - noone // function disableVoteCreationOnce() external auth(DISABLE_VOTE_CREATION) { // enableVoteCreation = false; // } // // function enableVoteCreationOnce() external auth(ENABLE_VOTE_CREATION) { // enableVoteCreation = true; // } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @return voteId Id for newly created vote */ function newVote(bytes calldata _executionScript, string calldata _metadata) external returns (uint256 voteId) { return _newVote(_executionScript, _metadata, true, true); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @param _castVote Whether to also cast newly created vote * @param _executesIfDecided Whether to also immediately execute newly created vote if decided * @return voteId id for newly created vote */ function newVote(bytes calldata _executionScript, string calldata _metadata, bool _castVote, bool _executesIfDecided) external returns (uint256 voteId) { return _newVote(_executionScript, _metadata, _castVote, _executesIfDecided); } /** * @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote * @param _supports Whether voter supports the vote * @param _executesIfDecided Whether the vote should execute its action if it becomes decided */ function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external voteExists(_voteId) { require(_canVote(_voteId, msg.sender), ERROR_CAN_NOT_VOTE); _vote(_voteId, _supports, msg.sender, _executesIfDecided); } /** * @notice Execute vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote */ function executeVote(uint256 _voteId) external voteExists(_voteId) { _executeVote(_voteId); } // Forwarding fns /** * @notice Tells whether the Voting app is a forwarder or not * @dev IForwarder interface conformance * @return Always true */ // function isForwarder() external pure override returns (bool) { // return true; // } /** * @notice Creates a vote to execute the desired action, and casts a support vote if possible * @dev IForwarder interface conformance * @param _evmScript Start vote with script */ // function forward(bytes memory _evmScript) public override { // require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); // _newVote(_evmScript, "", true, true); // } /** * @notice Tells whether `_sender` can forward actions or not * @dev IForwarder interface conformance * @param _sender Address of the account intending to forward an action * @return True if the given address can create votes, false otherwise */ // function canForward(address _sender, bytes memory) public view override returns (bool) { // // Note that `canPerform()` implicitly does an initialization check itself // return canPerform(_sender, CREATE_VOTES_ROLE, arr()) && canCreateNewVote(_sender); // } // Getter fns /** * @notice Tells whether a vote #`_voteId` can be executed or not * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @return True if the given vote can be executed, false otherwise */ function canExecute(uint256 _voteId) public view voteExists(_voteId) returns (bool) { return _canExecute(_voteId); } /** * @notice Tells whether `_sender` can participate in the vote #`_voteId` or not * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @return True if the given voter can participate a certain vote, false otherwise */ function canVote(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (bool) { return _canVote(_voteId, _voter); } function canCreateNewVote(address _sender) public view returns(bool) { return enableVoteCreation && token.balanceOf(_sender) >= minBalance && block.timestamp.sub(minTime) >= lastCreateVoteTimes[_sender]; } function getVote(uint256 _voteId) public view voteExists(_voteId) returns ( bool open, bool executed, uint64 startDate, uint64 snapshotBlock, uint64 supportRequired, uint64 minAcceptQuorum, uint256 yea, uint256 nay, uint256 votingPower, bytes memory script ) { Vote storage vote_ = votes[_voteId]; open = _isVoteOpen(vote_); executed = vote_.executed; startDate = vote_.startDate; snapshotBlock = vote_.snapshotBlock; supportRequired = vote_.supportRequiredPct; minAcceptQuorum = vote_.minAcceptQuorumPct; yea = vote_.yea; nay = vote_.nay; votingPower = vote_.votingPower; script = vote_.executionScript; } /** * @dev Return the state of a voter for a given vote by its ID * @param _voteId Vote identifier * @return VoterState of the requested voter for a certain vote */ function getVoterState(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (VoterState) { return votes[_voteId].voters[_voter]; } // Internal fns /** * @dev Internal function to create a new vote * @return voteId id for newly created vote */ function _newVote(bytes memory _executionScript, string calldata _metadata, bool _castVote, bool _executesIfDecided) internal returns (uint256 voteId) { require(canCreateNewVote(msg.sender)); uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 votingPower = token.totalSupplyAt(snapshotBlock); require(votingPower > 0, ERROR_NO_VOTING_POWER); voteId = votesLength++; Vote storage vote_ = votes[voteId]; vote_.startDate = getTimestamp64(); vote_.snapshotBlock = snapshotBlock; vote_.supportRequiredPct = supportRequiredPct; vote_.minAcceptQuorumPct = minAcceptQuorumPct; vote_.votingPower = votingPower; vote_.executionScript = _executionScript; emit StartVote(voteId, msg.sender, _metadata, minBalance, minTime, token.totalSupply(), token.balanceOfAt(msg.sender, snapshotBlock)); lastCreateVoteTimes[msg.sender] = getTimestamp64(); if (_castVote && _canVote(voteId, msg.sender)) { _vote(voteId, true, msg.sender, _executesIfDecided); } } /** * @dev Internal function to cast a vote. It assumes the queried vote exists. */ function _vote(uint256 _voteId, bool _supports, address _voter, bool _executesIfDecided) internal { Vote storage vote_ = votes[_voteId]; VoterState state = vote_.voters[_voter]; require(state == VoterState.Absent, "Can't change votes"); // This could re-enter, though we can assume the governance token is not malicious uint256 balance = token.balanceOfAt(_voter, vote_.snapshotBlock); uint256 voterStake = uint256(2).mul(balance).mul(vote_.startDate.add(voteTime).sub(getTimestamp64())).div(voteTime); if(voterStake > balance) { voterStake = balance; } if (_supports) { vote_.yea = vote_.yea.add(voterStake); } else { vote_.nay = vote_.nay.add(voterStake); } vote_.voters[_voter] = _supports ? VoterState.Yea : VoterState.Nay; emit CastVote(_voteId, _voter, _supports, voterStake); if (_executesIfDecided && _canExecute(_voteId)) { // We've already checked if the vote can be executed with `_canExecute()` _unsafeExecuteVote(_voteId); } } /** * @dev Internal function to execute a vote. It assumes the queried vote exists. */ function _executeVote(uint256 _voteId) internal { require(_canExecute(_voteId), ERROR_CAN_NOT_EXECUTE); _unsafeExecuteVote(_voteId); } /** * @dev Unsafe version of _executeVote that assumes you have already checked if the vote can be executed and exists */ function _unsafeExecuteVote(uint256 _voteId) internal { Vote storage vote_ = votes[_voteId]; vote_.executed = true; bytes memory input = new bytes(0); // TODO: Consider input for voting scripts // runScript(vote_.executionScript, input, new address[](0)); emit ExecuteVote(_voteId); } /** * @dev Internal function to check if a vote can be executed. It assumes the queried vote exists. * @return True if the given vote can be executed, false otherwise */ function _canExecute(uint256 _voteId) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; require(!_isVoteOpen(vote_), "Voting should be finished in order to execute the vote"); if (vote_.executed) { return false; } // Voting is already decided if (_isValuePct(vote_.yea, vote_.votingPower, vote_.supportRequiredPct)) { return true; } // Vote ended? if (_isVoteOpen(vote_)) { return false; } // Has enough support? uint256 totalVotes = vote_.yea.add(vote_.nay); if (!_isValuePct(vote_.yea, totalVotes, vote_.supportRequiredPct)) { return false; } // Has min quorum? if (!_isValuePct(vote_.yea, vote_.votingPower, vote_.minAcceptQuorumPct)) { return false; } return true; } /** * @dev Internal function to check if a voter can participate on a vote. It assumes the queried vote exists. * @return True if the given voter can participate a certain vote, false otherwise */ function _canVote(uint256 _voteId, address _voter) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; return _isVoteOpen(vote_) && token.balanceOfAt(_voter, vote_.snapshotBlock) > 0; } /** * @dev Internal function to check if a vote is still open * @return True if the given vote is open, false otherwise */ function _isVoteOpen(Vote storage vote_) internal view returns (bool) { return getTimestamp64() < vote_.startDate.add(voteTime) && !vote_.executed; } /** * @dev Calculates whether `_value` is more than a percentage `_pct` of `_total` */ function _isValuePct(uint256 _value, uint256 _total, uint256 _pct) internal pure returns (bool) { if (_total == 0) { return false; } uint256 computedPct = _value.mul(PCT_BASE) / _total; return computedPct > _pct; } }
Function to be called by top level contract after initialization has finished./
function initialized() internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber()); }
7,271,699
./full_match/97/0xA1e4af4C3A7cF5832732b73bD328e52fB1F82Fc1/sources/TBTPoolV2Permission.sol
Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
function _mint( address account, uint256 amount ) internal override { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); cTokenTotalSupply += amount; unchecked { cTokenBalances[account] += amount; } emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); }
3,285,880
// SPDX-License-Identifier: MIT pragma solidity =0.8.10; abstract contract IComptroller { struct CompMarketState { uint224 index; uint32 block; } mapping(address => uint) public compSpeeds; mapping(address => uint) public borrowCaps; mapping(address => uint) public compBorrowSpeeds; mapping(address => uint) public compSupplySpeeds; function claimComp(address holder) public virtual; function claimComp(address holder, address[] memory cTokens) public virtual; function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) public virtual; function compSupplyState(address) public view virtual returns (CompMarketState memory); function compSupplierIndex(address,address) public view virtual returns (uint); function compAccrued(address) public view virtual returns (uint); function compBorrowState(address) public view virtual returns (CompMarketState memory); function compBorrowerIndex(address,address) public view virtual returns (uint); function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); function getAssetsIn(address account) external virtual view returns (address[] memory); function markets(address account) public virtual view returns (bool, uint256); function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256); function oracle() public virtual view returns (address); } 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); } abstract contract ICToken is IERC20 { function mint(uint256 mintAmount) external virtual returns (uint256); function mint() external virtual payable; function accrueInterest() public virtual returns (uint); function redeem(uint256 redeemTokens) external virtual returns (uint256); function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256); function borrow(uint256 borrowAmount) external virtual returns (uint256); function borrowIndex() public view virtual returns (uint); function borrowBalanceStored(address) public view virtual returns(uint); function repayBorrow(uint256 repayAmount) external virtual returns (uint256); function repayBorrow() external virtual payable; function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256); function repayBorrowBehalf(address borrower) external virtual payable; function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral) external virtual returns (uint256); function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable; function exchangeRateCurrent() external virtual returns (uint256); function supplyRatePerBlock() external virtual returns (uint256); function borrowRatePerBlock() external virtual returns (uint256); function totalReserves() external virtual returns (uint256); function reserveFactorMantissa() external virtual returns (uint256); function borrowBalanceCurrent(address account) external virtual returns (uint256); function totalBorrowsCurrent() external virtual returns (uint256); function getCash() external virtual returns (uint256); function balanceOfUnderlying(address owner) external virtual returns (uint256); function underlying() external virtual returns (address); function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint); } 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 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"); } } } 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(); } } 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; } 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); } } contract MainnetCompAddresses { address internal constant C_ETH_ADDR = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address internal constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address internal constant COMP_ADDR = 0xc00e94Cb662C3520282E6f5717214004A7f26888; } contract CompHelper is MainnetCompAddresses{ uint256 constant NO_ERROR = 0; error CompEnterMarketError(); error CompExitMarketError(); // @notice Returns the underlying token address of the given cToken function getUnderlyingAddr(address _cTokenAddr) internal returns (address tokenAddr) { // cEth has no .underlying() method if (_cTokenAddr == C_ETH_ADDR) return TokenUtils.WETH_ADDR; tokenAddr = ICToken(_cTokenAddr).underlying(); } /// @notice Enters the Compound market so it can be deposited/borrowed /// @dev Markets can be entered multiple times, without the code reverting /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; uint256[] memory errCodes = IComptroller(COMPTROLLER_ADDR).enterMarkets(markets); if (errCodes[0] != NO_ERROR){ revert CompEnterMarketError(); } } /// @notice Exits the Compound market /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { if (IComptroller(COMPTROLLER_ADDR).exitMarket(_cTokenAddr) != NO_ERROR){ revert CompExitMarketError(); } } } contract CompBorrow is ActionBase, CompHelper { using TokenUtils for address; struct Params { address cTokenAddr; uint256 amount; address to; } error CompBorrowError(); /// @inheritdoc ActionBase function executeAction( bytes memory _callData, bytes32[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual override returns (bytes32) { Params memory params = parseInputs(_callData); params.cTokenAddr = _parseParamAddr(params.cTokenAddr, _paramMapping[0], _subData, _returnValues); params.amount = _parseParamUint(params.amount, _paramMapping[1], _subData, _returnValues); params.to = _parseParamAddr(params.to, _paramMapping[2], _subData, _returnValues); (uint256 withdrawAmount, bytes memory logData) = _borrow(params.cTokenAddr, params.amount, params.to); emit ActionEvent("CompBorrow", logData); return bytes32(withdrawAmount); } /// @inheritdoc ActionBase function executeActionDirect(bytes memory _callData) public payable override { Params memory params = parseInputs(_callData); (, bytes memory logData) = _borrow(params.cTokenAddr, params.amount, params.to); logger.logActionDirectEvent("CompBorrow", logData); } /// @inheritdoc ActionBase function actionType() public pure virtual override returns (uint8) { return uint8(ActionType.STANDARD_ACTION); } //////////////////////////// ACTION LOGIC //////////////////////////// /// @notice User borrows tokens from the Compound protocol /// @param _cTokenAddr Address of the cToken we are borrowing /// @param _amount Amount of tokens to be borrowed /// @param _to The address we are sending the borrowed tokens to function _borrow( address _cTokenAddr, uint256 _amount, address _to ) internal returns (uint256, bytes memory) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); // if the tokens are borrowed we need to enter the market enterMarket(_cTokenAddr); if (ICToken(_cTokenAddr).borrow(_amount) != NO_ERROR){ revert CompBorrowError(); } // always return WETH, never native Eth if (tokenAddr == TokenUtils.WETH_ADDR) { TokenUtils.depositWeth(_amount); } tokenAddr.withdrawTokens(_to, _amount); bytes memory logData = abi.encode(tokenAddr, _amount, _to); return (_amount, logData); } function parseInputs(bytes memory _callData) public pure returns (Params memory params) { params = abi.decode(_callData, (Params)); } }
User borrows tokens from the Compound protocol _cTokenAddr Address of the cToken we are borrowing _amount Amount of tokens to be borrowed _to The address we are sending the borrowed tokens to if the tokens are borrowed we need to enter the market always return WETH, never native Eth
function _borrow( address _cTokenAddr, uint256 _amount, address _to ) internal returns (uint256, bytes memory) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); enterMarket(_cTokenAddr); if (ICToken(_cTokenAddr).borrow(_amount) != NO_ERROR){ revert CompBorrowError(); } if (tokenAddr == TokenUtils.WETH_ADDR) { TokenUtils.depositWeth(_amount); } tokenAddr.withdrawTokens(_to, _amount); bytes memory logData = abi.encode(tokenAddr, _amount, _to); return (_amount, logData); }
6,953,381