file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/1/0x4482c5929618b848a46E3DA830A3D71085A5DE07/sources/src/nft/ZoraCreator1155Impl.sol
If we still have no schedule, return 0 supply royalty. If we have no recipient set, return 0 supply royalty.
function _handleSupplyRoyalty(uint256 tokenId, uint256 mintAmount, bytes memory data) internal returns (uint256 totalRoyaltyMints) { uint256 royaltyMintSchedule = royalties[tokenId].royaltyMintSchedule; if (royaltyMintSchedule == 0) { royaltyMintSchedule = royalties[CONTRACT_BASE_ID].royaltyMintSchedule; } if (royaltyMintSchedule == 0) { return 0; } totalRoyaltyMints = (mintAmount + (tokens[tokenId].totalMinted % royaltyMintSchedule)) / (royaltyMintSchedule - 1); if (totalRoyaltyMints > 0) { address royaltyRecipient = royalties[tokenId].royaltyRecipient; if (royaltyRecipient == address(0)) { royaltyRecipient = royalties[CONTRACT_BASE_ID].royaltyRecipient; } if (royaltyRecipient == address(0)) { return 0; } super._mint(royaltyRecipient, tokenId, totalRoyaltyMints, data); } }
16,490,090
./full_match/1/0xAD97639b0a94549E9391C20D5cAD0d52be96A383/sources/browser/ntrump.sol
dai to ntrumpdecimal changes make this harder. 1e21 = 18 + 18 - 15return(true,false);decimal changes make this harder. 1e21 = 18 + 18 - 15return(false, true);
function sellOrBuy() public view returns (bool _buy, bool _sell){ uint256 weightD = bpool.getDenormalizedWeight(address(want)); uint256 weightN = bpool.getDenormalizedWeight(address(ntrump)); uint256 balanceD = bpool.getBalance(address(want)); uint256 balanceN = bpool.getBalance(address(ntrump)); uint256 swapFee = bpool.getSwapFee(); uint256 outAmount = bpool.calcOutGivenIn(balanceD, weightD, balanceN, weightN, lotSizeBuy, swapFee); if(outAmount >= lotSizeBuy.mul(minBuy).div(1e21)){ _buy = true; } if(outAmount.mul(minSell).div(1e21) >= lotSizeSell){ _sell = true; } }
17,138,855
pragma solidity ^0.5.0; /** * @title Elliptic curve signature operations * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 */ library ECDSA { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param signature bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * and hash the result */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // Implementation of signature and verification by EIP712 for internal distribution token contract TokenExchangeVerification { using ECDSA for bytes32; string public constant name = "TokenExchangeVerification"; string public constant version = "1.0.0"; uint256 private _chainId; //web3.utils.soliditySha3('https://github.com/godappslab/signature-verification/contracts/TokenExchangeVerification.sol') //"0x21e9aa63a90ccdd955a8774d6c1884164cc3b549753ccc1ce262b12959be962e" bytes32 public constant salt = 0x21e9aa63a90ccdd955a8774d6c1884164cc3b549753ccc1ce262b12959be962e; struct EIP712Domain { string name; string version; uint256 chainId; address verifyingContract; bytes32 salt; } string private constant EIP712_DOMAIN_TYPE = "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"; bytes32 public constant EIP712_DOMAIN_TYPEHASH = keccak256(abi.encodePacked(EIP712_DOMAIN_TYPE)); struct Exchange { address sender; uint256 amount; bytes32 key; } string private constant EXCHANGE_TYPE = "Exchange(address sender,uint256 amount,bytes32 key)"; bytes32 public constant EXCHANGE_TYPEHASH = keccak256(abi.encodePacked(EXCHANGE_TYPE)); bytes32 DOMAIN_SEPARATOR; constructor(uint256 __chainId) public { _chainId = __chainId; DOMAIN_SEPARATOR = hashDomain(EIP712Domain({name: name, version: version, chainId: _chainId, verifyingContract: address(this), salt: salt})); } function chainId() public view returns (uint256) { return _chainId; } function verifyingContract() public view returns (address) { return address(this); } // @title Calculate EIP712Domain TypeHash function hashDomain(EIP712Domain memory eip712Domain) internal pure returns (bytes32) { return keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(eip712Domain.name)), keccak256(bytes(eip712Domain.version)), eip712Domain.chainId, eip712Domain.verifyingContract, eip712Domain.salt ) ); } // @title Calculate Exchange TypeHash function hashExchange(Exchange memory exchange) private view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(EXCHANGE_TYPEHASH, exchange.sender, exchange.amount, exchange.key))) ); } // @title Verify signature: Obtain EOA address from signature // @param bytes _signature // @param address sender // @param uint256 amount // @param bytes32 key // @return address EOA address obtained from signature function verify(bytes memory _signature, address sender, uint256 amount, bytes32 key) public view returns (address) { Exchange memory exchange = Exchange({sender: sender, amount: amount, key: key}); bytes32 hash = hashExchange(exchange); return hash.recover(_signature); } }
Calculate Exchange TypeHash
function hashExchange(Exchange memory exchange) private view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(EXCHANGE_TYPEHASH, exchange.sender, exchange.amount, exchange.key))) ); }
7,301,892
pragma solidity ^0.5.0; import 'openzeppelin-solidity/contracts/ownership/Ownable.sol'; /// @title A contract to store proof of documents and verify their existence /// @author John H. Yu /// @notice This is an assignment from ConsenSys Academy Blockchain Developer Bootcamp Spring 2019 course /// @dev Proof can be calculated offline to save gas contract ProofOfExistence is Ownable { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); /// @dev event emitted when notarize is called and succeeded event Notarized(address indexed owner, bytes32 indexed proof, uint time, string name, bytes32 tags, uint size, bytes32 contentType); bool private _paused; /// @dev struct save file/doc details struct DocInfo { string name; bytes32 tags; uint time; uint size; bytes32 contentType; address creator; } /// @dev mapping store file/doc details per proof. mapping (bytes32 => DocInfo) public proofDocInfo; /// @dev mapping store proofs owned per account. mapping (address => bytes32[]) public acountProofs; constructor () public { _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 owner to pause, triggers stopped state. */ function pause() public onlyOwner whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev Called by owner to unpause, returns to normal state. */ function unpause() public onlyOwner whenPaused { _paused = false; emit Unpaused(msg.sender); } // calculate and store the proof for a document /// @notice Notarize data of a document /// @dev This function burns a lot of gas. Consider calculate the hash offline then submit it using [addProof] /// @param name the name of the document /// @param tags the tags of the document /// @param size the size of the document /// @param contentType the content type of the document /// @param document the content of the document /// @return true if a new proof is stored. function notarize(string calldata name, bytes32 tags, uint size, bytes32 contentType, string calldata document) external whenNotPaused returns (bool) { bytes32 proof = proofFor(document); if (hasProof(proof)){ revert("This document has been Notarized before!"); } //store proof info. so later anyone can retrieve info abouta notarize file. proofDocInfo[proof].name = name; proofDocInfo[proof].tags = tags; proofDocInfo[proof].time = now; proofDocInfo[proof].size = size; proofDocInfo[proof].contentType = contentType; proofDocInfo[proof].creator = msg.sender; //group all proofs belonged to a user together acountProofs[msg.sender].push(proof); emit Notarized(msg.sender, proof, proofDocInfo[proof].time, name, tags, size, contentType); return true; } // helper function to get a document's keccak256 /// @notice caculate keccak256 of a document from its data /// @dev keccak256 is a variation of SHA3, different from NIST-SHA3 /// @param document the content of the document /// @return the proof in bytes32 function proofFor(string memory document) public pure returns (bytes32) { return keccak256(bytes(document)); } // verify if a document has been notarized /// @notice verify whether a document is notarized /// @dev ToDo /// @param document the content of the document /// @return boolean indicate whether the proof exist or not function verify(string memory document) public view returns (bool) { bytes32 proof = proofFor(document); return hasProof(proof); } // returns true if proof is stored /// @notice query a proof from storage /// @param proof a bytes32 hash /// @return boolean indicate whether the proof is stored or not function hasProof(bytes32 proof) internal view returns(bool) { return proofDocInfo[proof].creator != address(0); } /// @notice return all proofs done by current account /// @return proofs a bytes32 array function getAllProofs() external view returns(bytes32[] memory proofs) { return acountProofs[msg.sender]; } }
verify if a document has been notarized verify whether a document is notarized ToDo document the content of the document return boolean indicate whether the proof exist or not
function verify(string memory document) public view returns (bool) { bytes32 proof = proofFor(document); return hasProof(proof); }
13,021,570
pragma solidity ^0.4.13; contract Owned { modifier only_owner { if (msg.sender != owner) return; _; } event NewOwner(address indexed old, address indexed current); function setOwner(address _new) only_owner { NewOwner(owner, _new); owner = _new; } address public owner = msg.sender; } library Math { function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } } library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } contract LegalLazyScheduler is Ownable { uint64 public lastUpdate; uint64 public intervalDuration; bool schedulerEnabled = false; function() internal callback; event LogRegisteredInterval(uint64 date, uint64 duration); event LogProcessedInterval(uint64 date, uint64 intervals); /** * Triggers the registered callback function for the number of periods passed since last update */ modifier intervalTrigger() { uint64 currentTime = uint64(now); uint64 requiredIntervals = (currentTime - lastUpdate) / intervalDuration; if( schedulerEnabled && (requiredIntervals > 0)) { LogProcessedInterval(lastUpdate, requiredIntervals); while (requiredIntervals-- > 0) { callback(); } lastUpdate = currentTime; } _; } function LegalLazyScheduler() { lastUpdate = uint64(now); } function enableScheduler() onlyOwner public { schedulerEnabled = true; } function registerIntervalCall(uint64 _intervalDuration, function() internal _callback) internal { lastUpdate = uint64(now); intervalDuration = _intervalDuration; callback = _callback; LogRegisteredInterval(lastUpdate, intervalDuration); } } contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault(address _wallet) { require(_wallet != 0x0); wallet = _wallet; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyOwner { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } contract LegalTGE is Ownable, Pausable { /** * The safe math library for safety math opertations provided by Zeppelin */ using SafeMath for uint256; /** State machine * - PreparePreContribution: During this phase SmartOne adjust conversionRate and start/end date * - PreContribution: During this phase only registered users can contribute to the TGE and therefore receive a bonus until cap or end date is reached * - PrepareContribution: During this phase SmartOne adjusts conversionRate by the ETHUSD depreciation during PreContribution and change start and end date in case of an unforseen event * - Contribution: During this all users can contribute until cap or end date is reached * - Auditing: SmartOne awaits recommendation by auditor and board of foundation will then finalize contribution or enable refunding * - Finalized: Token are released * - Refunding: Refunds can be claimed */ enum States{PreparePreContribution, PreContribution, PrepareContribution, Contribution, Auditing, Finalized, Refunding} enum VerificationLevel { None, SMSVerified, KYCVerified } /** * Whenever the state of the contract changes, this event will be fired. */ event LogStateChange(States _states); /** * This event is fired when a user has been successfully verified by the external KYC verification process */ event LogKYCConfirmation(address sender); /** * Whenever a legalToken is assigned to this contract, this event will be fired. */ event LogTokenAssigned(address sender, address newToken); /** * Every timed transition must be loged for auditing */ event LogTimedTransition(uint _now, States _newState); /** * This event is fired when PreContribution data is changed during the PreparePreContribution phase */ event LogPreparePreContribution(address sender, uint conversionRate, uint startDate, uint endDate); /** * A user has transfered Ether and received unreleasead tokens in return */ event LogContribution(address contributor, uint256 weiAmount, uint256 tokenAmount, VerificationLevel verificationLevel, States _state); /** * This event will be fired when SmartOne finalizes the TGE */ event LogFinalized(address sender); /** * This event will be fired when the auditor confirms the confirms regularity confirmity */ event LogRegularityConfirmation(address sender, bool _regularity, bytes32 _comment); /** * This event will be fired when refunding is enabled by the auditor */ event LogRefundsEnabled(address sender); /** * This event is fired when PreContribution data is changed during the PreparePreContribution phase */ event LogPrepareContribution(address sender, uint conversionRate, uint startDate, uint endDate); /** * This refund vault used to hold funds while TGE is running. * Uses the default implementation provided by the OpenZeppelin community. */ RefundVault public vault; /** * Defines the state of the conotribution process */ States public state; /** * The token we are giving the contributors in return for their contributions */ LegalToken public token; /** * The contract provided by Parity Tech (Gav Woods) to verify the mobile number during user registration */ ProofOfSMS public proofOfSMS; /** * The contribution (wei) will be forwarded to this address after the token has been finalized by the foundation board */ address public multisigWallet; /** * Maximum amount of wei this TGE can raise. */ uint256 public tokenCap; /** * The amount of wei a contributor has contributed. * Used to check whether the total of contributions per user exceeds the max limit (depending on his verification level) */ mapping (address => uint) public weiPerContributor; /** * Minimum amount of tokens a contributor is able to buy */ uint256 public minWeiPerContributor; /** * Maximum amount of tokens an SMS verified user can contribute. */ uint256 public maxWeiSMSVerified; /** * Maximum amount of tokens an none-verified user can contribute. */ uint256 public maxWeiUnverified; /* * The number of token units a contributor receives per ETHER during pre-contribtion phase */ uint public preSaleConversionRate; /* * The UNIX timestamp (in seconds) defining when the pre-contribution phase will start */ uint public preSaleStartDate; /* * The UNIX timestamp (in seconds) defining when the TGE will end */ uint public preSaleEndDate; /* * The number of token units a contributor receives per ETHER during contribution phase */ uint public saleConversionRate; /* * The UNIX timestamp (in seconds) defining when the TGE will start */ uint public saleStartDate; /* * The UNIX timestamp (in seconds) defining when the TGE would end if cap will not be reached */ uint public saleEndDate; /* * The bonus a sms verified user will receive for a contribution during pre-contribution phase in base points */ uint public smsVerifiedBonusBps; /* * The bonus a kyc verified user will receive for a contribution during pre-contribution phase in base points */ uint public kycVerifiedBonusBps; /** * Total percent of tokens minted to the team at the end of the sale as base points * 1BP -> 0.01% */ uint public maxTeamBonusBps; /** * Only the foundation board is able to finalize the TGE. * Two of four members have to confirm the finalization. Therefore a multisig contract is used. */ address public foundationBoard; /** * Only the KYC confirmation account is allowed to confirm a successfull KYC verification */ address public kycConfirmer; /** * Once the contribution has ended an auditor will verify whether all regulations have been fullfilled */ address public auditor; /** * The tokens for the insitutional investors will be allocated to this wallet */ address public instContWallet; /** * This flag ist set by auditor before finalizing the TGE to indicate whether all regualtions have been fulfilled */ bool public regulationsFulfilled; /** * The auditor can comment the confirmation (e.g. in case of deviations) */ bytes32 public auditorComment; /** * The total number of institutional and public tokens sold during pre- and contribution phase */ uint256 public tokensSold = 0; /* * The number of tokens pre allocated to insitutional contributors */ uint public instContAllocatedTokens; /** * The amount of wei totally raised by the public TGE */ uint256 public weiRaised = 0; /* * The amount of wei raised during the preContribution phase */ uint256 public preSaleWeiRaised = 0; /* * How much wei we have given back to contributors. */ uint256 public weiRefunded = 0; /* * The number of tokens allocated to the team when the TGE was finalized. * The calculation is based on the predefined maxTeamBonusBps */ uint public teamBonusAllocatedTokens; /** * The number of contributors which have contributed to the TGE */ uint public numberOfContributors = 0; /** * dictionary that maps addresses to contributors which have sucessfully been verified by the external KYC process */ mapping (address => bool) public kycRegisteredContributors; struct TeamBonus { address toAddress; uint64 tokenBps; uint64 cliffDate; uint64 vestingDate; } /* * Defines the percentage (base points) distribution of the team-allocated bonus rewards among members which will be vested .. * 1 Bp -> 0.01% */ TeamBonus[] public teamBonuses; /** * @dev Check whether the TGE is currently in the state provided */ function LegalTGE (address _foundationBoard, address _multisigWallet, address _instContWallet, uint256 _instContAllocatedTokens, uint256 _tokenCap, uint256 _smsVerifiedBonusBps, uint256 _kycVerifiedBonusBps, uint256 _maxTeamBonusBps, address _auditor, address _kycConfirmer, ProofOfSMS _proofOfSMS, RefundVault _vault) { // -------------------------------------------------------------------------------- // -- Validate all variables which are not passed to the constructor first // -------------------------------------------------------------------------------- // the address of the account used for auditing require(_foundationBoard != 0x0); // the address of the multisig must not be 'undefined' require(_multisigWallet != 0x0); // the address of the wallet for constitutional contributors must not be 'undefined' require(_instContWallet != 0x0); // the address of the account used for auditing require(_auditor != 0x0); // the address of the cap for this TGE must not be 'undefined' require(_tokenCap > 0); // pre-contribution and contribution phases must not overlap // require(_preSaleStartDate <= _preSaleEndDate); multisigWallet = _multisigWallet; instContWallet = _instContWallet; instContAllocatedTokens = _instContAllocatedTokens; tokenCap = _tokenCap; smsVerifiedBonusBps = _smsVerifiedBonusBps; kycVerifiedBonusBps = _kycVerifiedBonusBps; maxTeamBonusBps = _maxTeamBonusBps; auditor = _auditor; foundationBoard = _foundationBoard; kycConfirmer = _kycConfirmer; proofOfSMS = _proofOfSMS; // -------------------------------------------------------------------------------- // -- Initialize all variables which are not passed to the constructor first // -------------------------------------------------------------------------------- state = States.PreparePreContribution; vault = _vault; } /** ============================================================================================================================= * All logic related to the TGE contribution is currently placed below. * ============================================================================================================================= */ function setMaxWeiForVerificationLevels(uint _minWeiPerContributor, uint _maxWeiUnverified, uint _maxWeiSMSVerified) public onlyOwner inState(States.PreparePreContribution) { require(_minWeiPerContributor >= 0); require(_maxWeiUnverified > _minWeiPerContributor); require(_maxWeiSMSVerified > _minWeiPerContributor); // the minimum number of wei an unverified user can contribute minWeiPerContributor = _minWeiPerContributor; // the maximum number of wei an unverified user can contribute maxWeiUnverified = _maxWeiUnverified; // the maximum number of wei an SMS verified user can contribute maxWeiSMSVerified = _maxWeiSMSVerified; } function setLegalToken(LegalToken _legalToken) public onlyOwner inState(States.PreparePreContribution) { token = _legalToken; if ( instContAllocatedTokens > 0 ) { // mint the pre allocated tokens for the institutional investors token.mint(instContWallet, instContAllocatedTokens); tokensSold += instContAllocatedTokens; } LogTokenAssigned(msg.sender, _legalToken); } function validatePreContribution(uint _preSaleConversionRate, uint _preSaleStartDate, uint _preSaleEndDate) constant internal { // the pre-contribution conversion rate must not be 'undefined' require(_preSaleConversionRate >= 0); // the pre-contribution start date must not be in the past require(_preSaleStartDate >= now); // the pre-contribution start date must not be in the past require(_preSaleEndDate >= _preSaleStartDate); } function validateContribution(uint _saleConversionRate, uint _saleStartDate, uint _saleEndDate) constant internal { // the contribution conversion rate must not be 'undefined' require(_saleConversionRate >= 0); // the contribution start date must not be in the past require(_saleStartDate >= now); // the contribution end date must not be before start date require(_saleEndDate >= _saleStartDate); } function isNowBefore(uint _date) constant internal returns (bool) { return ( now < _date ); } function evalTransitionState() public returns (States) { // once the TGE is in state finalized or refunding, there is now way to transit to another state! if ( hasState(States.Finalized)) return States.Finalized; if ( hasState(States.Refunding)) return States.Refunding; if ( isCapReached()) return States.Auditing; if ( isNowBefore(preSaleStartDate)) return States.PreparePreContribution; if ( isNowBefore(preSaleEndDate)) return States.PreContribution; if ( isNowBefore(saleStartDate)) return States.PrepareContribution; if ( isNowBefore(saleEndDate)) return States.Contribution; return States.Auditing; } modifier stateTransitions() { States evaluatedState = evalTransitionState(); setState(evaluatedState); _; } function hasState(States _state) constant private returns (bool) { return (state == _state); } function setState(States _state) private { if ( _state != state ) { state = _state; LogStateChange(state); } } modifier inState(States _state) { require(hasState(_state)); _; } function updateState() public stateTransitions { } /** * @dev Checks whether contract is in a state in which contributions will be accepted */ modifier inPreOrContributionState() { require(hasState(States.PreContribution) || (hasState(States.Contribution))); _; } modifier inPrePrepareOrPreContributionState() { require(hasState(States.PreparePreContribution) || (hasState(States.PreContribution))); _; } modifier inPrepareState() { // we can relay on state since modifer since already evaluated by stateTransitions modifier require(hasState(States.PreparePreContribution) || (hasState(States.PrepareContribution))); _; } /** * This modifier makes sure that not more tokens as specified can be allocated */ modifier teamBonusLimit(uint64 _tokenBps) { uint teamBonusBps = 0; for ( uint i = 0; i < teamBonuses.length; i++ ) { teamBonusBps = teamBonusBps.add(teamBonuses[i].tokenBps); } require(maxTeamBonusBps >= teamBonusBps); _; } /** * Allocates the team bonus with a specific vesting rule */ function allocateTeamBonus(address _toAddress, uint64 _tokenBps, uint64 _cliffDate, uint64 _vestingDate) public onlyOwner teamBonusLimit(_tokenBps) inState(States.PreparePreContribution) { teamBonuses.push(TeamBonus(_toAddress, _tokenBps, _cliffDate, _vestingDate)); } /** * This method can optional be called by the owner to adjust the conversionRate, startDate and endDate before contribution phase starts. * Pre-conditions: * - Caller is owner (deployer) * - TGE is in state PreContribution * Post-conditions: */ function preparePreContribution(uint _preSaleConversionRate, uint _preSaleStartDate, uint _preSaleEndDate) public onlyOwner inState(States.PreparePreContribution) { validatePreContribution(_preSaleConversionRate, _preSaleStartDate, _preSaleEndDate); preSaleConversionRate = _preSaleConversionRate; preSaleStartDate = _preSaleStartDate; preSaleEndDate = _preSaleEndDate; LogPreparePreContribution(msg.sender, preSaleConversionRate, preSaleStartDate, preSaleEndDate); } /** * This method can optional be called by the owner to adjust the conversionRate, startDate and endDate before pre contribution phase starts. * Pre-conditions: * - Caller is owner (deployer) * - Crowdsale is in state PreparePreContribution * Post-conditions: */ function prepareContribution(uint _saleConversionRate, uint _saleStartDate, uint _saleEndDate) public onlyOwner inPrepareState { validateContribution(_saleConversionRate, _saleStartDate, _saleEndDate); saleConversionRate = _saleConversionRate; saleStartDate = _saleStartDate; saleEndDate = _saleEndDate; LogPrepareContribution(msg.sender, saleConversionRate, saleStartDate, saleEndDate); } // fallback function can be used to buy tokens function () payable public { contribute(); } function getWeiPerContributor(address _contributor) public constant returns (uint) { return weiPerContributor[_contributor]; } function contribute() whenNotPaused stateTransitions inPreOrContributionState public payable { require(msg.sender != 0x0); require(msg.value >= minWeiPerContributor); VerificationLevel verificationLevel = getVerificationLevel(); // we only allow verified users to participate during pre-contribution phase require(hasState(States.Contribution) || verificationLevel > VerificationLevel.None); // we need to keep track of all contributions per user to limit total contributions weiPerContributor[msg.sender] = weiPerContributor[msg.sender].add(msg.value); // the total amount of ETH a KYC verified user can contribute is unlimited, so we do not need to check if ( verificationLevel == VerificationLevel.SMSVerified ) { // the total amount of ETH a non-KYC user can contribute is limited to maxWeiPerContributor require(weiPerContributor[msg.sender] <= maxWeiSMSVerified); } if ( verificationLevel == VerificationLevel.None ) { // the total amount of ETH a non-verified user can contribute is limited to maxWeiUnverified require(weiPerContributor[msg.sender] <= maxWeiUnverified); } if (hasState(States.PreContribution)) { preSaleWeiRaised = preSaleWeiRaised.add(msg.value); } weiRaised = weiRaised.add(msg.value); // calculate the token amount to be created uint256 tokenAmount = calculateTokenAmount(msg.value, verificationLevel); tokensSold = tokensSold.add(tokenAmount); if ( token.balanceOf(msg.sender) == 0 ) { numberOfContributors++; } if ( isCapReached()) { updateState(); } token.mint(msg.sender, tokenAmount); forwardFunds(); LogContribution(msg.sender, msg.value, tokenAmount, verificationLevel, state); } function calculateTokenAmount(uint256 _weiAmount, VerificationLevel _verificationLevel) public constant returns (uint256) { uint256 conversionRate = saleConversionRate; if ( state == States.PreContribution) { conversionRate = preSaleConversionRate; } uint256 tokenAmount = _weiAmount.mul(conversionRate); // an anonymous user (Level-0) gets no bonus uint256 bonusTokenAmount = 0; if ( _verificationLevel == VerificationLevel.SMSVerified ) { // a SMS verified user (Level-1) gets a bonus bonusTokenAmount = tokenAmount.mul(smsVerifiedBonusBps).div(10000); } else if ( _verificationLevel == VerificationLevel.KYCVerified ) { // a KYC verified user (Level-2) gets the highest bonus bonusTokenAmount = tokenAmount.mul(kycVerifiedBonusBps).div(10000); } return tokenAmount.add(bonusTokenAmount); } function getVerificationLevel() constant public returns (VerificationLevel) { if (kycRegisteredContributors[msg.sender]) { return VerificationLevel.KYCVerified; } else if (proofOfSMS.certified(msg.sender)) { return VerificationLevel.SMSVerified; } return VerificationLevel.None; } modifier onlyKycConfirmer() { require(msg.sender == kycConfirmer); _; } function confirmKYC(address addressId) onlyKycConfirmer inPrePrepareOrPreContributionState() public returns (bool) { LogKYCConfirmation(msg.sender); return kycRegisteredContributors[addressId] = true; } // ============================================================================================================================= // All functions related to the TGE cap come here // ============================================================================================================================= function isCapReached() constant internal returns (bool) { if (tokensSold >= tokenCap) { return true; } return false; } // ============================================================================================================================= // Everything which is related tof the auditing process comes here. // ============================================================================================================================= /** * @dev Throws if called by any account other than the foundation board */ modifier onlyFoundationBoard() { require(msg.sender == foundationBoard); _; } /** * @dev Throws if called by any account other than the auditor. */ modifier onlyAuditor() { require(msg.sender == auditor); _; } /** * @dev Throws if auditor has not yet confirmed TGE */ modifier auditorConfirmed() { require(auditorComment != 0x0); _; } /* * After the TGE reaches state 'auditing', the auditor will verify the legal and regulatory obligations */ function confirmLawfulness(bool _regulationsFulfilled, bytes32 _auditorComment) public onlyAuditor stateTransitions inState ( States.Auditing ) { regulationsFulfilled = _regulationsFulfilled; auditorComment = _auditorComment; LogRegularityConfirmation(msg.sender, _regulationsFulfilled, _auditorComment); } /** * After the auditor has verified the the legal and regulatory obligations of the TGE, the foundation board is able to finalize the TGE. * The finalization consists of the following steps: * - Transit state * - close the RefundVault and transfer funds to the foundation wallet * - release tokens (make transferable) * - enable scheduler for the inflation compensation * - Min the defined amount of token per team and make them vestable */ function finalize() public onlyFoundationBoard stateTransitions inState ( States.Auditing ) auditorConfirmed { setState(States.Finalized); // Make token transferable otherwise the transfer call used when granting vesting to teams will be rejected. token.releaseTokenTransfer(); // mint bonusus for allocateTeamBonusTokens(); // the funds can now be transfered to the multisig wallet of the foundation vault.close(); // disable minting for the TGE (though tokens will still be minted to compensate an inflation period) token.finishMinting(); // now we can safely enable the shceduler for inflation compensation token.enableScheduler(); // pass ownership from contract to SmartOne token.transferOwnership(owner); LogFinalized(msg.sender); } function enableRefunds() public onlyFoundationBoard stateTransitions inState ( States.Auditing ) auditorConfirmed { setState(States.Refunding); LogRefundsEnabled(msg.sender); // no need to trigger event here since this allready done in RefundVault (see event RefundsEnabled) vault.enableRefunds(); } // ============================================================================================================================= // Postallocation Reward Tokens // ============================================================================================================================= /** * Called once by TGE finalize() if the sale was success. */ function allocateTeamBonusTokens() private { for (uint i = 0; i < teamBonuses.length; i++) { // How many % of tokens the team member receive as rewards uint _teamBonusTokens = (tokensSold.mul(teamBonuses[i].tokenBps)).div(10000); // mint new tokens for contributors token.mint(this, _teamBonusTokens); token.grantVestedTokens(teamBonuses[i].toAddress, _teamBonusTokens, uint64(now), teamBonuses[i].cliffDate, teamBonuses[i].vestingDate, false, false); teamBonusAllocatedTokens = teamBonusAllocatedTokens.add(_teamBonusTokens); } } // ============================================================================================================================= // All functions related to Refunding can be found here. // Uses some slightly modifed logic from https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/crowdsale/RefundableTGE.sol // ============================================================================================================================= /** We're overriding the fund forwarding from TGE. * In addition to sending the funds, we want to call * the RefundVault deposit function */ function forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } /** * If TGE was not successfull refunding process will be released by SmartOne */ function claimRefund() public stateTransitions inState ( States.Refunding ) { // workaround since vault refund does not return refund value weiRefunded = weiRefunded.add(vault.deposited(msg.sender)); vault.refund(msg.sender); } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract LimitedTransferToken is ERC20 { /** * @dev Checks whether it can transfer or otherwise throws. */ modifier canTransfer(address _sender, uint256 _value) { require(_value <= transferableTokens(_sender, uint64(now))); _; } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _to The address that will receive the tokens. * @param _value The amount of tokens to be transferred. */ function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) public returns (bool) { return super.transfer(_to, _value); } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _from The address that will send the tokens. * @param _to The address that will receive the tokens. * @param _value The amount of tokens to be transferred. */ function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) public returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Default transferable tokens function returns all tokens for a holder (no limit). * @dev Overwriting transferableTokens(address holder, uint64 time) is the way to provide the * specific logic for limiting token transferability for a holder over time. */ function transferableTokens(address holder, uint64 time) public constant returns (uint256) { return balanceOf(holder); } } contract VestedToken is StandardToken, LimitedTransferToken, Ownable { uint256 MAX_GRANTS_PER_ADDRESS = 20; struct TokenGrant { address granter; // 20 bytes uint256 value; // 32 bytes uint64 cliff; uint64 vesting; uint64 start; // 3 * 8 = 24 bytes bool revokable; bool burnsOnRevoke; // 2 * 1 = 2 bits? or 2 bytes? } // total 78 bytes = 3 sstore per operation (32 per sstore) mapping (address => TokenGrant[]) public grants; event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint256 grantId); /** * @dev Grant tokens to a specified address * @param _to address The address which the tokens will be granted to. * @param _value uint256 The amount of tokens to be granted. * @param _start uint64 Time of the beginning of the grant. * @param _cliff uint64 Time of the cliff period. * @param _vesting uint64 The vesting period. */ function grantVestedTokens( address _to, uint256 _value, uint64 _start, uint64 _cliff, uint64 _vesting, bool _revokable, bool _burnsOnRevoke ) onlyOwner public { // Check for date inconsistencies that may cause unexpected behavior require(_cliff >= _start && _vesting >= _cliff); require(tokenGrantsCount(_to) < MAX_GRANTS_PER_ADDRESS); // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting). uint256 count = grants[_to].push( TokenGrant( _revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable _value, _cliff, _vesting, _start, _revokable, _burnsOnRevoke ) ); transfer(_to, _value); NewTokenGrant(msg.sender, _to, _value, count - 1); } /** * @dev Revoke the grant of tokens of a specifed address. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. */ function revokeTokenGrant(address _holder, uint256 _grantId) public { TokenGrant storage grant = grants[_holder][_grantId]; require(grant.revokable); require(grant.granter == msg.sender); // Only granter can revoke it address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender; uint256 nonVested = nonVestedTokens(grant, uint64(now)); // remove grant from array delete grants[_holder][_grantId]; grants[_holder][_grantId] = grants[_holder][grants[_holder].length.sub(1)]; grants[_holder].length -= 1; balances[receiver] = balances[receiver].add(nonVested); balances[_holder] = balances[_holder].sub(nonVested); Transfer(_holder, receiver, nonVested); } /** * @dev Calculate the total amount of transferable tokens of a holder at a given time * @param holder address The address of the holder * @param time uint64 The specific time. * @return An uint256 representing a holder's total amount of transferable tokens. */ function transferableTokens(address holder, uint64 time) public constant returns (uint256) { uint256 grantIndex = tokenGrantsCount(holder); if (grantIndex == 0) return super.transferableTokens(holder, time); // shortcut for holder without grants // Iterate through all the grants the holder has, and add all non-vested tokens uint256 nonVested = 0; for (uint256 i = 0; i < grantIndex; i++) { nonVested = SafeMath.add(nonVested, nonVestedTokens(grants[holder][i], time)); } // Balance - totalNonVested is the amount of tokens a holder can transfer at any given time uint256 vestedTransferable = SafeMath.sub(balanceOf(holder), nonVested); // Return the minimum of how many vested can transfer and other value // in case there are other limiting transferability factors (default is balanceOf) return Math.min256(vestedTransferable, super.transferableTokens(holder, time)); } /** * @dev Check the amount of grants that an address has. * @param _holder The holder of the grants. * @return A uint256 representing the total amount of grants. */ function tokenGrantsCount(address _holder) public constant returns (uint256 index) { return grants[_holder].length; } /** * @dev Calculate amount of vested tokens at a specific time * @param tokens uint256 The amount of tokens granted * @param time uint64 The time to be checked * @param start uint64 The time representing the beginning of the grant * @param cliff uint64 The cliff period, the period before nothing can be paid out * @param vesting uint64 The vesting period * @return An uint256 representing the amount of vested tokens of a specific grant * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Cliff Vesting */ function calculateVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vesting) public constant returns (uint256) { // Shortcuts for before cliff and after vesting cases. if (time < cliff) return 0; if (time >= vesting) return tokens; // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can use just calculate a value // in the vesting rect (as shown in above's figure) // vestedTokens = (tokens * (time - start)) / (vesting - start) uint256 vestedTokens = SafeMath.div( SafeMath.mul( tokens, SafeMath.sub(time, start) ), SafeMath.sub(vesting, start) ); return vestedTokens; } /** * @dev Get all information about a specific grant. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. * @return Returns all the values that represent a TokenGrant(address, value, start, cliff, * revokability, burnsOnRevoke, and vesting) plus the vested value at the current time. */ function tokenGrant(address _holder, uint256 _grantId) public constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) { TokenGrant storage grant = grants[_holder][_grantId]; granter = grant.granter; value = grant.value; start = grant.start; cliff = grant.cliff; vesting = grant.vesting; revokable = grant.revokable; burnsOnRevoke = grant.burnsOnRevoke; vested = vestedTokens(grant, uint64(now)); } /** * @dev Get the amount of vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time The time to be checked * @return An uint256 representing the amount of vested tokens of a specific grant at a specific time. */ function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return calculateVestedTokens( grant.value, uint256(time), uint256(grant.start), uint256(grant.cliff), uint256(grant.vesting) ); } /** * @dev Calculate the amount of non vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time uint64 The time to be checked * @return An uint256 representing the amount of non vested tokens of a specific grant on the * passed time frame. */ function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return grant.value.sub(vestedTokens(grant, time)); } /** * @dev Calculate the date when the holder can transfer all its tokens * @param holder address The address of the holder * @return An uint256 representing the date of the last transferable tokens. */ function lastTokenIsTransferableDate(address holder) public constant returns (uint64 date) { date = uint64(now); uint256 grantIndex = grants[holder].length; for (uint256 i = 0; i < grantIndex; i++) { date = Math.max64(grants[holder][i].vesting, date); } } } contract Certifier { event Confirmed(address indexed who); event Revoked(address indexed who); function certified(address _who) constant returns (bool); // function get(address _who, string _field) constant returns (bytes32) {} // function getAddress(address _who, string _field) constant returns (address) {} // function getUint(address _who, string _field) constant returns (uint) {} } contract SimpleCertifier is Owned, Certifier { modifier only_delegate { assert(msg.sender == delegate); _; } modifier only_certified(address _who) { if (!certs[_who].active) return; _; } struct Certification { bool active; mapping (string => bytes32) meta; } function certify(address _who) only_delegate { certs[_who].active = true; Confirmed(_who); } function revoke(address _who) only_delegate only_certified(_who) { certs[_who].active = false; Revoked(_who); } function certified(address _who) constant returns (bool) { return certs[_who].active; } // function get(address _who, string _field) constant returns (bytes32) { return certs[_who].meta[_field]; } // function getAddress(address _who, string _field) constant returns (address) { return address(certs[_who].meta[_field]); } // function getUint(address _who, string _field) constant returns (uint) { return uint(certs[_who].meta[_field]); } function setDelegate(address _new) only_owner { delegate = _new; } mapping (address => Certification) certs; // So that the server posting puzzles doesn't have access to the ETH. address public delegate = msg.sender; } contract ProofOfSMS is SimpleCertifier { modifier when_fee_paid { if (msg.value < fee) { RequiredFeeNotMet(fee, msg.value); return; } _; } event RequiredFeeNotMet(uint required, uint provided); event Requested(address indexed who); event Puzzled(address who, bytes32 puzzle); event LogAddress(address test); function request() payable when_fee_paid { if (certs[msg.sender].active) { return; } Requested(msg.sender); } function puzzle (address _who, bytes32 _puzzle) only_delegate { puzzles[_who] = _puzzle; Puzzled(_who, _puzzle); } function confirm(bytes32 _code) returns (bool) { LogAddress(msg.sender); if (puzzles[msg.sender] != sha3(_code)) return; delete puzzles[msg.sender]; certs[msg.sender].active = true; Confirmed(msg.sender); return true; } function setFee(uint _new) only_owner { fee = _new; } function drain() only_owner { require(msg.sender.send(this.balance)); } function certified(address _who) constant returns (bool) { return certs[_who].active; } mapping (address => bytes32) puzzles; uint public fee = 30 finney; } contract LegalToken is LegalLazyScheduler, MintableToken, VestedToken { /** * The name of the token */ bytes32 public name; /** * The symbol used for exchange */ bytes32 public symbol; /** * Use to convert to number of tokens. */ uint public decimals = 18; /** * The yearly expected inflation rate in base points. */ uint32 public inflationCompBPS; /** * The tokens are locked until the end of the TGE. * The contract can release the tokens if TGE successful. If false we are in transfer lock up period. */ bool public released = false; /** * Annually new minted tokens will be transferred to this wallet. * Publications will be rewarded with funds (incentives). */ address public rewardWallet; /** * Name and symbol were updated. */ event UpdatedTokenInformation(bytes32 newName, bytes32 newSymbol); /** * @dev Constructor that gives msg.sender all of existing tokens. */ function LegalToken(address _rewardWallet, uint32 _inflationCompBPS, uint32 _inflationCompInterval) onlyOwner public { setTokenInformation("Legal Token", "LGL"); totalSupply = 0; rewardWallet = _rewardWallet; inflationCompBPS = _inflationCompBPS; registerIntervalCall(_inflationCompInterval, mintInflationPeriod); } /** * This function allows the token owner to rename the token after the operations * have been completed and then point the audience to use the token contract. */ function setTokenInformation(bytes32 _name, bytes32 _symbol) onlyOwner public { name = _name; symbol = _symbol; UpdatedTokenInformation(name, symbol); } /** * Mint new tokens for the predefined inflation period and assign them to the reward wallet. */ function mintInflationPeriod() private { uint256 tokensToMint = totalSupply.mul(inflationCompBPS).div(10000); totalSupply = totalSupply.add(tokensToMint); balances[rewardWallet] = balances[rewardWallet].add(tokensToMint); Mint(rewardWallet, tokensToMint); Transfer(0x0, rewardWallet, tokensToMint); } function setRewardWallet(address _rewardWallet) public onlyOwner { rewardWallet = _rewardWallet; } /** * Limit token transfer until the TGE is over. */ modifier tokenReleased(address _sender) { require(released); _; } /** * This will make the tokens transferable */ function releaseTokenTransfer() public onlyOwner { released = true; } // error: canTransfer(msg.sender, _value) function transfer(address _to, uint _value) public tokenReleased(msg.sender) intervalTrigger returns (bool success) { // Calls StandardToken.transfer() // error: super.transfer(_to, _value); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) public tokenReleased(_from) intervalTrigger returns (bool success) { // Calls StandardToken.transferForm() return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public tokenReleased(msg.sender) intervalTrigger returns (bool) { // calls StandardToken.approve(..) return super.approve(_spender, _value); } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { // calls StandardToken.allowance(..) return super.allowance(_owner, _spender); } function increaseApproval (address _spender, uint _addedValue) public tokenReleased(msg.sender) intervalTrigger returns (bool success) { // calls StandardToken.increaseApproval(..) return super.increaseApproval(_spender, _addedValue); } function decreaseApproval (address _spender, uint _subtractedValue) public tokenReleased(msg.sender) intervalTrigger returns (bool success) { // calls StandardToken.decreaseApproval(..) return super.decreaseApproval(_spender, _subtractedValue); } }
once the TGE is in state finalized or refunding, there is now way to transit to another state!
function evalTransitionState() public returns (States) { if ( hasState(States.Finalized)) return States.Finalized; if ( hasState(States.Refunding)) return States.Refunding; if ( isCapReached()) return States.Auditing; if ( isNowBefore(preSaleStartDate)) return States.PreparePreContribution; if ( isNowBefore(preSaleEndDate)) return States.PreContribution; if ( isNowBefore(saleStartDate)) return States.PrepareContribution; if ( isNowBefore(saleEndDate)) return States.Contribution; return States.Auditing; }
6,387,510
// SPDX-License-Identifier: GPL-3.0 // @author : Bugrahan OZTURK // @date : 22.08.2021 // @reference : https://solidity-by-example.org/signature/ pragma solidity ^0.7; contract VerifySignature { // use this function to get the hash of any string function getHash(string memory str) public pure returns (bytes32) { return keccak256(abi.encodePacked(str)); } // take the keccak256 hashed message from the getHash function above and input into this function // this function prefixes the hash above with \x19Ethereum signed message:\n32 + hash // and produces a new hash signature function getEthSignedHash(bytes32 _messageHash) public pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash)); } // input the getEthSignedHash results and the signature hash results // the output of this function will be the account number that signed the original message function verify(bytes32 _ethSignedMessageHash, bytes memory _signature) public pure returns (address) { (bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature); return ecrecover(_ethSignedMessageHash, v, r, s); } function splitSignature(bytes memory sig) public pure returns (bytes32 r, bytes32 s, uint8 v) { require(sig.length == 65, "Invalid signature length"); assembly { /* First 32 bytes stores the length of the signature add(sig, 32) = pointer of sig + 32 effectively, skips first 32 bytes of signature mload(p) loads next 32 bytes starting at the memory address p into memory */ // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } // implicitly return (r, s, v) } }
first 32 bytes, after the length prefix second 32 bytes final byte (first byte of the next 32 bytes)
function splitSignature(bytes memory sig) public pure returns (bytes32 r, bytes32 s, uint8 v) { require(sig.length == 65, "Invalid signature length"); assembly { First 32 bytes stores the length of the signature add(sig, 32) = pointer of sig + 32 effectively, skips first 32 bytes of signature mload(p) loads next 32 bytes starting at the memory address p into memory r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) }
14,050,653
./partial_match/1/0x3711c959d9732255Dd5c0843622d8D364F143d73/sources/ComptrollerG1.sol
Sets the collateralFactor for a market Admin function to set per-market collateralFactor cToken The market to set the factor on newCollateralFactorMantissa The new collateral factor, scaled by 1e18 return uint 0=success, otherwise a failure. (See ErrorReporter for details)/ Check caller is admin
function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint256) { if (!hasAdminRights()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } market.collateralFactorMantissa = newCollateralFactorMantissa; return uint(Error.NO_ERROR); uint oldCollateralFactorMantissa = market.collateralFactorMantissa; emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); }
15,715,371
pragma solidity^0.4.18; //"AAPL", "2", "1.45", "0.5" contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract TokenERC20 { string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } } contract Advanced is owned, TokenERC20 { uint256 public sellPrice; uint256 public buyPrice; mapping (address => bool) public frozenAccount; // This generates a public event on the blockchain that will notify clients event FrozenFunds(address target, bool frozen); // Initializes contract with initial supply tokens to the creator of the contract function Advanced( uint256 initialSupply, string tokenName, string tokenSymbol ) TokenERC20(initialSupply, tokenName, tokenSymbol) public {} // Internal transfer, only can be called by this contract function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient Transfer(_from, _to, _value); } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth /// @param newSellPrice Price the users can sell to the contract /// @param newBuyPrice Price users can buy from the contract function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /// @notice Buy tokens from contract by sending ether function buy() payable public { uint amount = msg.value / buyPrice; // calculates the amount _transfer(this, msg.sender, amount); // makes the transfers } /// @notice Sell `amount` tokens to contract /// @param amount amount of tokens to be sold function sell(uint256 amount) public { require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy _transfer(msg.sender, this, amount); // makes the transfers msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks } } contract UsingFunctions{ function stringToUint(string _amount) internal pure returns (uint result) { bytes memory b = bytes(_amount); uint i; uint counterBeforeDot; uint counterAfterDot; result = 0; uint totNum = b.length; totNum--; bool hasDot = false; for (i = 0; i < b.length; i++) { uint c = uint(b[i]); if (c >= 48 && c <= 57) { result = result * 10 + (c - 48); counterBeforeDot ++; totNum--; } if(c == 46){ hasDot = true; break; } } if(hasDot) { for (uint j = counterBeforeDot + 1; j < 18; j++) { uint m = uint(b[j]); if (m >= 48 && m <= 57) { result = result * 10 + (m - 48); counterAfterDot ++; totNum--; } if(totNum == 0){ break; } } } if(counterAfterDot < 18){ uint addNum = 18 - counterAfterDot; uint multuply = 10 ** addNum; return result = result * multuply; } return result; } function tokenFlow( string assetPrice, string tokenPrice, uint volume ) internal pure returns (uint) { return stringToUint(tokenPrice)*volume/stringToUint(assetPrice); } } contract Econarchy is Advanced, UsingFunctions{ struct Position { uint volume; string direction; uint tokensBet; uint time; bool initialized; } // mapping(string => Position) positions; // mapping(bool => mapping(string => Position)) directions; //True for Long positions, False for shorts(this is to save memory, OK ????) //Each player can have a number of positions in different shadow assets. This is a mapping from ticker string to Position(dir, vol, tokensBet, time) struct. mapping(address => mapping(bool => mapping(string => Position)) ) accounts; // account ------>BUY or SELL----------------->Position //Types of events to record event EnterContract(address _player, string _ticker, string _direction, string _volume, uint _time); event PartialExecution(address _player, string _ticker, string _direction, string _volume, uint _time); event FullExecution(address _player, string _ticker, string _direction, uint _time); //Constructor function Econarchy(uint256 initialSupply) Advanced(initialSupply, "Econarchy", "khi") public {} /// @notice Opens long position for shadow asset `_ticker` of size `_volume` /// @param ticker kek /// @param volume kek /// @param assetPrice kek /// @param tokenPrice kek function OpenLong( string ticker, string volume, string assetPrice, string tokenPrice) public onlyOwner { uint volumeUint = stringToUint(volume); //Quote current asset price and token price (express in big numbers tho) uint tokenFlows = tokenFlow(tokenPrice, assetPrice, volumeUint); //calculate cost of buying in token terms require(balanceOf[msg.sender] >= tokenFlows); //check if there is enough funds to buy balanceOf[msg.sender] -= tokenFlows; //Withdraw khi(wei) from message sender's balance if(accounts[msg.sender][true][ticker].initialized == false){ //If there's no position yet accounts[msg.sender][true][ticker] = Position(volumeUint, "BUY", tokenFlows, now, true); //Record this position to message sender's account } else { //If already has position accounts[msg.sender][true][ticker].volume+=volumeUint; accounts[msg.sender][true][ticker].tokensBet+= tokenFlows; } EnterContract(msg.sender, ticker, "BUY", volume, now); //Put this event on the blockchain } /// @notice Closes long position for shadow asset `_ticker`. `_volume` can be less or equal /// @param ticker kek /// @param volume kek /// @param assetPrice kek /// @param tokenPrice kek function CloseLong( string ticker, string volume, string assetPrice, string tokenPrice) public onlyOwner { uint volumeUint = stringToUint(volume); require(accounts[msg.sender][true][ticker].volume >= volumeUint); ////////////////////must check for buy position //Quote current asset price and token price (express in big numbers tho) uint tokenFlows = tokenFlow(tokenPrice, assetPrice, volumeUint); uint executedBetTokens = volumeUint*accounts[msg.sender][true][ticker].tokensBet/accounts[msg.sender][true][ticker].volume; if (accounts[msg.sender][true][ticker].volume == volumeUint){ //If executed in full ammount delete accounts[msg.sender][true][ticker]; //Delete position from message sender's account FullExecution(msg.sender, ticker, "BUY", now); //Put this event on the blockchain } else { //If position is only partly executed accounts[msg.sender][true][ticker].volume -= volumeUint; //Subtract executed volume from corresponding account accounts[msg.sender][true][ticker].tokensBet-=executedBetTokens; //Subtract executed tokens from tokens that were bet PartialExecution(msg.sender, ticker, "BUY", volume, now); //put `PartialExecution` event on the blockchain } balanceOf[msg.sender] += tokenFlows; //Player gets returns to the balance //Adjust total supply if(tokenFlows > executedBetTokens){ totalSupply+=(tokenFlows - executedBetTokens); }else{ totalSupply-=(executedBetTokens - tokenFlows); } } }
Set allowance for other address Allows `_spender` to spend no more than `_value` tokens in your behalf _spender The address authorized to spend _value the max amount they can spend/
function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; }
2,516,165
./partial_match/1/0x08912DDa356f3F9898685221654CcF8643F1889a/sources/contracts/strategies/lending/BaseLendingStrategy.sol
must fetch price from lending protocol's oracle must fetch price from lending protocol's oracle
function _getCurrentDebt() internal virtual returns (uint256); function _getCurrentCollateral() internal virtual returns (uint256); function _getCollateralPrice() internal view virtual returns (uint256); function _getTokenToBorrowPrice() internal view virtual returns (uint256); function _getCurrentLTV() internal returns (uint256) { uint256 debtValue = _getTokenToBorrowPrice() * _getCurrentDebt() / (10 ** tokenToBorrow.decimals()); uint256 collateralValue = _getCollateralPrice() * _getCurrentCollateral() / (10 ** collateral.decimals()); if ((debtValue == 0) || (collateralValue == 0)) { return 0; } return debtValue * (10 ** 6) / collateralValue; }
4,457,313
./full_match/1/0x92A9f26e825161858C470A24211A1BA186dcCdC8/sources/contracts/Nft/ERC721.sol
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 _holderTokens[owner].length(); }
2,970,680
pragma solidity ^0.4.21; // SafeMath is a part of Zeppelin Solidity library // licensed under MIT License // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/LICENSE /** * @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; } } // https://github.com/OpenZeppelin/zeppelin-solidity /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Protection from short address attack */ modifier onlyPayloadSize(uint size) { assert(msg.data.length == size + 4); _; } /** * @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) onlyPayloadSize(2 * 32) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); _postTransferHook(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /** * @dev Hook for custom actions to be executed after transfer has completed * @param _from Transferred from * @param _to Transferred to * @param _value Value transferred */ function _postTransferHook(address _from, address _to, uint256 _value) internal; } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); _postTransferHook(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Owned { address owner; modifier onlyOwner { require(msg.sender == owner); _; } /// @dev Contract constructor function Owned() public { owner = msg.sender; } } contract AcceptsTokens { ETToken public tokenContract; function AcceptsTokens(address _tokenContract) public { tokenContract = ETToken(_tokenContract); } modifier onlyTokenContract { require(msg.sender == address(tokenContract)); _; } function acceptTokens(address _from, uint256 _value, uint256 param1, uint256 param2, uint256 param3) external; } contract ETToken is Owned, StandardToken { using SafeMath for uint; string public name = "ETH.TOWN Token"; string public symbol = "ETIT"; uint8 public decimals = 18; address public beneficiary; address public oracle; address public heroContract; modifier onlyOracle { require(msg.sender == oracle); _; } mapping (uint32 => address) public floorContracts; mapping (address => bool) public canAcceptTokens; mapping (address => bool) public isMinter; modifier onlyMinters { require(msg.sender == owner || isMinter[msg.sender]); _; } event Dividend(uint256 value); event Withdrawal(address indexed to, uint256 value); event Burn(address indexed from, uint256 value); function ETToken() public { oracle = owner; beneficiary = owner; totalSupply_ = 0; } function setOracle(address _oracle) external onlyOwner { oracle = _oracle; } function setBeneficiary(address _beneficiary) external onlyOwner { beneficiary = _beneficiary; } function setHeroContract(address _heroContract) external onlyOwner { heroContract = _heroContract; } function _mintTokens(address _user, uint256 _amount) private { require(_user != 0x0); balances[_user] = balances[_user].add(_amount); totalSupply_ = totalSupply_.add(_amount); emit Transfer(address(this), _user, _amount); } function authorizeFloor(uint32 _index, address _floorContract) external onlyOwner { floorContracts[_index] = _floorContract; } function _acceptDividends(uint256 _value) internal { uint256 beneficiaryShare = _value / 5; uint256 poolShare = _value.sub(beneficiaryShare); beneficiary.transfer(beneficiaryShare); emit Dividend(poolShare); } function acceptDividends(uint256 _value, uint32 _floorIndex) external { require(floorContracts[_floorIndex] == msg.sender); _acceptDividends(_value); } function rewardTokensFloor(address _user, uint256 _tokens, uint32 _floorIndex) external { require(floorContracts[_floorIndex] == msg.sender); _mintTokens(_user, _tokens); } function rewardTokens(address _user, uint256 _tokens) external onlyMinters { _mintTokens(_user, _tokens); } function() payable public { // Intentionally left empty, for use by floors } function payoutDividends(address _user, uint256 _value) external onlyOracle { _user.transfer(_value); emit Withdrawal(_user, _value); } function accountAuth(uint256 /*_challenge*/) external { // Does nothing by design } function burn(uint256 _amount) external { require(balances[msg.sender] >= _amount); balances[msg.sender] = balances[msg.sender].sub(_amount); totalSupply_ = totalSupply_.sub(_amount); emit Burn(msg.sender, _amount); } function setCanAcceptTokens(address _address, bool _value) external onlyOwner { canAcceptTokens[_address] = _value; } function setIsMinter(address _address, bool _value) external onlyOwner { isMinter[_address] = _value; } function _invokeTokenRecipient(address _from, address _to, uint256 _value, uint256 _param1, uint256 _param2, uint256 _param3) internal { if (!canAcceptTokens[_to]) { return; } AcceptsTokens recipient = AcceptsTokens(_to); recipient.acceptTokens(_from, _value, _param1, _param2, _param3); } /** * @dev transfer token for a specified address and forward the parameters to token recipient if any * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _param1 Parameter 1 for the token recipient * @param _param2 Parameter 2 for the token recipient * @param _param3 Parameter 3 for the token recipient */ function transferWithParams(address _to, uint256 _value, uint256 _param1, uint256 _param2, uint256 _param3) onlyPayloadSize(5 * 32) external returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); _invokeTokenRecipient(msg.sender, _to, _value, _param1, _param2, _param3); return true; } /** * @dev Hook for custom actions to be executed after transfer has completed * @param _from Transferred from * @param _to Transferred to * @param _value Value transferred */ function _postTransferHook(address _from, address _to, uint256 _value) internal { _invokeTokenRecipient(_from, _to, _value, 0, 0, 0); } } contract PresaleContract is Owned { ETToken public tokenContract; /// @dev Contract constructor function PresaleContract(address _tokenContract) public { tokenContract = ETToken(_tokenContract); } } contract ETCharPresale_v2 is PresaleContract { using SafeMath for uint; bool public enabled = true; uint32 public maxCharId = 10000; uint32 public currentCharId = 2000; uint256 public currentPrice = 0.02 ether; mapping (uint32 => address) public owners; mapping (address => uint32[]) public characters; bool public awardTokens = true; event Purchase(address from, uint32 charId, uint256 amount); function ETCharPresale_v2(address _presaleToken) PresaleContract(_presaleToken) public { } function _isContract(address _user) internal view returns (bool) { uint size; assembly { size := extcodesize(_user) } return size > 0; } function _provideChars(address _address, uint32 _number) internal { for (uint32 i = 0; i < _number; i++) { owners[currentCharId + i] = _address; characters[_address].push(currentCharId + i); emit Purchase(_address, currentCharId + i, currentPrice); } currentCharId += _number; currentPrice += priceIncrease() * _number; } function priceIncrease() public view returns (uint256) { uint256 _currentPrice = currentPrice; if (_currentPrice > 0.0425 ether) { return 0.00078125 finney; } else { return 0.028 finney; } } function() public payable { require(enabled); require(!_isContract(msg.sender)); require(msg.value >= currentPrice); uint32 chars = uint32(msg.value.div(currentPrice)); require(chars <= 100); if (chars > 50) { chars = 50; } require(currentCharId + chars - 1 <= maxCharId); uint256 purchaseValue = currentPrice.mul(chars); uint256 change = msg.value.sub(purchaseValue); _provideChars(msg.sender, chars); if (awardTokens) { tokenContract.rewardTokens(msg.sender, purchaseValue * 200); } if (currentCharId > maxCharId) { enabled = false; } if (change > 0) { msg.sender.transfer(change); } } function setEnabled(bool _enabled) public onlyOwner { enabled = _enabled; } function setMaxCharId(uint32 _maxCharId) public onlyOwner { maxCharId = _maxCharId; } function setCurrentPrice(uint256 _currentPrice) public onlyOwner { currentPrice = _currentPrice; } function setAwardTokens(bool _awardTokens) public onlyOwner { awardTokens = _awardTokens; } function withdraw() public onlyOwner { owner.transfer(address(this).balance); } function charactersOf(address _user) public view returns (uint32[]) { return characters[_user]; } function charactersCountOf(address _user) public view returns (uint256) { return characters[_user].length; } function getCharacter(address _user, uint256 _index) public view returns (uint32) { return characters[_user][_index]; } }
transfer token for a specified address _to The address to transfer to. _value The amount to be transferred./ SafeMath.sub will throw if there is not enough balance.
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); _postTransferHook(msg.sender, _to, _value); return true; }
1,759,763
./partial_match/1/0x39DC6a99209B5e6B81dC8540C86Ff10981ebDA29/sources/BatchDeposit.sol
Interface of the official Deposit contract from the ETH Foundation.
interface IDeposit { function deposit( bytes calldata pubkey, bytes calldata withdrawal_credentials, bytes calldata signature, bytes32 deposit_data_root ) external payable; }
4,041,770
./full_match/1/0xDbadeFb972132C82BE8601Fa7b9Ba4801262271d/sources/@exoda/contracts/token/ERC20/ERC20.sol
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) override public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; }
16,409,161
./full_match/1/0x4a7285cB7Ddcc9Ca37b152fac8B868411bC66bd1/sources/contracts/ponzai_test.sol
Overriding the ERC20 transferFrom function to include tax and maxTxAmount logic. Ensuring the transfer amount doesn't exceed maxTxAmount. Calling the internal _transferTokens function to handle tax and transfer. Decreasing the allowance by the transfer amount.
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { require(amount <= maxTxAmount, "Transfer amount exceeds maxTxAmount"); _transferTokens(sender, recipient, amount); uint256 currentAllowance = allowance(sender, _msgSender()); require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; }
2,897,775
pragma solidity ^0.4.22; // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address _owner, 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, uint256 _value) public returns (bool); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // ERC Token Standard #223 Interface // https://github.com/Dexaran/ERC223-token-standard/token/ERC223/ERC223_interface.sol // ---------------------------------------------------------------------------- contract ERC223Interface { uint public totalSupply; function transfer(address to, uint value, bytes data) public returns (bool success); event Transfer(address indexed from, address indexed to, uint value, bytes data); } /** * @title Owned * @dev To verify ownership */ contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } } /** * As part of the ERC223 standard we need to call the fallback of the token */ contract ContractReceiver { struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint _value, bytes _data) public pure { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); /* tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function * if data of token transaction is a function execution */ } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ 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 automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold 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 TimeVaultInterface is ERC20Interface, ERC223Interface { function timeVault(address who) public constant returns (uint); function getNow() public constant returns (uint); function transferByOwner(address to, uint _value, uint timevault) public returns (bool); } /** * All meta information for the Token must be defined here so that it can be accessed from both sides of proxy */ contract ELTTokenType { uint public decimals; uint public totalSupply; mapping(address => uint) balances; mapping(address => uint) timevault; mapping(address => mapping(address => uint)) allowed; // Token release switch bool public released; // The date before the release must be finalized (a unix timestamp) uint public globalTimeVault; event Transfer(address indexed from, address indexed to, uint tokens); } contract ERC20Token is ERC20Interface, ERC223Interface, ELTTokenType { using SafeMath for uint; function transfer(address _to, uint _value) public returns (bool success) { bytes memory empty; return transfer(_to, _value, empty); } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data) public returns (bool success) { if (isContract(_to)) { return transferToContract(_to, _value, _data, false); } else { return transferToAddress(_to, _value, _data, false); } } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * */ function approve(address _spender, uint _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 uint specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } 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, bool withAllowance) private returns (bool success) { transferIfRequirementsMet(msg.sender, _to, _value, withAllowance); emit Transfer(msg.sender, _to, _value, _data); return true; } //function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data, bool withAllowance) private returns (bool success) { transferIfRequirementsMet(msg.sender, _to, _value, withAllowance); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); emit Transfer(msg.sender, _to, _value, _data); return true; } // Function to verify that all the requirements to transfer are satisfied // The destination is not the null address // The tokens have been released for sale // The sender's tokens are not locked in a timevault function checkTransferRequirements(address _to, uint _value) private view { require(_to != address(0)); require(released == true); require(now > globalTimeVault); if (timevault[msg.sender] != 0) { require(now > timevault[msg.sender]); } require(balanceOf(msg.sender) >= _value); } // Do the transfer if the requirements are met function transferIfRequirementsMet(address _from, address _to, uint _value, bool withAllowances) private { checkTransferRequirements(_to, _value); if ( withAllowances) { require (_value <= allowed[_from][msg.sender]); } balances[_from] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); } // Transfer from one address to another taking into account ERC223 condition to verify that the to address is a contract or not function transferFrom(address from, address to, uint value) public returns (bool) { bytes memory empty; if (isContract(to)) { return transferToContract(to, value, empty, true); } else { return transferToAddress(to, value, empty, true); } allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); return true; } } contract TimeVaultToken is owned, TimeVaultInterface, ERC20Token { function transferByOwner(address to, uint value, uint earliestReTransferTime) onlyOwner public returns (bool) { transfer(to, value); timevault[to] = earliestReTransferTime; return true; } function timeVault(address owner) public constant returns (uint earliestTransferTime) { return timevault[owner]; } function getNow() public constant returns (uint blockchainTimeNow) { return now; } } contract StandardToken is TimeVaultToken { /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract StandardTokenExt is StandardToken { /* Interface declaration */ function isToken() public pure returns (bool weAre) { return true; } } contract OwnershipTransferrable is TimeVaultToken { event OwnershipTransferred(address indexed _from, address indexed _to); function transferOwnership(address newOwner) onlyOwner public { transferByOwner(newOwner, balanceOf(newOwner), 0); owner = newOwner; emit OwnershipTransferred(msg.sender, newOwner); } } contract VersionedToken is owned { address public upgradableContractAddress; /** * Constructor: * initialVersion - the address of the initial version of the implementation for the contract * * Note that this implementation must be visible to the relay contact even though it will not be a subclass * do this by importing the main contract that implements it. If the code is not visible it will not * always be accessible through the delegatecall() function. And even if it is, it will take an unlimited amount * of gas to process the call. * * In our case this it is ELTTokenImpl.sol * e.g. * import "ELTToken.sol" * * Please note: IMPORTANT * do not implement any function called "update()" otherwise it will break the Versioning system */ function VersionedToken(address initialImplementation) public { upgradableContractAddress = initialImplementation; } /** * update * Call to upgrade the implementation version of this constract * newVersion: this is the address of the new implementation for the contract */ function upgradeToken(address newImplementation) onlyOwner public { upgradableContractAddress = newImplementation; } /** * This is the fallback function that is called whenever a contract is called but can't find the called function. * In this case we delegate the call to the implementing contract ELTTokenImpl * * Instead of using delegatecall() in Solidity we use the assembly because it allows us to return values to the caller */ function() public { address upgradableContractMem = upgradableContractAddress; bytes memory functionCall = msg.data; assembly { // Load the first 32 bytes of the functionCall bytes array which represents the size of the bytes array let functionCallSize := mload(functionCall) // Calculate functionCallDataAddress which starts at the second 32 byte block in the functionCall bytes array let functionCallDataAddress := add(functionCall, 0x20) // delegatecall(gasAllowed, callAddress, inMemAddress, inSizeBytes, outMemAddress, outSizeBytes) returns/pushes to stack (1 on success, 0 on failure) let functionCallResult := delegatecall(gas, upgradableContractMem, functionCallDataAddress, functionCallSize, 0, 0) let freeMemAddress := mload(0x40) switch functionCallResult case 0 { // revert(fromMemAddress, sizeInBytes) ends execution and returns value revert(freeMemAddress, 0) } default { // returndatacopy(toMemAddress, fromMemAddress, sizeInBytes) returndatacopy(freeMemAddress, 0x0, returndatasize) // return(fromMemAddress, sizeInBytes) return (freeMemAddress, returndatasize) } } } } contract ELTToken is VersionedToken, ELTTokenType { string public name; string public symbol; function ELTToken(address _tokenOwner, string _tokenName, string _tokenSymbol, uint _totalSupply, uint _decimals, uint _globalTimeVaultOpeningTime, address _initialImplementation) VersionedToken(_initialImplementation) public { name = _tokenName; symbol = _tokenSymbol; decimals = _decimals; totalSupply = _totalSupply * 10 ** uint(decimals); // Allocate initial balance to the owner balances[_tokenOwner] = totalSupply; emit Transfer(address(0), owner, totalSupply); globalTimeVault = _globalTimeVaultOpeningTime; released = false; } } contract ELTTokenImpl is StandardTokenExt { /** Name and symbol were updated. */ event UpdatedTokenInformation(string newName, string newSymbol); string public name; string public symbol; bool private adminReturnStatus ; /** * One way function to perform the final token release. */ function releaseTokenTransfer(bool _value) onlyOwner public { released = _value; } function setGlobalTimeVault(uint _globalTimeVaultOpeningTime) onlyOwner public { globalTimeVault = _globalTimeVaultOpeningTime; } function admin(string functionName, string p1, string p2, string p3) onlyOwner public returns (bool result) { // Use parameters to remove warning adminReturnStatus = (bytes(functionName).length + bytes(p1).length + bytes(p2).length + bytes(p3).length) != 0; return adminReturnStatus ; } /** * Owner can update token information here. * * It is often useful to conceal the actual token association, until * the token operations, like central issuance or reissuance have been completed. * In this case the initial token can be supplied with empty name and symbol information. * * This function allows the token owner to rename the token after the operations * have been completed and then point the audience to use the token contract. */ function setTokenInformation(string _tokenName, string _tokenSymbol) onlyOwner public { name = _tokenName; symbol = _tokenSymbol; emit UpdatedTokenInformation(name, symbol); } }
function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data, bool withAllowance) private returns (bool success) { transferIfRequirementsMet(msg.sender, _to, _value, withAllowance); emit Transfer(msg.sender, _to, _value, _data); return true; }
5,436,314
/** *Submitted for verification at Etherscan.io on 2021-03-11 */ pragma solidity =0.6.6; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // 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'); } } // DebunkswapLibrary library DebunkswapV1Library { using SafeMath for uint; // 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, 'DebunkswapV1Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'DebunkswapV1Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'2bb5dc7a385ed5bf1bb9acec54f4ca97963f5b87ace3902a12adb962155a9ecb' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IDebunkswapV1Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'DebunkswapV1Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'DebunkswapV1Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'DebunkswapV1Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'DebunkswapV1Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'DebunkswapV1Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'DebunkswapV1Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'DebunkswapV1Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'DebunkswapV1Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // IERC20 Contract Interface interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } // WETH Interface interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // Debunkswap Factory Contract Interface interface IDebunkswapV1Factory { 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; } // Debunkswap Pair Contract Interface interface IDebunkswapV1Pair { 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; } // Debunkswap Router01 Contract Interface interface IDebunkswapV1Router01 { 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); } interface IDebunkswapV1Router02 is IDebunkswapV1Router01 { 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; } // Debunkswap Router02 Contract contract DebunkswapV1Router02 is IDebunkswapV1Router02 { using SafeMath for uint; address public immutable override factory; address public immutable override WETH; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'DebunkswapV1Router: EXPIRED'); _; } constructor(address _factory, address _WETH) public { factory = _factory; WETH = _WETH; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { // create the pair if it doesn't exist yet if (IDebunkswapV1Factory(factory).getPair(tokenA, tokenB) == address(0)) { IDebunkswapV1Factory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = DebunkswapV1Library.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = DebunkswapV1Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'DebunkswapV1Router: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = DebunkswapV1Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'DebunkswapV1Router: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = DebunkswapV1Library.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = IDebunkswapV1Pair(pair).mint(to); } function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = DebunkswapV1Library.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = IDebunkswapV1Pair(pair).mint(to); // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { address pair = DebunkswapV1Library.pairFor(factory, tokenA, tokenB); IDebunkswapV1Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = IDebunkswapV1Pair(pair).burn(to); (address token0,) = DebunkswapV1Library.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'DebunkswapV1Router: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'DebunkswapV1Router: INSUFFICIENT_B_AMOUNT'); } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, 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 virtual override returns (uint amountA, uint amountB) { address pair = DebunkswapV1Library.pairFor(factory, tokenA, tokenB); uint value = approveMax ? uint(-1) : liquidity; IDebunkswapV1Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountToken, uint amountETH) { address pair = DebunkswapV1Library.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IDebunkswapV1Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this))); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountETH) { address pair = DebunkswapV1Library.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IDebunkswapV1Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = DebunkswapV1Library.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? DebunkswapV1Library.pairFor(factory, output, path[i + 2]) : _to; IDebunkswapV1Pair(DebunkswapV1Library.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = DebunkswapV1Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'DebunkswapV1Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, DebunkswapV1Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = DebunkswapV1Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'DebunkswapV1Router: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, DebunkswapV1Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'DebunkswapV1Router: INVALID_PATH'); amounts = DebunkswapV1Library.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'DebunkswapV1Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(DebunkswapV1Library.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'DebunkswapV1Router: INVALID_PATH'); amounts = DebunkswapV1Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'DebunkswapV1Router: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, DebunkswapV1Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'DebunkswapV1Router: INVALID_PATH'); amounts = DebunkswapV1Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'DebunkswapV1Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, DebunkswapV1Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'DebunkswapV1Router: INVALID_PATH'); amounts = DebunkswapV1Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, 'DebunkswapV1Router: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(DebunkswapV1Library.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = DebunkswapV1Library.sortTokens(input, output); IDebunkswapV1Pair pair = IDebunkswapV1Pair(DebunkswapV1Library.pairFor(factory, input, output)); uint amountInput; uint amountOutput; { // scope to avoid stack too deep errors (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = DebunkswapV1Library.getAmountOut(amountInput, reserveInput, reserveOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? DebunkswapV1Library.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { TransferHelper.safeTransferFrom( path[0], msg.sender, DebunkswapV1Library.pairFor(factory, path[0], path[1]), amountIn ); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'DebunkswapV1Router: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override payable ensure(deadline) { require(path[0] == WETH, 'DebunkswapV1Router: INVALID_PATH'); uint amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(DebunkswapV1Library.pairFor(factory, path[0], path[1]), amountIn)); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'DebunkswapV1Router: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { require(path[path.length - 1] == WETH, 'DebunkswapV1Router: INVALID_PATH'); TransferHelper.safeTransferFrom( path[0], msg.sender, DebunkswapV1Library.pairFor(factory, path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint amountOut = IERC20(WETH).balanceOf(address(this)); require(amountOut >= amountOutMin, 'DebunkswapV1Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return DebunkswapV1Library.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountOut) { return DebunkswapV1Library.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountIn) { return DebunkswapV1Library.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint amountIn, address[] memory path) public view virtual override returns (uint[] memory amounts) { return DebunkswapV1Library.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view virtual override returns (uint[] memory amounts) { return DebunkswapV1Library.getAmountsIn(factory, amountOut, path); } }
ADD LIQUIDITY create the pair if it doesn't exist yet
function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { if (IDebunkswapV1Factory(factory).getPair(tokenA, tokenB) == address(0)) { IDebunkswapV1Factory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = DebunkswapV1Library.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); uint amountBOptimal = DebunkswapV1Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'DebunkswapV1Router: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); uint amountAOptimal = DebunkswapV1Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'DebunkswapV1Router: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } }
15,089,680
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; abstract contract ChainClaim is EIP712 { error ErrorUsedClaim(); error ErrorInvalidIssuerSignature(); error ErrorInvalidClaimantSignature(); bytes32 private immutable _CHAIN_CLAIM_TYPEHASH = keccak256("Claim(address chainedAddress)"); address public immutable ISSUER; mapping(address => bool) public usedClaims; /// @notice On chain generation for a valid EIP-712 hash /// @param _issuer the address that must match the signing /// private key for all claim codes /// @param name EIP712 name constructor(address _issuer, string memory name) EIP712(name, "1") { ISSUER = _issuer; } /// @notice On chain generation for a valid EIP-712 hash /// @param chainedAddress the address that has been signed /// @return The typed data hash function genDataHash(address chainedAddress) internal view returns (bytes32) { bytes32 structHash = keccak256( abi.encode(_CHAIN_CLAIM_TYPEHASH, chainedAddress) ); return _hashTypedDataV4(structHash); } /// @notice First of two signature validations, signer must match ISSUER /// @param issuedAddress the address that has been signed, /// this address must match the claim code private key /// @param v split signature v /// @param r split signature r /// @param s split signature s /// @return True if signature is valid and signer matches issuer function isValidIssuerSig( address issuedAddress, uint8 v, bytes32 r, bytes32 s ) internal view returns (bool) { bytes32 hash = genDataHash(issuedAddress); address signer = ECDSA.recover(hash, v, r, s); return signer == ISSUER; } /// @notice Second of two signature validations, signer must match /// issued address from the first signature validation /// @param issuedAddress address that much match the signer address /// @param destinationAddress the address that has been signed, /// this is the final address for whatever can be claimed, can be msg.sender /// @param v split signature v /// @param r split signature r /// @param s split signature s /// @return True if signature is valid and signer matches issuedAddress function isValidClaimantSig( address issuedAddress, address destinationAddress, uint8 v, bytes32 r, bytes32 s ) internal view returns (bool) { bytes32 hash = genDataHash(destinationAddress); address signer = ECDSA.recover(hash, v, r, s); return signer == issuedAddress; } /// @notice Validates the chain of two signatures the first is an adddress /// signed by the issuer. The second is a final address signed by a one /// time use private key before sending the transaction. The final address /// should be the destination address for whatever is being claimed /// @param issuedAddress address that has been signed by issuer /// @param destinationAddress address that has been signed by claimant /// this is the final address for whatever can be claimed, can be msg.sender /// @param v array of split signature v /// @param r array of split signature r /// @param s array of split signature s /// @return True if signature chain is valid function claim( address issuedAddress, address destinationAddress, uint8[2] memory v, bytes32[2] memory r, bytes32[2] memory s ) internal returns (bool) { if (usedClaims[issuedAddress]) { revert ErrorUsedClaim(); } if (!isValidIssuerSig(issuedAddress, v[0], r[0], s[0])) revert ErrorInvalidIssuerSignature(); if ( !isValidClaimantSig(issuedAddress, destinationAddress, v[1], r[1], s[1]) ) revert ErrorInvalidClaimantSignature(); usedClaims[issuedAddress] = true; return true; } }
On chain generation for a valid EIP-712 hash chainedAddress the address that has been signed return The typed data hash
function genDataHash(address chainedAddress) internal view returns (bytes32) { bytes32 structHash = keccak256( abi.encode(_CHAIN_CLAIM_TYPEHASH, chainedAddress) ); return _hashTypedDataV4(structHash); }
923,633
pragma solidity ^0.4.23; // Copyright 2018 OpenST Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ---------------------------------------------------------------------------- // Auxiliary Chain: CoGateway Contract // // http://www.simpletoken.org/ // // ---------------------------------------------------------------------------- /* Origin chain | Auxiliary chain ------------------------------------------------------------------------------- EIP20Gateway - - - - - - - - - - -EIP20CoGateway ------------------------------------------------------------------------------- 1. Redeem and Unstake: Normal flow confirmRedemptionIntent <--- redeem | progressUnstake (HL) ---> progressRedemption (HL) ------------------------------------------------------------------------------- 2. Redeem and Unstake (Revert): Normal flow confirmRedemptionIntent <--- redeem | RevertRedemptionIntentConfirmed ---> revertRedemption | progressRevertRedemption ---> progressRevertRedemption ------------------------------------------------------------------------------- 3. Redeem and Unstake: Incase the facilitator is not able to progress confirmRedemptionIntent <--- redeem (by facilitator) (by facilitator) | facilitator (offline) | progressUnstakeWithProof <--- progressRedemptionWithProof ------------------------------------------------------------------------------- */ import "./CoGateway.sol"; /** * @title EIP20CoGateway Contract * * @notice EIP20CoGateway act as medium to send messages from auxiliary * chain to origin chain. Currently CoGateway supports redeem and * unstake, redeem and unstake, revert redeem message & linking of * gateway and cogateway. */ contract EIP20CoGateway is CoGateway { /* Events */ /** Emitted whenever a staking intent is confirmed. */ event StakingIntentConfirmed( bytes32 indexed _messageHash, address _staker, uint256 _stakerNonce, address _beneficiary, uint256 _amount, uint256 _blockHeight, bytes32 _hashLock ); /** Emitted whenever a utility tokens are minted. */ event ProgressedMint( bytes32 indexed _messageHash, address _staker, address _beneficiary, uint256 _stakeAmount, uint256 _mintedAmount, uint256 _rewardAmount, bool _proofProgress, bytes32 _unlockSecret ); /** Emitted whenever revert staking intent is confirmed. */ event RevertStakingIntentConfirmed( bytes32 indexed _messageHash, address _staker, uint256 _stakerNonce, uint256 _amount ); /** Emitted whenever a staking intent is reverted. */ event RevertStakeProgressed( bytes32 indexed _messageHash, address _staker, uint256 _stakerNonce, uint256 _amount ); /** Emitted whenever redemption is initiated. */ event RedemptionIntentDeclared( bytes32 indexed _messageHash, address _redeemer, uint256 _redeemerNonce, address _beneficiary, uint256 _amount ); /** Emitted whenever redemption is completed. */ event ProgressedRedemption( bytes32 indexed _messageHash, address _redeemer, uint256 _redeemerNonce, uint256 _amount, bool _proofProgress, bytes32 _unlockSecret ); /** Emitted whenever revert redemption is initiated. */ event RevertRedemptionDeclared( bytes32 indexed _messageHash, address _redeemer, uint256 _redeemerNonce, uint256 _amount ); /** Emitted whenever revert redemption is complete. */ event RevertedRedemption( bytes32 indexed _messageHash, address _redeemer, uint256 _redeemerNonce, uint256 _amount ); /* Struct */ /** * Redeem stores the redemption information about the redeem amount, * beneficiary address, message data and facilitator address. */ struct Redeem { /** Amount that will be redeemed. */ uint256 amount; /** * Address where the value tokens will be unstaked in the * origin chain. */ address beneficiary; /** Address of the facilitator that initiates the staking process. */ address facilitator; //todo need to discuss revocation process /** bounty amount kept by facilitator for transferring redeem messages*/ uint256 bounty; } /** * Mint stores the minting information * like mint amount, beneficiary address, message data. */ struct Mint { /** Amount that will be minted. */ uint256 amount; /** Address for which the utility tokens will be minted */ address beneficiary; } /* public variables */ /** Maps messageHash to the Mint object. */ mapping(bytes32 /*messageHash*/ => Mint) mints; /** Maps messageHash to the Redeem object. */ mapping(bytes32/*messageHash*/ => Redeem) redeems; /* Constructor */ /** * @notice Initialise the contract by providing the Gateway contract * address for which the CoGateway will enable facilitation of * minting and redeeming. * * @param _valueToken The value token contract address. * @param _utilityToken The utility token address that will be used for * minting the utility token. * @param _core Core contract address. * @param _bounty The amount that facilitator will stakes to initiate the * staking process. * @param _organisation Organisation address. * @param _gateway Gateway contract address. * @param _messageBus Message bus contract address. */ constructor( address _valueToken, address _utilityToken, CoreInterface _core, uint256 _bounty, address _organisation, address _gateway, address _messageBus ) CoGateway( _valueToken, _utilityToken, _core, _bounty, _organisation, _gateway, _messageBus ) public { } /* External functions */ /** * @notice Confirms the initiation of the stake process. * * @param _staker Staker address. * @param _stakerNonce Nonce of the staker address. * @param _beneficiary The address in the auxiliary chain where the utility * tokens will be minted. * @param _amount Amount of utility token will be minted. * @param _gasPrice Gas price that staker is ready to pay to get the stake * and mint process done * @param _gasLimit Gas limit that staker is ready to pay * @param _hashLock Hash Lock provided by the facilitator. * @param _blockHeight Block number for which the proof is valid * @param _rlpParentNodes RLP encoded parent node data to prove in * messageBox outbox of Gateway * * @return messageHash_ which is unique for each request. */ function confirmStakingIntent( address _staker, uint256 _stakerNonce, address _beneficiary, uint256 _amount, uint256 _gasPrice, uint256 _gasLimit, bytes32 _hashLock, uint256 _blockHeight, bytes memory _rlpParentNodes ) public returns (bytes32 messageHash_) { // Get the initial gas amount uint256 initialGas = gasleft(); require( _staker != address(0), "Staker address must not be zero" ); require( _beneficiary != address(0), "Beneficiary address must not be zero" ); require( _amount != 0, "Mint amount must not be zero" ); require( _gasPrice != 0, "Gas price must not be zero" ); require( _gasLimit != 0, "Gas limit must not be zero" ); require( _rlpParentNodes.length != 0, "RLP parent nodes must not be zero" ); // Get the staking intent hash bytes32 intentHash = hashStakingIntent( _amount, _beneficiary, _staker, _stakerNonce, _gasPrice, _gasLimit ); // Get the messageHash messageHash_ = MessageBus.messageDigest( STAKE_TYPEHASH, intentHash, _stakerNonce, _gasPrice, _gasLimit ); registerInboxProcess( _staker, _stakerNonce, messageHash_ ); // Create new mint object mints[messageHash_] = Mint({ amount : _amount, beneficiary : _beneficiary }); // create new message object messages[messageHash_] = getMessage( _staker, _stakerNonce, _gasPrice, _gasLimit, intentHash, _hashLock); // execute the confirm staking intent. This is done in separate // function to avoid stack too deep error executeConfirmStakingIntent( messages[messageHash_], _blockHeight, _rlpParentNodes ); // Emit StakingIntentConfirmed event emit StakingIntentConfirmed( messageHash_, _staker, _stakerNonce, _beneficiary, _amount, _blockHeight, _hashLock ); // Update the gas consumed for this function. messages[messageHash_].gasConsumed = initialGas.sub(gasleft()); } /** * @notice Complete minting process by minting the utility tokens * * @param _messageHash Message hash. * @param _unlockSecret Unlock secret for the hashLock provide by the * facilitator while initiating the stake * * @return beneficiary_ Address to which the utility tokens will be * transferred after minting * @return stakeAmount_ Total amount for which the staking was * initiated. The reward amount is deducted from the * this amount and is given to the facilitator. * @return mintedAmount_ Actual minted amount, after deducting the reward * from the total (stake) amount. * @return rewardAmount_ Reward amount that is transferred to facilitator */ function progressMinting( bytes32 _messageHash, bytes32 _unlockSecret ) external returns ( address beneficiary_, uint256 stakeAmount_, uint256 mintedAmount_, uint256 rewardAmount_ ) { // Get the initial gas amount uint256 initialGas = gasleft(); require( _messageHash != bytes32(0), "Message hash must not be zero" ); MessageBus.Message storage message = messages[_messageHash]; // Progress inbox MessageBus.progressInbox( messageBox, STAKE_TYPEHASH, message, _unlockSecret ); (beneficiary_, stakeAmount_, mintedAmount_, rewardAmount_) = progressMintingInternal(_messageHash, initialGas, true, bytes32(0)); } /** * @notice Completes the minting process by providing the merkle proof * instead of unlockSecret. In case the facilitator process is not * able to complete the stake and minting process then this is an * alternative approach to complete the process * * @dev This can be called to prove that the outbox status of messageBox on * Gateway is either declared or progressed. * * @param _messageHash Message hash. * @param _rlpEncodedParentNodes RLP encoded parent node data to prove in * messageBox inbox of Gateway * @param _blockHeight Block number for which the proof is valid * @param _messageStatus Message status i.e. Declared or Progressed that * will be proved. * * @return beneficiary_ Address to which the utility tokens will be * transferred after minting * @return stakeAmount_ Total amount for which the stake was initiated. The * reward amount is deducted from the total amount and * is given to the facilitator. * @return mintedAmount_ Actual minted amount, after deducting the reward * from the total amount. * @return rewardAmount_ Reward amount that is transferred to facilitator */ function progressMintingWithProof( bytes32 _messageHash, bytes _rlpEncodedParentNodes, uint256 _blockHeight, uint256 _messageStatus ) public returns ( address beneficiary_, uint256 stakeAmount_, uint256 mintedAmount_, uint256 rewardAmount_ ) { // Get the inital gas uint256 initialGas = gasleft(); require( _messageHash != bytes32(0), "Message hash must not be zero" ); require( _rlpEncodedParentNodes.length > 0, "RLP encoded parent nodes must not be zero" ); // Get the storage root for the given block height bytes32 storageRoot = storageRoots[_blockHeight]; require( storageRoot != bytes32(0), "Storage root must not be zero" ); MessageBus.Message storage message = messages[_messageHash]; MessageBus.progressInboxWithProof( messageBox, STAKE_TYPEHASH, message, _rlpEncodedParentNodes, MESSAGE_BOX_OFFSET, storageRoot, MessageBus.MessageStatus(_messageStatus) ); (beneficiary_, stakeAmount_, mintedAmount_, rewardAmount_) = progressMintingInternal(_messageHash, initialGas, true, bytes32(0)); } /** * @notice Declare staking revert intent. This will set message status to * revoked. This method will also clear mint mapping storage. * * @param _messageHash Message hash. * @param _blockHeight Block number for which the proof is valid * @param _rlpEncodedParentNodes RLP encoded parent node data to prove * DeclaredRevocation in messageBox outbox * of Gateway * * @return staker_ Staker address * @return stakerNonce_ Staker nonce * @return amount_ Redeem amount */ function confirmRevertStakingIntent( bytes32 _messageHash, uint256 _blockHeight, bytes _rlpEncodedParentNodes ) external returns ( address staker_, uint256 stakerNonce_, uint256 amount_ ) { // Get the initial gas value uint256 initialGas = gasleft(); require( _messageHash != bytes32(0), "Message hash must not be zero" ); require( _rlpEncodedParentNodes.length > 0, "RLP encoded parent nodes must not be zero" ); MessageBus.Message storage message = messages[_messageHash]; require( message.intentHash != bytes32(0), "RevertRedemption intent hash must not be zero" ); // Get the storage root bytes32 storageRoot = storageRoots[_blockHeight]; require( storageRoot != bytes32(0), "Storage root must not be zero" ); // Confirm revocation MessageBus.confirmRevocation( messageBox, STAKE_TYPEHASH, message, _rlpEncodedParentNodes, MESSAGE_BOX_OFFSET, storageRoot ); Mint storage mint = mints[_messageHash]; staker_ = message.sender; stakerNonce_ = message.nonce; amount_ = mint.amount; // delete the mint data delete mints[_messageHash]; // Emit RevertStakingIntentConfirmed event emit RevertStakingIntentConfirmed( _messageHash, message.sender, message.nonce, mint.amount ); // Update the gas consumed for this function. message.gasConsumed = initialGas.sub(gasleft()); } /** * @notice Initiates the redemption process. * * @dev In order to redeem the redeemer needs to approve CoGateway contract * for redeem amount. Redeem amount is transferred from redeemer * address to CoGateway contract. * This is a payable function. The bounty is transferred in base token * Redeemer is always msg.sender * * @param _amount Redeem amount that will be transferred form redeemer * account. * @param _beneficiary The address in the origin chain where the value * tok ens will be released. * @param _facilitator Facilitator address. * @param _gasPrice Gas price that redeemer is ready to pay to get the * redemption process done. * @param _gasLimit Gas limit that redeemer is ready to pay * @param _nonce Nonce of the redeemer address. * @param _hashLock Hash Lock provided by the facilitator. * * @return messageHash_ which is unique for each request. */ function redeem( uint256 _amount, address _beneficiary, address _facilitator, uint256 _gasPrice, uint256 _gasLimit, uint256 _nonce, bytes32 _hashLock ) public payable isActive returns (bytes32 messageHash_) { require( msg.value == bounty, "msg.value must match the bounty amount" ); require( _amount > uint256(0), "Redeem amount must not be zero" ); require( _facilitator != address(0), "Facilitator address must not be zero" ); require( _gasPrice != 0, "Gas price must not be zero" ); require( _gasLimit != 0, "Gas limit must not be zero" ); // Get the redemption intent hash bytes32 intentHash = GatewayLib.hashRedemptionIntent( _amount, _beneficiary, msg.sender, _nonce, _gasPrice, _gasLimit, valueToken ); // Get the messageHash messageHash_ = MessageBus.messageDigest( REDEEM_TYPEHASH, intentHash, _nonce, _gasPrice, _gasLimit ); // Get previousMessageHash bytes32 previousMessageHash = registerOutboxProcess( msg.sender, _nonce, messageHash_ ); // Delete the previous progressed/revoked redeem data delete redeems[previousMessageHash]; redeems[messageHash_] = Redeem({ amount : _amount, beneficiary : _beneficiary, facilitator : _facilitator, bounty : bounty }); // create message object messages[messageHash_] = getMessage( msg.sender, _nonce, _gasPrice, _gasLimit, intentHash, _hashLock ); require( messageBox.outbox[messageHash_] == MessageBus.MessageStatus.Undeclared, "Message status must be Undeclared" ); // Update the message outbox status to declared. messageBox.outbox[messageHash_] = MessageBus.MessageStatus.Declared; //transfer redeem amount to Co-Gateway EIP20Interface(utilityToken).transferFrom( msg.sender, address(this), _amount ); // Emit RedemptionIntentDeclared event emit RedemptionIntentDeclared( messageHash_, msg.sender, _nonce, _beneficiary, _amount ); } /** * @notice Completes the redemption process. * * @param _messageHash Message hash. * @param _unlockSecret Unlock secret for the hashLock provide by the * facilitator while initiating the redeem * * @return redeemer_ Redeemer address * @return redeemAmount_ Redeem amount */ function progressRedemption( bytes32 _messageHash, bytes32 _unlockSecret ) external returns ( address redeemer_, uint256 redeemAmount_ ) { require( _messageHash != bytes32(0), "Message hash must not be zero" ); // Get the message object MessageBus.Message storage message = messages[_messageHash]; // Get the redeemer address redeemer_ = message.sender; // Get the redeem amount redeemAmount_ = redeems[_messageHash].amount; // Progress outbox MessageBus.progressOutbox( messageBox, REDEEM_TYPEHASH, message, _unlockSecret ); (redeemer_, redeemAmount_) = progressRedemptionInternal(_messageHash, false, _unlockSecret); } /** * @notice Completes the redemption process by providing the merkle proof * instead of unlockSecret. In case the facilitator process is not * able to complete the redeem and unstake process then this is an * alternative approach to complete the process * * @dev This can be called to prove that the inbox status of messageBox on * Gateway is either declared or progressed. * * @param _messageHash Message hash. * @param _rlpEncodedParentNodes RLP encoded parent node data to prove in * messageBox outbox of Gateway * @param _blockHeight Block number for which the proof is valid * @param _messageStatus Message status i.e. Declared or Progressed that * will be proved. * * @return redeemer_ Redeemer address * @return redeemAmount_ Redeem amount */ function progressRedemptionWithProof( bytes32 _messageHash, bytes _rlpEncodedParentNodes, uint256 _blockHeight, uint256 _messageStatus ) external returns ( address redeemer_, uint256 redeemAmount_ ) { require( _messageHash != bytes32(0), "Message hash must not be zero" ); require( _rlpEncodedParentNodes.length > 0, "RLP encoded parent nodes must not be zero" ); bytes32 storageRoot = storageRoots[_blockHeight]; require( storageRoot != bytes32(0), "Storage root must not be zero" ); MessageBus.Message storage message = messages[_messageHash]; redeemer_ = message.sender; redeemAmount_ = redeems[_messageHash].amount; MessageBus.progressOutboxWithProof( messageBox, REDEEM_TYPEHASH, message, _rlpEncodedParentNodes, MESSAGE_BOX_OFFSET, storageRoot, MessageBus.MessageStatus(_messageStatus) ); (redeemer_, redeemAmount_) = progressRedemptionInternal(_messageHash, true, bytes32(0)); } /** * @notice Revert redemption to stop the redeem process. Only redeemer can * revert redemption by providing penalty i.e. 1.5 times of * bounty amount. On revert process, penalty and facilitator * bounty will be burned. * * @param _messageHash Message hash. * * @return redeemer_ Redeemer address * @return redeemerNonce_ Redeemer nonce * @return amount_ Redeem amount */ function revertRedemption( bytes32 _messageHash ) payable external returns ( address redeemer_, uint256 redeemerNonce_, uint256 amount_ ) { require( _messageHash != bytes32(0), "Message hash must not be zero" ); // get the message object for the _messageHash MessageBus.Message storage message = messages[_messageHash]; require(message.intentHash != bytes32(0)); require( message.intentHash != bytes32(0), "RedemptionIntentHash must not be zero" ); require( message.sender == msg.sender, "Only redeemer can revert redemption." ); //penalty charged to redeemer uint256 penalty = redeems[_messageHash].bounty .mul(REVOCATION_PENALTY) .div(100); require( msg.value == penalty, "msg.value must match the penalty amount" ); require( messageBox.outbox[_messageHash] == MessageBus.MessageStatus.Undeclared, "Message status must be Undeclared" ); // Update the message outbox status to declared. messageBox.outbox[_messageHash] = MessageBus.MessageStatus.DeclaredRevocation; redeemer_ = message.sender; redeemerNonce_ = message.nonce; amount_ = redeems[_messageHash].amount; // Emit RevertRedemptionDeclared event. emit RevertRedemptionDeclared( _messageHash, redeemer_, redeemerNonce_, amount_ ); } /** * @notice Complete revert redemption by providing the merkle proof. * It will burn facilitator bounty and redeemer penalty. * * @param _messageHash Message hash. * @param _blockHeight Block number for which the proof is valid * @param _rlpEncodedParentNodes RLP encoded parent node data to prove * DeclaredRevocation in messageBox inbox * of Gateway * * @return redeemer_ Redeemer address * @return redeemerNonce_ Redeemer nonce * @return amount_ Redeem amount */ function progressRevertRedemption( bytes32 _messageHash, uint256 _blockHeight, bytes _rlpEncodedParentNodes ) external returns ( address redeemer_, uint256 redeemerNonce_, uint256 amount_ ) { require( _messageHash != bytes32(0), "Message hash must not be zero" ); require( _rlpEncodedParentNodes.length > 0, "RLP encoded parent nodes must not be zero" ); // Get the message object MessageBus.Message storage message = messages[_messageHash]; require( message.intentHash != bytes32(0), "StakingIntentHash must not be zero" ); // Get the storageRoot for the given block height bytes32 storageRoot = storageRoots[_blockHeight]; require( storageRoot != bytes32(0), "Storage root must not be zero" ); // Progress with revocation message MessageBus.progressOutboxRevocation( messageBox, message, REDEEM_TYPEHASH, MESSAGE_BOX_OFFSET, _rlpEncodedParentNodes, storageRoot, MessageBus.MessageStatus.Revoked ); Redeem storage redeemProcess = redeems[_messageHash]; redeemer_ = message.sender; redeemerNonce_ = message.nonce; amount_ = redeemProcess.amount; // return the redeem amount back EIP20Interface(utilityToken).transfer(message.sender, amount_); // burn bounty address(0).transfer(redeemProcess.bounty); //penalty charged to redeemer uint256 penalty = redeemProcess.bounty .mul(REVOCATION_PENALTY) .div(100); //burn penalty address(0).transfer(penalty); // delete the redeem data delete redeems[_messageHash]; // Emit RevertedRedemption event emit RevertedRedemption( _messageHash, message.sender, message.nonce, redeemProcess.amount ); } /** * @notice Activate CoGateway contract. Can be set only by the * Organisation address * * @return `true` if value is set */ function activateCoGateway() external onlyOrganisation returns (bool) { require( deactivated == true, "Gateway is already active" ); deactivated = false; return true; } /** * @notice Deactivate CoGateway contract. Can be set only by the * Organisation address * * @return `true` if value is set */ function deactivateCoGateway() external onlyOrganisation returns (bool) { require( deactivated == false, "Gateway is already deactive" ); deactivated = true; return true; } /* private methods */ /** * @notice private function to execute confirm staking intent. * * @dev This function is to avoid stack too deep error in * confirmStakingIntent function * * @param _message message object * @param _blockHeight Block number for which the proof is valid * @param _rlpParentNodes RLP encoded parent nodes. * * @return `true` if executed successfully */ function executeConfirmStakingIntent( MessageBus.Message storage _message, uint256 _blockHeight, bytes _rlpParentNodes ) private returns (bool) { // Get storage root bytes32 storageRoot = storageRoots[_blockHeight]; require( storageRoot != bytes32(0), "Storage root must not be zero" ); // Confirm message MessageBus.confirmMessage( messageBox, STAKE_TYPEHASH, _message, _rlpParentNodes, MESSAGE_BOX_OFFSET, storageRoot ); return true; } /** * @notice private function to calculate staking intent hash. * * @dev This function is to avoid stack too deep error in * confirmStakingIntent function * * @param _amount staking amount * @param _beneficiary minting account * @param _staker staking account * @param _stakerNonce nounce of staker * @param _gasPrice price used for reward calculation * @param _gasLimit max limit for reward calculation * * @return bytes32 staking intent hash */ function hashStakingIntent( uint256 _amount, address _beneficiary, address _staker, uint256 _stakerNonce, uint256 _gasPrice, uint256 _gasLimit ) private view returns(bytes32) { return GatewayLib.hashStakingIntent( _amount, _beneficiary, _staker, _stakerNonce, _gasPrice, _gasLimit, valueToken ); } /** * @notice This is internal method for process meeting contains common logic. * * @param _messageHash Message hash. * @param _initialGas initial gas during progress process. * * @param _proofProgress true if progress with proof, false if progress * with hashlock. * @param _unlockSecret unlock secret to progress, zero in case of progress * with proof * * @return beneficiary_ Address to which the utility tokens will be * transferred after minting. * @return stakeAmount_ Total amount for which the stake was initiated. The * reward amount is deducted from the total amount and * is given to the facilitator. * @return mintedAmount_ Actual minted amount, after deducting the reward * from the total amount. * @return rewardAmount_ Reward amount that is transferred to facilitator */ function progressMintingInternal( bytes32 _messageHash, uint256 _initialGas, bool _proofProgress, bytes32 _unlockSecret ) private returns ( address beneficiary_, uint256 stakeAmount_, uint256 mintedAmount_, uint256 rewardAmount_ ) { Mint storage mint = mints[_messageHash]; MessageBus.Message storage message = messages[_messageHash]; beneficiary_ = mint.beneficiary; stakeAmount_ = mint.amount; //TODO: Remove the hardcoded 50000. Discuss and implement it properly (rewardAmount_, message.gasConsumed) = GatewayLib.feeAmount( message.gasConsumed, message.gasLimit, message.gasPrice, _initialGas, 50000 //21000 * 2 for transactions + approx buffer ); mintedAmount_ = stakeAmount_.sub(rewardAmount_); //Mint token after subtracting reward amount UtilityTokenInterface(utilityToken).mint(beneficiary_, mintedAmount_); //reward beneficiary with the reward amount UtilityTokenInterface(utilityToken).mint(msg.sender, rewardAmount_); // delete the mint data delete mints[_messageHash]; // Emit ProgressedMint event emit ProgressedMint( _messageHash, message.sender, mint.beneficiary, stakeAmount_, mintedAmount_, rewardAmount_, _proofProgress, _unlockSecret ); } /** * @notice Internal method to progressRedemptionInternal. * * @param _messageHash Message hash. * @param _proofProgress true if progress with proof, false if progress * with hashlock. * @param _unlockSecret unlock secret to progress, zero in case of progress * with proof * * @return redeemer_ Redeemer address * @return redeemAmount_ Redeem amount */ function progressRedemptionInternal( bytes32 _messageHash, bool _proofProgress, bytes32 _unlockSecret ) private returns ( address redeemer_, uint256 redeemAmount_ ) { MessageBus.Message storage message = messages[_messageHash]; redeemer_ = message.sender; redeemAmount_ = redeems[_messageHash].amount; // Burn the redeem amount. UtilityTokenInterface(utilityToken).burn(address(this), redeemAmount_); // Transfer the bounty amount to the facilitator msg.sender.transfer(redeems[_messageHash].bounty); // delete the redeem data delete redeems[_messageHash]; // Emit ProgressedRedemption event. emit ProgressedRedemption( _messageHash, redeemer_, message.nonce, redeemAmount_, _proofProgress, _unlockSecret ); } }
Revert redemption to stop the redeem process. Only redeemer can revert redemption by providing penalty i.e. 1.5 times of bounty amount. On revert process, penalty and facilitator bounty will be burned. _messageHash Message hash. return redeemer_ Redeemer address return redeemerNonce_ Redeemer nonce return amount_ Redeem amount/ get the message object for the _messageHashpenalty charged to redeemer Update the message outbox status to declared. Emit RevertRedemptionDeclared event.
function revertRedemption( bytes32 _messageHash ) payable external returns ( address redeemer_, uint256 redeemerNonce_, uint256 amount_ ) { require( _messageHash != bytes32(0), "Message hash must not be zero" ); MessageBus.Message storage message = messages[_messageHash]; require(message.intentHash != bytes32(0)); require( message.intentHash != bytes32(0), "RedemptionIntentHash must not be zero" ); require( message.sender == msg.sender, "Only redeemer can revert redemption." ); uint256 penalty = redeems[_messageHash].bounty .mul(REVOCATION_PENALTY) .div(100); require( msg.value == penalty, "msg.value must match the penalty amount" ); require( messageBox.outbox[_messageHash] == MessageBus.MessageStatus.Undeclared, "Message status must be Undeclared" ); messageBox.outbox[_messageHash] = MessageBus.MessageStatus.DeclaredRevocation; redeemer_ = message.sender; redeemerNonce_ = message.nonce; amount_ = redeems[_messageHash].amount; emit RevertRedemptionDeclared( _messageHash, redeemer_, redeemerNonce_, amount_ ); }
2,553,542
// Sources flattened with hardhat v2.4.1 https://hardhat.org // File @openzeppelin/upgrades/contracts/Initializable.sol@v2.8.0 pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol@v2.5.0 pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol@v2.5.0 pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } // File hardlydifficult-ethereum-contracts/contracts/proxies/Clone2Factory.sol@v0.11.1 pragma solidity ^0.5.0; // From https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol // Updated to support Solidity 5, switch to `create2` and revert on fail library Clone2Factory { /** * @notice Uses create2 to deploy a clone to a pre-determined address. * @param target the address of the template contract, containing the logic for this contract. * @param salt a salt used to determine the contract address before the transaction is mined, * may be random or sequential. * The salt to use with the create2 call can be `msg.sender+salt` in order to * prevent an attacker from front-running another user's deployment. * @return proxyAddress the address of the newly deployed contract. * @dev Using `bytes12` for the salt saves 6 gas over using `uint96` (requires another shift). * Will revert on fail. */ function createClone2( address target, bytes32 salt ) internal returns (address proxyAddress) { // solium-disable-next-line assembly { let pointer := mload(0x40) // Create the bytecode for deployment based on the Minimal Proxy Standard (EIP-1167) // bytecode: 0x0 mstore(pointer, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(pointer, 0x14), shl(96, target)) mstore(add(pointer, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) // `create2` consumes all available gas if called with a salt that's already been consumed // we check if the address is available first so that doesn't happen // Costs ~958 gas // Calculate the hash let contractCodeHash := keccak256(pointer, 0x37) // salt: 0x100 mstore(add(pointer, 0x100), salt) // addressSeed: 0x40 // 0xff mstore(add(pointer, 0x40), 0xff00000000000000000000000000000000000000000000000000000000000000) // this mstore(add(pointer, 0x41), shl(96, address)) // salt mstore(add(pointer, 0x55), mload(add(pointer, 0x100))) // hash mstore(add(pointer, 0x75), contractCodeHash) proxyAddress := keccak256(add(pointer, 0x40), 0x55) switch extcodesize(proxyAddress) case 0 { // Deploy the contract, returning the address or 0 on fail proxyAddress := create2(0, pointer, 0x37, mload(add(pointer, 0x100))) } default { proxyAddress := 0 } } // Revert if the deployment fails (possible if salt was already used) require(proxyAddress != address(0), 'PROXY_DEPLOY_FAILED'); } } // File contracts/interfaces/IPublicLock.sol pragma solidity 0.5.17; /** * @title The PublicLock Interface * @author Nick Furfaro (unlock-protocol.com) */ contract IPublicLock { // See indentationissue description here: // https://github.com/duaraghav8/Ethlint/issues/268 // solium-disable indentation /// Functions function initialize( address _lockCreator, uint _expirationDuration, address _tokenAddress, uint _keyPrice, uint _maxNumberOfKeys, string calldata _lockName ) external; /** * @notice Allow the contract to accept tips in ETH sent directly to the contract. * @dev This is okay to use even if the lock is priced in ERC-20 tokens */ function() external payable; /** * @dev Never used directly */ function initialize() external; /** * @notice The version number of the current implementation on this network. * @return The current version number. */ function publicLockVersion() public pure returns (uint); /** * @notice Gets the current balance of the account provided. * @param _tokenAddress The token type to retrieve the balance of. * @param _account The account to get the balance of. * @return The number of tokens of the given type for the given address, possibly 0. */ function getBalance( address _tokenAddress, address _account ) external view returns (uint); /** * @notice Used to disable lock before migrating keys and/or destroying contract. * @dev Throws if called by other than a lock manager. * @dev Throws if lock contract has already been disabled. */ function disableLock() external; /** * @dev Called by a lock manager or beneficiary to withdraw all funds from the lock and send them to the `beneficiary`. * @dev Throws if called by other than a lock manager or beneficiary * @param _tokenAddress specifies the token address to withdraw or 0 for ETH. This is usually * the same as `tokenAddress` in MixinFunds. * @param _amount specifies the max amount to withdraw, which may be reduced when * considering the available balance. Set to 0 or MAX_UINT to withdraw everything. * -- however be wary of draining funds as it breaks the `cancelAndRefund` and `expireAndRefundFor` * use cases. */ function withdraw( address _tokenAddress, uint _amount ) external; /** * @notice An ERC-20 style approval, allowing the spender to transfer funds directly from this lock. */ function approveBeneficiary( address _spender, uint _amount ) external returns (bool); /** * A function which lets a Lock manager of the lock to change the price for future purchases. * @dev Throws if called by other than a Lock manager * @dev Throws if lock has been disabled * @dev Throws if _tokenAddress is not a valid token * @param _keyPrice The new price to set for keys * @param _tokenAddress The address of the erc20 token to use for pricing the keys, * or 0 to use ETH */ function updateKeyPricing( uint _keyPrice, address _tokenAddress ) external; /** * A function which lets a Lock manager update the beneficiary account, * which receives funds on withdrawal. * @dev Throws if called by other than a Lock manager or beneficiary * @dev Throws if _beneficiary is address(0) * @param _beneficiary The new address to set as the beneficiary */ function updateBeneficiary( address _beneficiary ) external; /** * Checks if the user has a non-expired key. * @param _user The address of the key owner */ function getHasValidKey( address _user ) external view returns (bool); /** * @notice Find the tokenId for a given user * @return The tokenId of the NFT, else returns 0 * @param _account The address of the key owner */ function getTokenIdFor( address _account ) external view returns (uint); /** * A function which returns a subset of the keys for this Lock as an array * @param _page the page of key owners requested when faceted by page size * @param _pageSize the number of Key Owners requested per page * @dev Throws if there are no key owners yet */ function getOwnersByPage( uint _page, uint _pageSize ) external view returns (address[] memory); /** * Checks if the given address owns the given tokenId. * @param _tokenId The tokenId of the key to check * @param _keyOwner The potential key owners address */ function isKeyOwner( uint _tokenId, address _keyOwner ) external view returns (bool); /** * @dev Returns the key's ExpirationTimestamp field for a given owner. * @param _keyOwner address of the user for whom we search the key * @dev Returns 0 if the owner has never owned a key for this lock */ function keyExpirationTimestampFor( address _keyOwner ) external view returns (uint timestamp); /** * Public function which returns the total number of unique owners (both expired * and valid). This may be larger than totalSupply. */ function numberOfOwners() external view returns (uint); /** * Allows a Lock manager to assign a descriptive name for this Lock. * @param _lockName The new name for the lock * @dev Throws if called by other than a Lock manager */ function updateLockName( string calldata _lockName ) external; /** * Allows a Lock manager to assign a Symbol for this Lock. * @param _lockSymbol The new Symbol for the lock * @dev Throws if called by other than a Lock manager */ function updateLockSymbol( string calldata _lockSymbol ) external; /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory); /** * Allows a Lock manager to update the baseTokenURI for this Lock. * @dev Throws if called by other than a Lock manager * @param _baseTokenURI String representing the base of the URI for this lock. */ function setBaseTokenURI( string calldata _baseTokenURI ) external; /** @notice A distinct Uniform Resource Identifier (URI) for a given asset. * @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC * 3986. The URI may point to a JSON file that conforms to the "ERC721 * Metadata JSON Schema". * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md * @param _tokenId The tokenID we're inquiring about * @return String representing the URI for the requested token */ function tokenURI( uint256 _tokenId ) external view returns(string memory); /** * @notice Allows a Lock manager to add or remove an event hook */ function setEventHooks( address _onKeyPurchaseHook, address _onKeyCancelHook ) external; /** * Allows a Lock manager to give a collection of users a key with no charge. * Each key may be assigned a different expiration date. * @dev Throws if called by other than a Lock manager * @param _recipients An array of receiving addresses * @param _expirationTimestamps An array of expiration Timestamps for the keys being granted */ function grantKeys( address[] calldata _recipients, uint[] calldata _expirationTimestamps, address[] calldata _keyManagers ) external; /** * @dev Purchase function * @param _value the number of tokens to pay for this purchase >= the current keyPrice - any applicable discount * (_value is ignored when using ETH) * @param _recipient address of the recipient of the purchased key * @param _referrer address of the user making the referral * @param _data arbitrary data populated by the front-end which initiated the sale * @dev Throws if lock is disabled. Throws if lock is sold-out. Throws if _recipient == address(0). * @dev Setting _value to keyPrice exactly doubles as a security feature. That way if a Lock manager increases the * price while my transaction is pending I can't be charged more than I expected (only applicable to ERC-20 when more * than keyPrice is approved for spending). */ function purchase( uint256 _value, address _recipient, address _referrer, bytes calldata _data ) external payable; /** * @notice returns the minimum price paid for a purchase with these params. * @dev this considers any discount from Unlock or the OnKeyPurchase hook. */ function purchasePriceFor( address _recipient, address _referrer, bytes calldata _data ) external view returns (uint); /** * Allow a Lock manager to change the transfer fee. * @dev Throws if called by other than a Lock manager * @param _transferFeeBasisPoints The new transfer fee in basis-points(bps). * Ex: 200 bps = 2% */ function updateTransferFee( uint _transferFeeBasisPoints ) external; /** * Determines how much of a fee a key owner would need to pay in order to * transfer the key to another account. This is pro-rated so the fee goes down * overtime. * @dev Throws if _keyOwner does not have a valid key * @param _keyOwner The owner of the key check the transfer fee for. * @param _time The amount of time to calculate the fee for. * @return The transfer fee in seconds. */ function getTransferFee( address _keyOwner, uint _time ) external view returns (uint); /** * @dev Invoked by a Lock manager to expire the user's key and perform a refund and cancellation of the key * @param _keyOwner The key owner to whom we wish to send a refund to * @param amount The amount to refund the key-owner * @dev Throws if called by other than a Lock manager * @dev Throws if _keyOwner does not have a valid key */ function expireAndRefundFor( address _keyOwner, uint amount ) external; /** * @dev allows the key manager to expire a given tokenId * and send a refund to the keyOwner based on the amount of time remaining. * @param _tokenId The id of the key to cancel. */ function cancelAndRefund(uint _tokenId) external; /** * @dev Cancels a key managed by a different user and sends the funds to the keyOwner. * @param _keyManager the key managed by this user will be canceled * @param _v _r _s getCancelAndRefundApprovalHash signed by the _keyManager * @param _tokenId The key to cancel */ function cancelAndRefundFor( address _keyManager, uint8 _v, bytes32 _r, bytes32 _s, uint _tokenId ) external; /** * @notice Sets the minimum nonce for a valid off-chain approval message from the * senders account. * @dev This can be used to invalidate a previously signed message. */ function invalidateOffchainApproval( uint _nextAvailableNonce ) external; /** * Allow a Lock manager to change the refund penalty. * @dev Throws if called by other than a Lock manager * @param _freeTrialLength The new duration of free trials for this lock * @param _refundPenaltyBasisPoints The new refund penaly in basis-points(bps) */ function updateRefundPenalty( uint _freeTrialLength, uint _refundPenaltyBasisPoints ) external; /** * @dev Determines how much of a refund a key owner would receive if they issued * @param _keyOwner The key owner to get the refund value for. * a cancelAndRefund block.timestamp. * Note that due to the time required to mine a tx, the actual refund amount will be lower * than what the user reads from this call. */ function getCancelAndRefundValueFor( address _keyOwner ) external view returns (uint refund); function keyManagerToNonce(address ) external view returns (uint256 ); /** * @notice returns the hash to sign in order to allow another user to cancel on your behalf. * @dev this can be computed in JS instead of read from the contract. * @param _keyManager The key manager's address (also the message signer) * @param _txSender The address cancelling cancel on behalf of the keyOwner * @return approvalHash The hash to sign */ function getCancelAndRefundApprovalHash( address _keyManager, address _txSender ) external view returns (bytes32 approvalHash); function addKeyGranter(address account) external; function addLockManager(address account) external; function isKeyGranter(address account) external view returns (bool); function isLockManager(address account) external view returns (bool); function onKeyPurchaseHook() external view returns(address); function onKeyCancelHook() external view returns(address); function revokeKeyGranter(address _granter) external; function renounceLockManager() external; ///=================================================================== /// Auto-generated getter functions from public state variables function beneficiary() external view returns (address ); function expirationDuration() external view returns (uint256 ); function freeTrialLength() external view returns (uint256 ); function isAlive() external view returns (bool ); function keyPrice() external view returns (uint256 ); function maxNumberOfKeys() external view returns (uint256 ); function owners(uint256 ) external view returns (address ); function refundPenaltyBasisPoints() external view returns (uint256 ); function tokenAddress() external view returns (address ); function transferFeeBasisPoints() external view returns (uint256 ); function unlockProtocol() external view returns (address ); function keyManagerOf(uint) external view returns (address ); ///=================================================================== /** * @notice Allows the key owner to safely share their key (parent key) by * transferring a portion of the remaining time to a new key (child key). * @dev Throws if key is not valid. * @dev Throws if `_to` is the zero address * @param _to The recipient of the shared key * @param _tokenId the key to share * @param _timeShared The amount of time shared * checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256('onERC721Received(address,address,uint,bytes)'))`. * @dev Emit Transfer event */ function shareKey( address _to, uint _tokenId, uint _timeShared ) external; /** * @notice Update transfer and cancel rights for a given key * @param _tokenId The id of the key to assign rights for * @param _keyManager The address to assign the rights to for the given key */ function setKeyManagerOf( uint _tokenId, address _keyManager ) external; /// @notice A descriptive name for a collection of NFTs in this contract function name() external view returns (string memory _name); ///=================================================================== /// From ERC165.sol function supportsInterface(bytes4 interfaceId) external view returns (bool ); ///=================================================================== /// From ERC-721 /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address _owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address _owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; /** * @notice Get the approved address for a single NFT * @dev Throws if `_tokenId` is not a valid NFT. * @param _tokenId The NFT to find the approved address for * @return The approved address for this NFT, or the zero address if there is none */ function getApproved(uint256 _tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address _owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 index) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); /** * @notice An ERC-20 style transfer. * @param _value sends a token with _value * expirationDuration (the amount of time remaining on a standard purchase). * @dev The typical use case would be to call this with _value 1, which is on par with calling `transferFrom`. If the user * has more than `expirationDuration` time remaining this may use the `shareKey` function to send some but not all of the token. */ function transfer( address _to, uint _value ) external returns (bool success); } // File contracts/interfaces/IUnlock.sol pragma solidity 0.5.17; /** * @title The Unlock Interface * @author Nick Furfaro (unlock-protocol.com) **/ interface IUnlock { // Use initialize instead of a constructor to support proxies(for upgradeability via zos). function initialize(address _unlockOwner) external; /** * @dev Create lock * This deploys a lock for a creator. It also keeps track of the deployed lock. * @param _tokenAddress set to the ERC20 token address, or 0 for ETH. * @param _salt an identifier for the Lock, which is unique for the user. * This may be implemented as a sequence ID or with RNG. It's used with `create2` * to know the lock's address before the transaction is mined. */ function createLock( uint _expirationDuration, address _tokenAddress, uint _keyPrice, uint _maxNumberOfKeys, string calldata _lockName, bytes12 _salt ) external; /** * This function keeps track of the added GDP, as well as grants of discount tokens * to the referrer, if applicable. * The number of discount tokens granted is based on the value of the referal, * the current growth rate and the lock's discount token distribution rate * This function is invoked by a previously deployed lock only. */ function recordKeyPurchase( uint _value, address _referrer // solhint-disable-line no-unused-vars ) external; /** * This function will keep track of consumed discounts by a given user. * It will also grant discount tokens to the creator who is granting the discount based on the * amount of discount and compensation rate. * This function is invoked by a previously deployed lock only. */ function recordConsumedDiscount( uint _discount, uint _tokens // solhint-disable-line no-unused-vars ) external; /** * This function returns the discount available for a user, when purchasing a * a key from a lock. * This does not modify the state. It returns both the discount and the number of tokens * consumed to grant that discount. */ function computeAvailableDiscountFor( address _purchaser, // solhint-disable-line no-unused-vars uint _keyPrice // solhint-disable-line no-unused-vars ) external view returns(uint discount, uint tokens); // Function to read the globalTokenURI field. function globalBaseTokenURI() external view returns(string memory); /** * @dev Redundant with globalBaseTokenURI() for backwards compatibility with v3 & v4 locks. */ function getGlobalBaseTokenURI() external view returns (string memory); // Function to read the globalTokenSymbol field. function globalTokenSymbol() external view returns(string memory); /** * @dev Redundant with globalTokenSymbol() for backwards compatibility with v3 & v4 locks. */ function getGlobalTokenSymbol() external view returns (string memory); /** * @notice Allows the owner to update configuration variables */ function configUnlock( address _udt, address _weth, uint _estimatedGasForPurchase, string calldata _symbol, string calldata _URI ) external; /** * @notice Upgrade the PublicLock template used for future calls to `createLock`. * @dev This will initialize the template and revokeOwnership. */ function setLockTemplate( address payable _publicLockAddress ) external; // Allows the owner to change the value tracking variables as needed. function resetTrackedValue( uint _grossNetworkProduct, uint _totalDiscountGranted ) external; function grossNetworkProduct() external view returns(uint); function totalDiscountGranted() external view returns(uint); function locks(address) external view returns(bool deployed, uint totalSales, uint yieldedDiscountTokens); // The address of the public lock template, used when `createLock` is called function publicLockAddress() external view returns(address); // Map token address to exchange contract address if the token is supported // Used for GDP calculations function uniswapOracles(address) external view returns(address); // The WETH token address, used for value calculations function weth() external view returns(address); // The UDT token address, used to mint tokens on referral function udt() external view returns(address); // The approx amount of gas required to purchase a key function estimatedGasForPurchase() external view returns(uint); // The version number of the current Unlock implementation on this network function unlockVersion() external pure returns(uint16); /** * @notice allows the owner to set the oracle address to use for value conversions * setting the _oracleAddress to address(0) removes support for the token * @dev This will also call update to ensure at least one datapoint has been recorded. */ function setOracle( address _tokenAddress, address _oracleAddress ) external; /** * @dev Returns true if the caller is the current owner. */ function isOwner() external view returns(bool); /** * @dev Returns the address of the current owner. */ function owner() external view returns(address); /** * @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() external; /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) external; } // File @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol@v2.5.0 pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File hardlydifficult-eth/contracts/protocols/Uniswap/IUniswapOracle.sol@v1.1.1 // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface IUniswapOracle { function PERIOD() external returns (uint); function factory() external returns (address); function update( address _tokenIn, address _tokenOut ) external; function consult( address _tokenIn, uint _amountIn, address _tokenOut ) external view returns (uint _amountOut); function updateAndConsult( address _tokenIn, uint _amountIn, address _tokenOut ) external returns (uint _amountOut); } // File @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol@v2.5.0 pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File contracts/interfaces/IMintableERC20.sol pragma solidity 0.5.17; interface IMintableERC20 { function mint(address account, uint256 amount) external returns (bool); function totalSupply() external returns (uint); } // File contracts/Unlock.sol pragma solidity 0.5.17; /** * @title The Unlock contract * @author Julien Genestoux (unlock-protocol.com) * This smart contract has 3 main roles: * 1. Distribute discounts to discount token holders * 2. Grant dicount tokens to users making referrals and/or publishers granting discounts. * 3. Create & deploy Public Lock contracts. * In order to achieve these 3 elements, it keeps track of several things such as * a. Deployed locks addresses and balances of discount tokens granted by each lock. * b. The total network product (sum of all key sales, net of discounts) * c. Total of discounts granted * d. Balances of discount tokens, including 'frozen' tokens (which have been used to claim * discounts and cannot be used/transferred for a given period) * e. Growth rate of Network Product * f. Growth rate of Discount tokens supply * The smart contract has an owner who only can perform the following * - Upgrades * - Change in golden rules (20% of GDP available in discounts, and supply growth rate is at most * 50% of GNP growth rate) * NOTE: This smart contract is partially implemented for now until enough Locks are deployed and * in the wild. * The partial implementation includes the following features: * a. Keeping track of deployed locks * b. Keeping track of GNP */ /// @dev Must list the direct base contracts in the order from “most base-like” to “most derived”. /// https://solidity.readthedocs.io/en/latest/contracts.html#multiple-inheritance-and-linearization contract Unlock is IUnlock, Initializable, Ownable { using Address for address; using Clone2Factory for address; using SafeMath for uint; /** * The struct for a lock * We use deployed to keep track of deployments. * This is required because both totalSales and yieldedDiscountTokens are 0 when initialized, * which would be the same values when the lock is not set. */ struct LockBalances { bool deployed; uint totalSales; // This is in wei uint yieldedDiscountTokens; } modifier onlyFromDeployedLock() { require(locks[msg.sender].deployed, 'ONLY_LOCKS'); _; } uint public grossNetworkProduct; uint public totalDiscountGranted; // We keep track of deployed locks to ensure that callers are all deployed locks. mapping (address => LockBalances) public locks; // global base token URI // Used by locks where the owner has not set a custom base URI. string public globalBaseTokenURI; // global base token symbol // Used by locks where the owner has not set a custom symbol string public globalTokenSymbol; // The address of the public lock template, used when `createLock` is called address public publicLockAddress; // Map token address to oracle contract address if the token is supported // Used for GDP calculations mapping (address => IUniswapOracle) public uniswapOracles; // The WETH token address, used for value calculations address public weth; // The UDT token address, used to mint tokens on referral address public udt; // The approx amount of gas required to purchase a key uint public estimatedGasForPurchase; // Events event NewLock( address indexed lockOwner, address indexed newLockAddress ); event ConfigUnlock( address udt, address weth, uint estimatedGasForPurchase, string globalTokenSymbol, string globalTokenURI ); event SetLockTemplate( address publicLockAddress ); event ResetTrackedValue( uint grossNetworkProduct, uint totalDiscountGranted ); // Use initialize instead of a constructor to support proxies (for upgradeability via zos). function initialize( address _unlockOwner ) public initializer() { // We must manually initialize Ownable.sol Ownable.initialize(_unlockOwner); } /** * @dev Create lock * This deploys a lock for a creator. It also keeps track of the deployed lock. * @param _tokenAddress set to the ERC20 token address, or 0 for ETH. * @param _salt an identifier for the Lock, which is unique for the user. * This may be implemented as a sequence ID or with RNG. It's used with `create2` * to know the lock's address before the transaction is mined. */ function createLock( uint _expirationDuration, address _tokenAddress, uint _keyPrice, uint _maxNumberOfKeys, string memory _lockName, bytes12 _salt ) public { require(publicLockAddress != address(0), 'MISSING_LOCK_TEMPLATE'); // create lock bytes32 salt; // solium-disable-next-line assembly { let pointer := mload(0x40) // The salt is the msg.sender mstore(pointer, shl(96, caller)) // followed by the _salt provided mstore(add(pointer, 0x14), _salt) salt := mload(pointer) } address payable newLock = address(uint160(publicLockAddress.createClone2(salt))); IPublicLock(newLock).initialize( msg.sender, _expirationDuration, _tokenAddress, _keyPrice, _maxNumberOfKeys, _lockName ); // Assign the new Lock locks[newLock] = LockBalances({ deployed: true, totalSales: 0, yieldedDiscountTokens: 0 }); // trigger event emit NewLock(msg.sender, newLock); } /** * This function returns the discount available for a user, when purchasing a * a key from a lock. * This does not modify the state. It returns both the discount and the number of tokens * consumed to grant that discount. * TODO: actually implement this. */ function computeAvailableDiscountFor( address /* _purchaser */, uint /* _keyPrice */ ) public view returns (uint discount, uint tokens) { // TODO: implement me return (0, 0); } /** * This function keeps track of the added GDP, as well as grants of discount tokens * to the referrer, if applicable. * The number of discount tokens granted is based on the value of the referal, * the current growth rate and the lock's discount token distribution rate * This function is invoked by a previously deployed lock only. * TODO: actually implement */ function recordKeyPurchase( uint _value, address _referrer ) public onlyFromDeployedLock() { if(_value > 0) { uint valueInETH; address tokenAddress = IPublicLock(msg.sender).tokenAddress(); if(tokenAddress != address(0) && tokenAddress != weth) { // If priced in an ERC-20 token, find the supported uniswap oracle IUniswapOracle oracle = uniswapOracles[tokenAddress]; if(address(oracle) != address(0)) { valueInETH = oracle.updateAndConsult(tokenAddress, _value, weth); } } else { // If priced in ETH (or value is 0), no conversion is required valueInETH = _value; } grossNetworkProduct = grossNetworkProduct.add(valueInETH); // If GNP does not overflow, the lock totalSales should be safe locks[msg.sender].totalSales += valueInETH; // Mint UDT if(_referrer != address(0)) { IUniswapOracle udtOracle = uniswapOracles[udt]; if(address(udtOracle) != address(0)) { // Get the value of 1 UDT (w/ 18 decimals) in ETH uint udtPrice = udtOracle.updateAndConsult(udt, 10 ** 18, weth); // tokensToMint is either == to the gas cost times 1.25 to cover the 20% dev cut uint tokensToMint = (estimatedGasForPurchase * tx.gasprice).mul(125 * 10 ** 18) / 100 / udtPrice; // or tokensToMint is capped by percent growth uint maxTokens = IMintableERC20(udt).totalSupply().mul(valueInETH) / 2 / grossNetworkProduct; if(tokensToMint > maxTokens) { tokensToMint = maxTokens; } if(tokensToMint > 0) { // 80% goes to the referrer, 20% to the Unlock dev - round in favor of the referrer uint devReward = tokensToMint.mul(20) / 100; IMintableERC20(udt).mint(_referrer, tokensToMint - devReward); if(devReward > 0) { IMintableERC20(udt).mint(owner(), devReward); } } } } } } /** * This function will keep track of consumed discounts by a given user. * It will also grant discount tokens to the creator who is granting the discount based on the * amount of discount and compensation rate. * This function is invoked by a previously deployed lock only. */ function recordConsumedDiscount( uint _discount, uint /* _tokens */ ) public onlyFromDeployedLock() { // TODO: implement me totalDiscountGranted += _discount; return; } // The version number of the current Unlock implementation on this network function unlockVersion( ) external pure returns (uint16) { return 8; } /** * @notice Allows the owner to update configuration variables */ function configUnlock( address _udt, address _weth, uint _estimatedGasForPurchase, string calldata _symbol, string calldata _URI ) external onlyOwner { udt = _udt; weth = _weth; estimatedGasForPurchase = _estimatedGasForPurchase; globalTokenSymbol = _symbol; globalBaseTokenURI = _URI; emit ConfigUnlock(_udt, _weth, _estimatedGasForPurchase, _symbol, _URI); } /** * @notice Upgrade the PublicLock template used for future calls to `createLock`. * @dev This will initialize the template and revokeOwnership. */ function setLockTemplate( address payable _publicLockAddress ) external onlyOwner { // First claim the template so that no-one else could // this will revert if the template was already initialized. IPublicLock(_publicLockAddress).initialize( address(this), 0, address(0), 0, 0, '' ); IPublicLock(_publicLockAddress).renounceLockManager(); publicLockAddress = _publicLockAddress; emit SetLockTemplate(_publicLockAddress); } /** * @notice allows the owner to set the oracle address to use for value conversions * setting the _oracleAddress to address(0) removes support for the token * @dev This will also call update to ensure at least one datapoint has been recorded. */ function setOracle( address _tokenAddress, address _oracleAddress ) external onlyOwner { uniswapOracles[_tokenAddress] = IUniswapOracle(_oracleAddress); if(_oracleAddress != address(0)) { IUniswapOracle(_oracleAddress).update(_tokenAddress, weth); } } // Allows the owner to change the value tracking variables as needed. function resetTrackedValue( uint _grossNetworkProduct, uint _totalDiscountGranted ) external onlyOwner { grossNetworkProduct = _grossNetworkProduct; totalDiscountGranted = _totalDiscountGranted; emit ResetTrackedValue(_grossNetworkProduct, _totalDiscountGranted); } /** * @dev Redundant with globalBaseTokenURI() for backwards compatibility with v3 & v4 locks. */ function getGlobalBaseTokenURI() external view returns (string memory) { return globalBaseTokenURI; } /** * @dev Redundant with globalTokenSymbol() for backwards compatibility with v3 & v4 locks. */ function getGlobalTokenSymbol() external view returns (string memory) { return globalTokenSymbol; } }
This function will keep track of consumed discounts by a given user. It will also grant discount tokens to the creator who is granting the discount based on the amount of discount and compensation rate. This function is invoked by a previously deployed lock only./ TODO: implement me
function recordConsumedDiscount( uint _discount, uint /* _tokens */ ) public onlyFromDeployedLock() { totalDiscountGranted += _discount; return; }
954,018
pragma solidity 0.5.16; import "../lib/protobuf/IssuanceData.sol"; import "../lib/protobuf/SupplementalLineItem.sol"; import "../lib/protobuf/TokenTransfer.sol"; import "./InstrumentInterface.sol"; /** * @title Base contract for instruments. */ contract InstrumentBase is InstrumentInterface { /** * @dev The event used to schedule contract events after specific time. * @param issuanceId The id of the issuance * @param timestamp After when the issuance should be notified * @param eventName The name of the custom event * @param eventPayload The payload the custom event */ event EventTimeScheduled( uint256 indexed issuanceId, uint256 timestamp, bytes32 eventName, bytes eventPayload ); /** * @dev The event used to schedule contract events after specific block. * @param issuanceId The id of the issuance * @param blockNumber After which block the issuance should be notified * @param eventName The name of the custom event * @param eventPayload The payload the custom event */ event EventBlockScheduled( uint256 indexed issuanceId, uint256 blockNumber, bytes32 eventName, bytes eventPayload ); /** * @dev The event used to track the creation of a new supplemental line item. * @param issuanceId The id of the issuance * @param itemId The id of the supplemental line item * @param itemType Type of the supplemental line item * @param state State of the supplemental line item * @param obligatorAddress The obligator of the supplemental line item * @param claimorAddress The claimor of the supplemental line item * @param tokenAddress The asset type of the supplemental line item * @param amount The asset amount of the supplemental line item * @param dueTimestamp When is the supplemental line item due */ event SupplementalLineItemCreated( uint256 indexed issuanceId, uint8 indexed itemId, SupplementalLineItem.Type itemType, SupplementalLineItem.State state, address obligatorAddress, address claimorAddress, address tokenAddress, uint256 amount, uint256 dueTimestamp ); /** * @dev The event used to track the update of an existing supplemental line item * @param issuanceId The id of the issuance * @param itemId The id of the supplemental line item * @param state The new state of the supplemental line item * @param reinitiatedTo The target supplemental line item if the current one is reinitiated */ event SupplementalLineItemUpdated( uint256 indexed issuanceId, uint8 indexed itemId, SupplementalLineItem.State state, uint8 reinitiatedTo ); // Scheduled custom events bytes32 internal constant ENGAGEMENT_DUE_EVENT = "engagement_due"; bytes32 internal constant ISSUANCE_DUE_EVENT = "issuance_due"; // Custom events bytes32 internal constant CANCEL_ISSUANCE_EVENT = "cancel_issuance"; bytes32 internal constant REPAY_ISSUANCE_FULL_EVENT = "repay_full"; // Common properties shared by all issuances uint256 internal _issuanceId; address internal _fspAddress; address internal _brokerAddress; address internal _instrumentEscrowAddress; address internal _issuanceEscrowAddress; address internal _priceOracleAddress; address internal _makerAddress; address internal _takerAddress; uint256 internal _creationTimestamp; uint256 internal _engagementTimestamp; uint256 internal _engagementDueTimestamp; uint256 internal _issuanceDueTimestamp; uint256 internal _settlementTimestamp; IssuanceProperties.State internal _state; // List of supplemental line items mapping(uint8 => SupplementalLineItem.Data) internal _supplementalLineItems; uint8[] internal _supplementalLineItemIds; /** * @dev Initializes an issuance with common parameters. * @param issuanceId ID of the issuance. * @param fspAddress Address of the FSP who creates the issuance. * @param brokerAddress Address of the instrument broker. * @param instrumentEscrowAddress Address of the instrument escrow. * @param issuanceEscrowAddress Address of the issuance escrow. * @param priceOracleAddress Address of the price oracle. */ function initialize( uint256 issuanceId, address fspAddress, address brokerAddress, address instrumentEscrowAddress, address issuanceEscrowAddress, address priceOracleAddress ) public { require(_issuanceId == 0, "Already initialized"); require(issuanceId != 0, "Issuance ID not set"); require(fspAddress != address(0x0), "FSP not set"); require( instrumentEscrowAddress != address(0x0), "Instrument Escrow not set" ); require( issuanceEscrowAddress != address(0x0), "Issuance Escrow not set" ); require(priceOracleAddress != address(0x0), "Price Oracle not set"); _issuanceId = issuanceId; _fspAddress = fspAddress; _brokerAddress = brokerAddress; _instrumentEscrowAddress = instrumentEscrowAddress; _issuanceEscrowAddress = issuanceEscrowAddress; _priceOracleAddress = priceOracleAddress; _state = IssuanceProperties.State.Initiated; } /** * @dev Checks whether the issuance is terminated. No futher action is taken on a terminated issuance. */ function isTerminated() public view returns (bool) { return _state == IssuanceProperties.State.Unfunded || _state == IssuanceProperties.State.Cancelled || _state == IssuanceProperties.State.CompleteNotEngaged || _state == IssuanceProperties.State.CompleteEngaged || _state == IssuanceProperties.State.Delinquent; } /** * @dev Create a new issuance of the financial instrument */ function createIssuance( address, /** callerAddress */ bytes memory /** makerParametersData */ ) public returns (bytes memory) { revert("Unsupported operation"); } /** * @dev A taker engages to the issuance */ function engageIssuance( address, /** callerAddress */ bytes memory /** takerParameters */ ) public returns (bytes memory) { revert("Unsupported operation"); } /** * @dev An account has made an ERC20 token deposit to the issuance */ function processTokenDeposit( address, /** callerAddress */ address, /** tokenAddress */ uint256 /** amount */ ) public returns (bytes memory) { revert("Unsupported operation"); } /** * @dev An account has made an ERC20 token withdraw from the issuance */ function processTokenWithdraw( address, /** callerAddress */ address, /** tokenAddress */ uint256 /** amount */ ) public returns (bytes memory) { revert("Unsupported operation"); } /** * @dev A custom event is triggered. */ function processCustomEvent( address, /** callerAddress */ bytes32, /** eventName */ bytes memory /** eventPayload */ ) public returns (bytes memory) { revert("Unsupported operation"); } /** * @dev Get custom data. */ function getCustomData( address, /** callerAddress */ bytes32 /** dataName */ ) public view returns (bytes memory) { revert("Unsupported operation"); } /** * @dev Returns the common properties about the issuance. */ function _getIssuanceProperties() internal view returns (IssuanceProperties.Data memory) { SupplementalLineItem.Data[] memory supplementalLineItems = new SupplementalLineItem.Data[]( _supplementalLineItemIds.length ); for (uint256 i = 0; i < _supplementalLineItemIds.length; i++) { supplementalLineItems[i] = _supplementalLineItems[_supplementalLineItemIds[i]]; } return IssuanceProperties.Data({ issuanceId: _issuanceId, makerAddress: _makerAddress, takerAddress: _takerAddress, engagementDueTimestamp: _engagementDueTimestamp, issuanceDueTimestamp: _issuanceDueTimestamp, creationTimestamp: _creationTimestamp, engagementTimestamp: _engagementTimestamp, settlementTimestamp: _settlementTimestamp, issuanceProxyAddress: address(this), issuanceEscrowAddress: _issuanceEscrowAddress, state: _state, supplementalLineItems: supplementalLineItems }); } /** * @dev Create a new inbound transfer action. */ function _createInboundTransfer( address account, address tokenAddress, uint256 amount, bytes32 action ) internal pure returns (Transfer.Data memory) { Transfer.Data memory transfer = Transfer.Data({ transferType: Transfer.Type.Inbound, fromAddress: account, toAddress: account, tokenAddress: tokenAddress, amount: amount, action: action }); return transfer; } /** * @dev Create a new outbound transfer action. */ function _createOutboundTransfer( address account, address tokenAddress, uint256 amount, bytes32 action ) internal pure returns (Transfer.Data memory) { Transfer.Data memory transfer = Transfer.Data({ transferType: Transfer.Type.Outbound, fromAddress: account, toAddress: account, tokenAddress: tokenAddress, amount: amount, action: action }); return transfer; } /** * @dev Create a new intra-issuance transfer action. */ function _createIntraIssuanceTransfer( address fromAddress, address toAddress, address tokenAddress, uint256 amount, bytes32 action ) internal pure returns (Transfer.Data memory) { Transfer.Data memory transfer = Transfer.Data({ transferType: Transfer.Type.IntraIssuance, fromAddress: fromAddress, toAddress: toAddress, tokenAddress: tokenAddress, amount: amount, action: action }); return transfer; } /** * @dev Create new payable for the issuance. */ function _createNewPayable( uint8 id, address obligatorAddress, address claimorAddress, address tokenAddress, uint256 amount, uint256 dueTimestamp ) internal { require( _supplementalLineItems[id].state == SupplementalLineItem.State.UnknownState, "Item exists" ); _supplementalLineItemIds.push(id); _supplementalLineItems[id] = SupplementalLineItem.Data({ id: id, lineItemType: SupplementalLineItem.Type.Payable, state: SupplementalLineItem.State.Unpaid, obligatorAddress: obligatorAddress, claimorAddress: claimorAddress, tokenAddress: tokenAddress, amount: amount, dueTimestamp: dueTimestamp, reinitiatedTo: 0 }); emit SupplementalLineItemCreated( _issuanceId, id, SupplementalLineItem.Type.Payable, SupplementalLineItem.State.Unpaid, obligatorAddress, claimorAddress, tokenAddress, amount, dueTimestamp ); } /** * @dev Updates the existing payable for the issuance. */ function _updatePayable( uint8 id, SupplementalLineItem.State state, uint8 reinitiatedTo ) internal { require( _supplementalLineItems[id].state != SupplementalLineItem.State.UnknownState, "Item not exists" ); _supplementalLineItems[id].state = state; _supplementalLineItems[id].reinitiatedTo = reinitiatedTo; emit SupplementalLineItemUpdated(_issuanceId, id, state, reinitiatedTo); } }
Returns the common properties about the issuance./
function _getIssuanceProperties() internal view returns (IssuanceProperties.Data memory) { SupplementalLineItem.Data[] memory supplementalLineItems = new SupplementalLineItem.Data[]( _supplementalLineItemIds.length ); for (uint256 i = 0; i < _supplementalLineItemIds.length; i++) { supplementalLineItems[i] = _supplementalLineItems[_supplementalLineItemIds[i]]; } return IssuanceProperties.Data({ issuanceId: _issuanceId, makerAddress: _makerAddress, takerAddress: _takerAddress, engagementDueTimestamp: _engagementDueTimestamp, issuanceDueTimestamp: _issuanceDueTimestamp, creationTimestamp: _creationTimestamp, engagementTimestamp: _engagementTimestamp, settlementTimestamp: _settlementTimestamp, issuanceProxyAddress: address(this), issuanceEscrowAddress: _issuanceEscrowAddress, state: _state, supplementalLineItems: supplementalLineItems }); }
12,957,178
/** *Submitted for verification at Etherscan.io on 2021-08-03 */ /** *Submitted for verification at BscScan.com on 2021-07-09 */ /** *Submitted for verification at hecoinfo.com on 2021-05-24 */ pragma solidity 0.5.16; interface IDOJO { /** * @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); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view 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 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; } } /** * @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 onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract DOJOToken is Context, IDOJO, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint8 private _decimals; string private _symbol; string private _name; constructor() public { _name = "DOJO"; _symbol = "DOJO"; _decimals = 18; _totalSupply = 19716280000000000000000000000000; _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address) { return owner(); } /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns the token name. */ function name() external view returns (string memory) { return _name; } /** * @dev See {DOJO-totalSupply}. */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @dev See {DOJO-balanceOf}. */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @dev See {DOJO-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) external returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {DOJO-allowance}. */ function allowance(address owner, address spender) external view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {DOJO-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {DOJO-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {DOJO}; * * 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) external returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "DOJO: 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 {DOJO-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 {DOJO-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, "DOJO: 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 { require(sender != address(0), "DOJO: transfer from the zero address"); require(recipient != address(0), "DOJO: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "DOJO: 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), "DOJO: 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), "DOJO: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "DOJO: 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), "DOJO: approve from the zero address"); require(spender != address(0), "DOJO: 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, "DOJO: burn amount exceeds allowance")); } }
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), "DOJO: transfer from the zero address"); require(recipient != address(0), "DOJO: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "DOJO: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); }
8,044,029
//SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "./interfaces/IStakingFactory.sol"; import "./StakingRewards.sol"; import "./interfaces/IStakingRewards.sol"; /// @title StakingFactory, A contract where users can create their own staking pool contract StakingFactory is IStakingFactory { address[] private allPools; mapping(address => bool) private isOurs; /** * @notice Caller creates a new StakingRewards pool and it gets added to this factory * @param _stakingToken token address that needs to be staked to earn rewards * @param _startBlock block number when rewards start * @param _endBlock block number when rewards end * @param _bufferBlocks no. of blocks after which owner can reclaim any unclaimed rewards * @return listaddr address of newly created contract */ function createPool( address _stakingToken, uint256 _startBlock, uint256 _endBlock, uint256 _bufferBlocks ) external override returns (address listaddr) { listaddr = address( new StakingRewards( _stakingToken, _startBlock, _endBlock, _bufferBlocks ) ); StakingRewards(listaddr).transferOwnership(msg.sender); allPools.push(listaddr); isOurs[listaddr] = true; emit PoolCreated(msg.sender, listaddr); } /** * @notice Checks if a address belongs to this contract' pools */ function ours(address _a) external view override returns (bool) { return isOurs[_a]; } /** * @notice Returns no. of pools stored in contract */ function listCount() external view override returns (uint256) { return allPools.length; } /** * @notice Returns address of the pool located at given id */ function listAt(uint256 _idx) external view override returns (address) { require(_idx < allPools.length, "Index exceeds list length"); return allPools[_idx]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.3; interface IStakingFactory { event PoolCreated(address indexed sender, address indexed newPool); function createPool( address _stakingToken, uint256 _startBlock, uint256 _endBlock, uint256 _bufferBlocks ) external returns (address); function ours(address _a) external view returns (bool); function listCount() external view returns (uint256); function listAt(uint256 _idx) external view returns (address); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "./interfaces/IStakingRewards.sol"; /// @title StakingRewards, A contract where users can stake a token X "stakingToken" and get Y..X..Z as rewards /// @notice Based on https://github.com/sushiswap/sushiswap/blob/master/contracts/MasterChef.sol but better contract StakingRewards is Ownable, ReentrancyGuard, IStakingRewards { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; modifier notStopped { require(!isStopped, "Rewards have stopped"); _; } modifier onlyRewardsPeriod { require(block.number < endBlock, "Rewards period ended"); _; } struct RewardInfo { IERC20 rewardToken; uint256 lastRewardBlock; // Last block number that reward token distribution occurs. uint256 rewardPerBlock; // How many reward tokens to distribute per block. uint256 totalRewards; uint256 accTokenPerShare; // Accumulated token per share, times 1e18. } RewardInfo[] private rewardInfo; IERC20 public immutable stakingToken; // token to be staked for rewards uint256 public immutable startBlock; // block number when reward period starts uint256 public endBlock; // block number when reward period ends // how many blocks to wait after owner can reclaim unclaimed tokens uint256 public immutable bufferBlocks; // indicates that rewards have stopped forever and can't be extended anymore // also means that owner recovered all unclaimed rewards after a certain amount of bufferBlocks has passed // new users won't be able to deposit and everyone left can withdraw his/her stake bool public isStopped; mapping(address => uint256) private userAmount; mapping(uint256 => mapping(address => uint256)) private rewardDebt; // rewardDebt[rewardId][user] = N mapping(uint256 => mapping(address => uint256)) private rewardPaid; // rewardPaid[rewardId][user] = N EnumerableSet.AddressSet private pooledTokens; uint8 private constant MAX_POOLED_TOKENS = 5; constructor( address _stakingToken, uint256 _startBlock, uint256 _endBlock, uint256 _bufferBlocks ) { _startBlock = (_startBlock == 0) ? block.number : _startBlock; require( _endBlock > block.number && _endBlock > _startBlock, "Invalid end block" ); stakingToken = IERC20(_stakingToken); startBlock = _startBlock; endBlock = _endBlock; bufferBlocks = _bufferBlocks; } /** * @notice Caller deposits the staking token to start earning rewards * @param _amount amount of staking token to deposit */ function deposit(uint256 _amount) external override notStopped nonReentrant { updateAllRewards(); uint256 _currentAmount = userAmount[msg.sender]; uint256 _balanceBefore = stakingToken.balanceOf(address(this)); stakingToken.safeTransferFrom(msg.sender, address(this), _amount); _amount = stakingToken.balanceOf(address(this)) - _balanceBefore; uint256 _newUserAmount = _currentAmount + _amount; if (_currentAmount > 0) { for (uint256 i = 0; i < rewardInfo.length; i++) { RewardInfo memory _reward = rewardInfo[i]; uint256 _pending = ((_currentAmount * _reward.accTokenPerShare) / 1e18) - rewardDebt[i][msg.sender]; rewardDebt[i][msg.sender] = (_newUserAmount * _reward.accTokenPerShare) / 1e18; rewardPaid[i][msg.sender] += _pending; _reward.rewardToken.safeTransfer(msg.sender, _pending); } } else { for (uint256 i = 0; i < rewardInfo.length; i++) { RewardInfo memory _reward = rewardInfo[i]; rewardDebt[i][msg.sender] = (_amount * _reward.accTokenPerShare) / 1e18; } } userAmount[msg.sender] = _newUserAmount; emit Deposit(msg.sender, _amount); } /** * @notice Caller withdraws the staking token and its pending rewards, if any * @param _amount amount of staking token to withdraw */ function withdraw(uint256 _amount) external override nonReentrant { updateAllRewards(); uint256 _currentAmount = userAmount[msg.sender]; require(_currentAmount >= _amount, "withdraw: not good"); uint256 newUserAmount = _currentAmount - _amount; if (!isStopped) { for (uint256 i = 0; i < rewardInfo.length; i++) { RewardInfo memory _reward = rewardInfo[i]; uint256 _pending = ((_currentAmount * _reward.accTokenPerShare) / 1e18) - rewardDebt[i][msg.sender]; rewardDebt[i][msg.sender] = (newUserAmount * _reward.accTokenPerShare) / 1e18; rewardPaid[i][msg.sender] += _pending; _reward.rewardToken.safeTransfer(msg.sender, _pending); } } userAmount[msg.sender] = newUserAmount; stakingToken.safeTransfer(msg.sender, _amount); emit Withdraw(msg.sender, _amount); } /** * @notice Caller withdraws tokens staked by user without caring about rewards */ function emergencyWithdraw() external override nonReentrant { for (uint256 i = 0; i < rewardInfo.length; i++) { rewardDebt[i][msg.sender] = 0; } stakingToken.safeTransfer(msg.sender, userAmount[msg.sender]); userAmount[msg.sender] = 0; emit EmergencyWithdraw(msg.sender, userAmount[msg.sender]); } /** * @notice Caller claims its pending rewards without having to withdraw its stake */ function claimRewards() external override notStopped nonReentrant { for (uint256 i = 0; i < rewardInfo.length; i++) _claimReward(i); } /** * @notice Caller claims a single pending reward without having to withdraw its stake * @dev _rid is the index of rewardInfo array * @param _rid reward id */ function claimReward(uint256 _rid) external override notStopped nonReentrant { _claimReward(_rid); } /** * @notice Adds a reward token to the pool, only contract owner can call this * @param _rewardToken address of the ERC20 token * @param _totalRewards amount of total rewards to distribute from startBlock to endBlock */ function add(IERC20 _rewardToken, uint256 _totalRewards) external override nonReentrant onlyOwner onlyRewardsPeriod { require(rewardInfo.length < MAX_POOLED_TOKENS, "Pool is full"); _add(_rewardToken, _totalRewards); } /** * @notice Adds multiple reward tokens to the pool in a single call, only contract owner can call this * @param _rewardSettings array of struct composed of "IERC20 rewardToken" and "uint256 totalRewards" */ function addMulti(RewardSettings[] memory _rewardSettings) external override nonReentrant onlyOwner onlyRewardsPeriod { require( rewardInfo.length + _rewardSettings.length < MAX_POOLED_TOKENS, "Pool is full" ); for (uint8 i = 0; i < _rewardSettings.length; i++) _add( _rewardSettings[i].rewardToken, _rewardSettings[i].totalRewards ); } /** * @notice Owner can recover any ERC20 that's not the staking token neither a pooledToken * @param _tokenAddress address of the ERC20 mistakenly sent to this contract * @param _tokenAmount amount to recover */ function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external override onlyOwner { require( _tokenAddress != address(stakingToken) && !pooledTokens.contains(_tokenAddress), "Cannot recover" ); IERC20(_tokenAddress).safeTransfer(msg.sender, _tokenAmount); emit Recovered(_tokenAddress, _tokenAmount); } /** * @notice Owner can recover rewards that's not been claimed after endBlock + bufferBlocks * @dev Warning: it will set isStopped to true, so no more deposits, extensions or rewards claim but only withdrawals */ function recoverUnclaimedRewards() external override onlyOwner notStopped { require( block.number > endBlock + bufferBlocks, "Not allowed to reclaim" ); isStopped = true; for (uint8 i = 0; i < rewardInfo.length; i++) { IERC20 _token = IERC20(rewardInfo[i].rewardToken); uint256 _amount = _token.balanceOf(address(this)); rewardInfo[i].lastRewardBlock = block.number; _token.safeTransfer(msg.sender, _amount); emit UnclaimedRecovered(address(_token), _amount); } } /** * @notice After a reward period has ended owner can decide to extend it by adding more rewards * @dev totalRewards will be distributed from block.number to newEndBlock * @param _newEndBlock block number when new rewards end * @param _newTotalRewards array of new total rewards for each pooled token */ function extendRewards( uint256 _newEndBlock, uint256[] memory _newTotalRewards ) external override onlyOwner notStopped nonReentrant { require(block.number > endBlock, "Rewards not ended"); require(_newEndBlock > block.number, "Invalid end block"); require( _newTotalRewards.length == rewardInfo.length, "Pool length mismatch" ); for (uint8 i = 0; i < _newTotalRewards.length; i++) { updateReward(i); uint256 _balanceBefore = IERC20(rewardInfo[i].rewardToken).balanceOf(address(this)); IERC20(rewardInfo[i].rewardToken).safeTransferFrom( msg.sender, address(this), _newTotalRewards[i] ); _newTotalRewards[i] = IERC20(rewardInfo[i].rewardToken).balanceOf(address(this)) - _balanceBefore; uint256 _rewardPerBlock = _newTotalRewards[i] / (_newEndBlock - block.number); rewardInfo[i].rewardPerBlock = _rewardPerBlock; rewardInfo[i].totalRewards += _newTotalRewards[i]; } endBlock = _newEndBlock; emit RewardsExtended(_newEndBlock); } /** * @notice Gets the number of pooled reward tokens in contract */ function rewardsLength() external view override returns (uint256) { return rewardInfo.length; } /** * @notice Gets the amount of staked tokens for a given user * @param _user address of given user */ function balanceOf(address _user) external view override returns (uint256) { return userAmount[_user]; } /** * @notice Gets the total amount of staked tokens in contract */ function totalSupply() external view override returns (uint256) { return stakingToken.balanceOf(address(this)); } /** * @notice Caller can see pending rewards for a given reward id and user * @dev _rid is the index of rewardInfo array * @param _rid reward id * @param _user address of a user * @return amount of pending rewards */ function getPendingRewards(uint256 _rid, address _user) external view override returns (uint256) { return _getPendingRewards(_rid, _user); } /** * @notice Caller can see pending rewards for a given user * @param _user address of a user * @return array of struct containing rewardToken and pendingReward */ function getAllPendingRewards(address _user) external view override returns (PendingRewards[] memory) { PendingRewards[] memory _pendingRewards = new PendingRewards[](rewardInfo.length); for (uint8 i = 0; i < rewardInfo.length; i++) { _pendingRewards[i] = PendingRewards({ rewardToken: rewardInfo[i].rewardToken, pendingReward: _getPendingRewards(i, _user) }); } return _pendingRewards; } /** * @notice Caller can see pending rewards for a given user * @param _user address of a user * @return array of struct containing rewardToken and pendingReward */ function earned(address _user) external view override returns (EarnedRewards[] memory) { EarnedRewards[] memory earnedRewards = new EarnedRewards[](rewardInfo.length); for (uint8 i = 0; i < rewardInfo.length; i++) { earnedRewards[i] = EarnedRewards({ rewardToken: rewardInfo[i].rewardToken, earnedReward: rewardPaid[i][_user] + _getPendingRewards(i, _user) }); } return earnedRewards; } /** * @notice Caller can see total rewards for every pooled token * @return array of struct containing rewardToken and totalRewards */ function getRewardsForDuration() external view override returns (RewardSettings[] memory) { RewardSettings[] memory _rewardSettings = new RewardSettings[](rewardInfo.length); for (uint8 i = 0; i < rewardInfo.length; i++) { _rewardSettings[i] = RewardSettings({ rewardToken: rewardInfo[i].rewardToken, totalRewards: rewardInfo[i].totalRewards }); } return _rewardSettings; } /** * @notice Update reward variables of the given pool to be up-to-date. * @dev _rid is the index of rewardInfo array * @param _rid reward id */ function updateReward(uint256 _rid) public { RewardInfo storage _reward = rewardInfo[_rid]; if (block.number <= _reward.lastRewardBlock) { return; } uint256 _lpSupply = stakingToken.balanceOf(address(this)); if (_lpSupply == 0) { _reward.lastRewardBlock = block.number; return; } uint256 _tokenReward = getMultiplier(_reward) * _reward.rewardPerBlock; _reward.accTokenPerShare += (_tokenReward * 1e18) / _lpSupply; _reward.lastRewardBlock = block.number; } /** * @notice Mass updates reward variables */ function updateAllRewards() public { uint256 _length = rewardInfo.length; for (uint256 pid = 0; pid < _length; pid++) { updateReward(pid); } } /** * @notice Gets the correct multiplier of rewardPerBlock for a given RewardInfo */ function getMultiplier(RewardInfo memory _reward) internal view returns (uint256 _multiplier) { uint256 _lastBlock = (block.number > endBlock) ? endBlock : block.number; _multiplier = (_lastBlock > _reward.lastRewardBlock) ? _lastBlock - _reward.lastRewardBlock : 0; } /** * @notice Pending rewards for a given reward id and user * @dev _rid is the index of rewardInfo array * @param _rid reward id * @param _user address of a user * @return amount of pending rewards */ function _getPendingRewards(uint256 _rid, address _user) internal view returns (uint256) { if (isStopped) return 0; RewardInfo storage _reward = rewardInfo[_rid]; uint256 _amount = userAmount[_user]; uint256 _debt = rewardDebt[_rid][_user]; uint256 _rewardPerBlock = _reward.rewardPerBlock; uint256 _accTokenPerShare = _reward.accTokenPerShare; uint256 _lpSupply = stakingToken.balanceOf(address(this)); if (block.number > _reward.lastRewardBlock && _lpSupply != 0) { uint256 reward = getMultiplier(_reward) * _rewardPerBlock; _accTokenPerShare += ((reward * 1e18) / _lpSupply); } return ((_amount * _accTokenPerShare) / 1e18) - _debt; } /** * @notice Adds a reward token to the rewards pool * @param _rewardToken address of the ERC20 token * @param _totalRewards amount of total rewards to distribute from startBlock to endBlock */ function _add(IERC20 _rewardToken, uint256 _totalRewards) internal { require( address(_rewardToken) != address(stakingToken), "rewardToken = stakingToken" ); require(!pooledTokens.contains(address(_rewardToken)), "pool exists"); uint256 _balanceBefore = _rewardToken.balanceOf(address(this)); _rewardToken.safeTransferFrom(msg.sender, address(this), _totalRewards); _totalRewards = _rewardToken.balanceOf(address(this)) - _balanceBefore; require(_totalRewards != 0, "No rewards"); uint256 _lastRewardBlock = block.number > startBlock ? block.number : startBlock; pooledTokens.add(address(_rewardToken)); uint256 _rewardPerBlock = _totalRewards / (endBlock - _lastRewardBlock); rewardInfo.push( RewardInfo({ rewardToken: _rewardToken, rewardPerBlock: _rewardPerBlock, totalRewards: _totalRewards, lastRewardBlock: _lastRewardBlock, accTokenPerShare: 0 }) ); } /** * @notice Caller claims a single pending reward without having to withdraw its stake * @dev _rid is the index of rewardInfo array * @param _rid reward id */ function _claimReward(uint256 _rid) internal { updateReward(_rid); uint256 _amount = userAmount[msg.sender]; uint256 _debt = rewardDebt[_rid][msg.sender]; RewardInfo memory _reward = rewardInfo[_rid]; uint256 pending = ((_amount * _reward.accTokenPerShare) / 1e18) - _debt; rewardPaid[_rid][msg.sender] += pending; rewardDebt[_rid][msg.sender] = (_amount * _reward.accTokenPerShare) / 1e18; _reward.rewardToken.safeTransfer(msg.sender, pending); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; struct RewardSettings { IERC20 rewardToken; uint256 totalRewards; } struct PendingRewards { IERC20 rewardToken; uint256 pendingReward; } struct EarnedRewards { IERC20 rewardToken; uint256 earnedReward; } interface IStakingRewards { event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); event Recovered(address token, uint256 amount); event UnclaimedRecovered(address token, uint256 amount); event RewardsExtended(uint256 newEndBlock); function deposit(uint256 _amount) external; function withdraw(uint256 _amount) external; function emergencyWithdraw() external; function claimRewards() external; function claimReward(uint256 _rid) external; function add(IERC20 _rewardToken, uint256 _totalRewards) external; function addMulti(RewardSettings[] memory _poolSettings) external; function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external; function recoverUnclaimedRewards() external; function extendRewards( uint256 _newEndBlock, uint256[] memory _newTotalRewards ) external; function rewardsLength() external view returns (uint256); function balanceOf(address _user) external view returns (uint256); function totalSupply() external view returns (uint256); function getPendingRewards(uint256 _rid, address _user) external view returns (uint256); function getAllPendingRewards(address _user) external view returns (PendingRewards[] memory); function getRewardsForDuration() external view returns (RewardSettings[] memory); function earned(address _user) external view returns (EarnedRewards[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
Gets the number of pooled reward tokens in contract/
function rewardsLength() external view override returns (uint256) { return rewardInfo.length; }
10,130,558
./full_match/97/0xa650d5fB7002a35d9370Efdad2a0888Ecc252E98/sources/contracts/Darbi/UPMintDarbi.sol
Permissioned function to update the address of the UP Controller _upController - the address of the new UP Controller
function updateController(address _upController) public onlyAdmin { require(_upController != address(0), "INVALID_ADDRESS"); UP_CONTROLLER = payable(_upController); emit UpdateController(_upController); }
5,034,551
// File: @openzeppelin\contracts\token\ERC20\IERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: node_modules\@openzeppelin\contracts\math\SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: node_modules\@openzeppelin\contracts\utils\Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin\contracts\token\ERC20\SafeERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin\contracts\utils\ReentrancyGuard.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: node_modules\@openzeppelin\contracts\GSN\Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin\contracts\access\Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: node_modules\@openzeppelin\contracts\token\ERC20\ERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view 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 { } } // File: @openzeppelin\contracts\token\ERC20\ERC20Burnable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // File: contracts\SHEESHA.sol pragma solidity 0.7.6; contract SHEESHA is ERC20Burnable, Ownable { using SafeMath for uint256; //100,000 tokens uint256 public constant initialSupply = 100000e18; address public devAddress; address public teamAddress; address public marketingAddress; address public reserveAddress; bool public vaultTransferDone; bool public vaultLPTransferDone; // 15% team (4% monthly unlock over 25 months) // 10% dev // 10% marketing // 15% liquidity provision // 10% SHEESHA staking rewards // 20% LP rewards // 20% Reserve constructor(address _devAddress, address _marketingAddress, address _teamAddress, address _reserveAddress) ERC20("Sheesha Finance", "SHEESHA") { devAddress = _devAddress; marketingAddress = _marketingAddress; teamAddress = _teamAddress; reserveAddress = _reserveAddress; _mint(address(this), initialSupply); _transfer(address(this), devAddress, initialSupply.mul(10).div(100)); _transfer(address(this), teamAddress, initialSupply.mul(15).div(100)); _transfer(address(this), marketingAddress, initialSupply.mul(10).div(100)); _transfer(address(this), reserveAddress, initialSupply.mul(20).div(100)); } //one time only function transferVaultRewards(address _vaultAddress) public onlyOwner { require(!vaultTransferDone, "Already transferred"); _transfer(address(this), _vaultAddress, initialSupply.mul(10).div(100)); vaultTransferDone = true; } //one time only function transferVaultLPRewards(address _vaultLPAddress) public onlyOwner { require(!vaultLPTransferDone, "Already transferred"); _transfer(address(this), _vaultLPAddress, initialSupply.mul(20).div(100)); vaultLPTransferDone = true; } } // File: contracts\SHEESHAVaultLP.sol pragma solidity 0.7.6; contract SHEESHAVaultLP is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 checkpoint; //time user staked bool status; //true-> user existing | false-> not // // We do some fancy math here. Basically, any point in time, the amount of SHEESHAs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSheeshaPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSheeshaPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of token/LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SHEESHAs to distribute per block. uint256 lastRewardBlock; // Last block number that SHEESHAs distribution occurs. uint256 accSheeshaPerShare; // Accumulated SHEESHAs per share, times 1e12. See below. } // The SHEESHA TOKEN! SHEESHA public sheesha; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; // The block number when SHEESHA mining starts. uint256 public startBlock; // SHEESHA tokens percenatge created per block based on rewards pool- 0.01% uint256 public constant sheeshaPerBlock = 1; //handle case till 0.01(2 decimal places) uint256 public constant percentageDivider = 10000; //20,000 sheesha 20% of supply uint256 public lpRewards = 20000e18; address public feeWallet = 0x5483d944038189B4232d1E35367420989E2C3762; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor( SHEESHA _sheesha ) { sheesha = _sheesha; startBlock = block.number; IERC20(sheesha).safeApprove(msg.sender, uint256(-1)); } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSheeshaPerShare: 0 }) ); } // Update the given pool's SHEESHA allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 sheeshaReward = (lpRewards.mul(sheeshaPerBlock).div(percentageDivider)).mul(pool.allocPoint).div(totalAllocPoint); lpRewards = lpRewards.sub(sheeshaReward); pool.accSheeshaPerShare = pool.accSheeshaPerShare.add(sheeshaReward.mul(1e12).div(lpSupply)); } // Deposit LP tokens to MasterChef for SHEESHA allocation. function deposit(uint256 _pid, uint256 _amount) public { _deposit(msg.sender, _pid, _amount); } // stake from LGE directly // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function depositFor(address _depositFor, uint256 _pid, uint256 _amount) public { _deposit(_depositFor, _pid, _amount); } function _deposit(address _depositFor, uint256 _pid, uint256 _amount) internal nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_depositFor]; updatePool(_pid); if(!isActive(_pid, _depositFor)) { user.status = true; user.checkpoint = block.timestamp; } if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accSheeshaPerShare).div(1e12).sub(user.rewardDebt); safeSheeshaTransfer(_depositFor, pending); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // This is depositedFor address } user.rewardDebt = user.amount.mul(pool.accSheeshaPerShare).div(1e12); /// This is deposited for address emit Deposit(_depositFor, _pid, _amount); } // Withdraw LP tokens or claim rewrads if amount is 0 function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accSheeshaPerShare).div(1e12).sub(user.rewardDebt); safeSheeshaTransfer(msg.sender, pending); if(_amount > 0) { uint256 feePercent = 4; //2 years if(user.checkpoint.add(730 days) <= block.timestamp) { //4-> unstake fee interval feePercent = uint256(100).sub(getElapsedMonthsCount(user.checkpoint).mul(4)); } uint256 fees = _amount.mul(feePercent).div(100); user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(feeWallet, fees); pool.lpToken.safeTransfer(address(msg.sender), _amount.sub(fees)); } user.rewardDebt = user.amount.mul(pool.accSheeshaPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } //user must approve this contract to add rewards function addRewards(uint256 _amount) public onlyOwner { require(_amount > 0, "Invalid amount"); IERC20(sheesha).safeTransferFrom(address(msg.sender), address(this), _amount); lpRewards = lpRewards.add(_amount); } // Safe sheesha transfer function, just in case if rounding error causes pool to not have enough SHEESHAs function safeSheeshaTransfer(address _to, uint256 _amount) internal { uint256 sheeshaBal = sheesha.balanceOf(address(this)); if (_amount > sheeshaBal) { sheesha.transfer(_to, sheeshaBal); } else { sheesha.transfer(_to, _amount); } } // View function to see pending SHEESHAs on frontend. function pendingSheesha(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSheeshaPerShare = pool.accSheeshaPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 sheeshaReward = (lpRewards.mul(sheeshaPerBlock).div(percentageDivider)).mul(pool.allocPoint).div(totalAllocPoint); accSheeshaPerShare = accSheeshaPerShare.add(sheeshaReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSheeshaPerShare).div(1e12).sub(user.rewardDebt); } function isActive(uint256 _pid, address _user) public view returns(bool) { return userInfo[_pid][_user].status; } function getElapsedMonthsCount(uint256 checkpoint) public view returns(uint256) { return ((block.timestamp.sub(checkpoint)).div(30 days)).add(1); } function changeFeeWallet(address _feeWallet) external onlyOwner { feeWallet = _feeWallet; } }
Safe sheesha transfer function, just in case if rounding error causes pool to not have enough SHEESHAs
function safeSheeshaTransfer(address _to, uint256 _amount) internal { uint256 sheeshaBal = sheesha.balanceOf(address(this)); if (_amount > sheeshaBal) { sheesha.transfer(_to, sheeshaBal); sheesha.transfer(_to, _amount); } }
1,133,350
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './ERC20Base.sol'; import './ERC20ImplicitApprovalStorage.sol'; /** * @title ERC20 token with approval whitelist */ abstract contract ERC20ImplicitApproval is ERC20Base { /** * @inheritdoc ERC20Base */ function allowance ( address holder, address spender ) override public view returns (uint) { if (_isImplicitlyApproved(spender)) { return type(uint).max; } else { return super.allowance(holder, spender); } } /** * @inheritdoc ERC20Base */ function transferFrom ( address sender, address recipient, uint amount ) override public returns (bool) { if (_isImplicitlyApproved(msg.sender)) { _transfer(sender, recipient, amount); return true; } else { return super.transferFrom(sender, recipient, amount); } } /** * @notice get whether address is implicitly approved to spend tokens * @param account address to query * @return implicit approval status */ function _isImplicitlyApproved ( address account ) internal view returns (bool) { return ERC20ImplicitApprovalStorage.layout().implicitApprovals[account]; } }
get whether address is implicitly approved to spend tokens account address to query return implicit approval status/
function _isImplicitlyApproved ( address account ) internal view returns (bool) { return ERC20ImplicitApprovalStorage.layout().implicitApprovals[account]; }
12,741,208
pragma solidity ^0.5.0; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./ServiceTypeManager.sol"; import "./ClaimsManager.sol"; import "./Staking.sol"; /// @notice Governance imported via Staking.sol contract ServiceProviderFactory is InitializableV2 { using SafeMath for uint256; /// @dev - denominator for deployer cut calculations /// @dev - user values are intended to be x/DEPLOYER_CUT_BASE uint256 private constant DEPLOYER_CUT_BASE = 100; string private constant ERROR_ONLY_GOVERNANCE = ( "ServiceProviderFactory: Only callable by Governance contract" ); string private constant ERROR_ONLY_SP_GOVERNANCE = ( "ServiceProviderFactory: Only callable by Service Provider or Governance" ); address private stakingAddress; address private delegateManagerAddress; address private governanceAddress; address private serviceTypeManagerAddress; address private claimsManagerAddress; /// @notice Period in blocks that a decrease stake operation is delayed. /// Must be greater than governance votingPeriod + executionDelay in order to /// prevent pre-emptive withdrawal in anticipation of a slash proposal uint256 private decreaseStakeLockupDuration; /// @notice Period in blocks that an update deployer cut operation is delayed. /// Must be greater than funding round block diff in order /// to prevent manipulation around a funding round uint256 private deployerCutLockupDuration; /// @dev - Stores following entities /// 1) Directly staked amount by SP, not including delegators /// 2) % Cut of delegator tokens taken during reward /// 3) Bool indicating whether this SP has met min/max requirements /// 4) Number of endpoints registered by SP /// 5) Minimum deployer stake for this service provider /// 6) Maximum total stake for this account struct ServiceProviderDetails { uint256 deployerStake; uint256 deployerCut; bool validBounds; uint256 numberOfEndpoints; uint256 minAccountStake; uint256 maxAccountStake; } /// @dev - Data structure for time delay during withdrawal struct DecreaseStakeRequest { uint256 decreaseAmount; uint256 lockupExpiryBlock; } /// @dev - Data structure for time delay during deployer cut update struct UpdateDeployerCutRequest { uint256 newDeployerCut; uint256 lockupExpiryBlock; } /// @dev - Struct maintaining information about sp /// @dev - blocknumber is block.number when endpoint registered struct ServiceEndpoint { address owner; string endpoint; uint256 blocknumber; address delegateOwnerWallet; } /// @dev - Mapping of service provider address to details mapping(address => ServiceProviderDetails) private spDetails; /// @dev - Uniquely assigned serviceProvider ID, incremented for each service type /// @notice - Keeps track of the total number of services registered regardless of /// whether some have been deregistered since mapping(bytes32 => uint256) private serviceProviderTypeIDs; /// @dev - mapping of (serviceType -> (serviceInstanceId <-> serviceProviderInfo)) /// @notice - stores the actual service provider data like endpoint and owner wallet /// with the ability lookup by service type and service id */ mapping(bytes32 => mapping(uint256 => ServiceEndpoint)) private serviceProviderInfo; /// @dev - mapping of keccak256(endpoint) to uint256 ID /// @notice - used to check if a endpoint has already been registered and also lookup /// the id of an endpoint mapping(bytes32 => uint256) private serviceProviderEndpointToId; /// @dev - mapping of address -> sp id array */ /// @notice - stores all the services registered by a provider. for each address, /// provides the ability to lookup by service type and see all registered services mapping(address => mapping(bytes32 => uint256[])) private serviceProviderAddressToId; /// @dev - Mapping of service provider -> decrease stake request mapping(address => DecreaseStakeRequest) private decreaseStakeRequests; /// @dev - Mapping of service provider -> update deployer cut requests mapping(address => UpdateDeployerCutRequest) private updateDeployerCutRequests; event RegisteredServiceProvider( uint256 indexed _spID, bytes32 indexed _serviceType, address indexed _owner, string _endpoint, uint256 _stakeAmount ); event DeregisteredServiceProvider( uint256 indexed _spID, bytes32 indexed _serviceType, address indexed _owner, string _endpoint, uint256 _unstakeAmount ); event UpdatedStakeAmount( address indexed _owner, uint256 indexed _stakeAmount ); event EndpointUpdated( bytes32 indexed _serviceType, address indexed _owner, string _oldEndpoint, string _newEndpoint, uint256 indexed _spID ); event DelegateOwnerWalletUpdated( address indexed _owner, bytes32 indexed _serviceType, uint256 indexed _spID, address _updatedWallet ); event ServiceProviderCutUpdated( address indexed _owner, uint256 indexed _updatedCut ); event DecreaseStakeLockupDurationUpdated(uint256 indexed _lockupDuration); event UpdateDeployerCutLockupDurationUpdated(uint256 indexed _lockupDuration); event GovernanceAddressUpdated(address indexed _newGovernanceAddress); event StakingAddressUpdated(address indexed _newStakingAddress); event ClaimsManagerAddressUpdated(address indexed _newClaimsManagerAddress); event DelegateManagerAddressUpdated(address indexed _newDelegateManagerAddress); event ServiceTypeManagerAddressUpdated(address indexed _newServiceTypeManagerAddress); /** * @notice Function to initialize the contract * @dev stakingAddress must be initialized separately after Staking contract is deployed * @dev delegateManagerAddress must be initialized separately after DelegateManager contract is deployed * @dev serviceTypeManagerAddress must be initialized separately after ServiceTypeManager contract is deployed * @dev claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed * @param _governanceAddress - Governance proxy address */ function initialize ( address _governanceAddress, address _claimsManagerAddress, uint256 _decreaseStakeLockupDuration, uint256 _deployerCutLockupDuration ) public initializer { _updateGovernanceAddress(_governanceAddress); claimsManagerAddress = _claimsManagerAddress; _updateDecreaseStakeLockupDuration(_decreaseStakeLockupDuration); _updateDeployerCutLockupDuration(_deployerCutLockupDuration); InitializableV2.initialize(); } /** * @notice Register a new endpoint to the account of msg.sender * @dev Transfers stake from service provider into staking pool * @param _serviceType - type of service to register, must be valid in ServiceTypeManager * @param _endpoint - url of the service to register - url of the service to register * @param _stakeAmount - amount to stake, must be within bounds in ServiceTypeManager * @param _delegateOwnerWallet - wallet to delegate some permissions for some basic management properties * @return New service provider ID for this endpoint */ function register( bytes32 _serviceType, string calldata _endpoint, uint256 _stakeAmount, address _delegateOwnerWallet ) external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceTypeManagerAddressIsSet(); _requireClaimsManagerAddressIsSet(); require( ServiceTypeManager(serviceTypeManagerAddress).serviceTypeIsValid(_serviceType), "ServiceProviderFactory: Valid service type required"); // Stake token amount from msg.sender if (_stakeAmount > 0) { require( !_claimPending(msg.sender), "ServiceProviderFactory: No pending claim expected" ); Staking(stakingAddress).stakeFor(msg.sender, _stakeAmount); } require ( serviceProviderEndpointToId[keccak256(bytes(_endpoint))] == 0, "ServiceProviderFactory: Endpoint already registered"); uint256 newServiceProviderID = serviceProviderTypeIDs[_serviceType].add(1); serviceProviderTypeIDs[_serviceType] = newServiceProviderID; // Index spInfo serviceProviderInfo[_serviceType][newServiceProviderID] = ServiceEndpoint({ owner: msg.sender, endpoint: _endpoint, blocknumber: block.number, delegateOwnerWallet: _delegateOwnerWallet }); // Update endpoint mapping serviceProviderEndpointToId[keccak256(bytes(_endpoint))] = newServiceProviderID; // Update (address -> type -> ids[]) serviceProviderAddressToId[msg.sender][_serviceType].push(newServiceProviderID); // Increment number of endpoints for this address spDetails[msg.sender].numberOfEndpoints = spDetails[msg.sender].numberOfEndpoints.add(1); // Update deployer total spDetails[msg.sender].deployerStake = ( spDetails[msg.sender].deployerStake.add(_stakeAmount) ); // Update min and max totals for this service provider (, uint256 typeMin, uint256 typeMax) = ServiceTypeManager( serviceTypeManagerAddress ).getServiceTypeInfo(_serviceType); spDetails[msg.sender].minAccountStake = spDetails[msg.sender].minAccountStake.add(typeMin); spDetails[msg.sender].maxAccountStake = spDetails[msg.sender].maxAccountStake.add(typeMax); // Confirm both aggregate account balance and directly staked amount are valid this.validateAccountStakeBalance(msg.sender); uint256 currentlyStakedForOwner = Staking(stakingAddress).totalStakedFor(msg.sender); // Indicate this service provider is within bounds spDetails[msg.sender].validBounds = true; emit RegisteredServiceProvider( newServiceProviderID, _serviceType, msg.sender, _endpoint, currentlyStakedForOwner ); return newServiceProviderID; } /** * @notice Deregister an endpoint from the account of msg.sender * @dev Unstakes all tokens for service provider if this is the last endpoint * @param _serviceType - type of service to deregister * @param _endpoint - endpoint to deregister * @return spId of the service that was deregistered */ function deregister( bytes32 _serviceType, string calldata _endpoint ) external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceTypeManagerAddressIsSet(); // Unstake on deregistration if and only if this is the last service endpoint uint256 unstakeAmount = 0; bool unstaked = false; // owned by the service provider if (spDetails[msg.sender].numberOfEndpoints == 1) { unstakeAmount = spDetails[msg.sender].deployerStake; // Submit request to decrease stake, overriding any pending request decreaseStakeRequests[msg.sender] = DecreaseStakeRequest({ decreaseAmount: unstakeAmount, lockupExpiryBlock: block.number.add(decreaseStakeLockupDuration) }); unstaked = true; } require ( serviceProviderEndpointToId[keccak256(bytes(_endpoint))] != 0, "ServiceProviderFactory: Endpoint not registered"); // Cache invalided service provider ID uint256 deregisteredID = serviceProviderEndpointToId[keccak256(bytes(_endpoint))]; // Update endpoint mapping serviceProviderEndpointToId[keccak256(bytes(_endpoint))] = 0; require( keccak256(bytes(serviceProviderInfo[_serviceType][deregisteredID].endpoint)) == keccak256(bytes(_endpoint)), "ServiceProviderFactory: Invalid endpoint for service type"); require ( serviceProviderInfo[_serviceType][deregisteredID].owner == msg.sender, "ServiceProviderFactory: Only callable by endpoint owner"); // Update info mapping delete serviceProviderInfo[_serviceType][deregisteredID]; // Reset id, update array uint256 spTypeLength = serviceProviderAddressToId[msg.sender][_serviceType].length; for (uint256 i = 0; i < spTypeLength; i ++) { if (serviceProviderAddressToId[msg.sender][_serviceType][i] == deregisteredID) { // Overwrite element to be deleted with last element in array serviceProviderAddressToId[msg.sender][_serviceType][i] = serviceProviderAddressToId[msg.sender][_serviceType][spTypeLength - 1]; // Reduce array size, exit loop serviceProviderAddressToId[msg.sender][_serviceType].length--; // Confirm this ID has been found for the service provider break; } } // Decrement number of endpoints for this address spDetails[msg.sender].numberOfEndpoints -= 1; // Update min and max totals for this service provider (, uint256 typeMin, uint256 typeMax) = ServiceTypeManager( serviceTypeManagerAddress ).getServiceTypeInfo(_serviceType); spDetails[msg.sender].minAccountStake = spDetails[msg.sender].minAccountStake.sub(typeMin); spDetails[msg.sender].maxAccountStake = spDetails[msg.sender].maxAccountStake.sub(typeMax); emit DeregisteredServiceProvider( deregisteredID, _serviceType, msg.sender, _endpoint, unstakeAmount); // Confirm both aggregate account balance and directly staked amount are valid // Only if unstake operation has not occurred if (!unstaked) { this.validateAccountStakeBalance(msg.sender); // Indicate this service provider is within bounds spDetails[msg.sender].validBounds = true; } return deregisteredID; } /** * @notice Increase stake for service provider * @param _increaseStakeAmount - amount to increase staked amount by * @return New total stake for service provider */ function increaseStake( uint256 _increaseStakeAmount ) external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireClaimsManagerAddressIsSet(); // Confirm owner has an endpoint require( spDetails[msg.sender].numberOfEndpoints > 0, "ServiceProviderFactory: Registered endpoint required to increase stake" ); require( !_claimPending(msg.sender), "ServiceProviderFactory: No claim expected to be pending prior to stake transfer" ); Staking stakingContract = Staking( stakingAddress ); // Stake increased token amount for msg.sender stakingContract.stakeFor(msg.sender, _increaseStakeAmount); uint256 newStakeAmount = stakingContract.totalStakedFor(msg.sender); // Update deployer total spDetails[msg.sender].deployerStake = ( spDetails[msg.sender].deployerStake.add(_increaseStakeAmount) ); // Confirm both aggregate account balance and directly staked amount are valid this.validateAccountStakeBalance(msg.sender); // Indicate this service provider is within bounds spDetails[msg.sender].validBounds = true; emit UpdatedStakeAmount( msg.sender, newStakeAmount ); return newStakeAmount; } /** * @notice Request to decrease stake. This sets a lockup for decreaseStakeLockupDuration after which the actual decreaseStake can be called * @dev Decreasing stake is only processed if a service provider is within valid bounds * @param _decreaseStakeAmount - amount to decrease stake by in wei * @return New total stake amount after the lockup */ function requestDecreaseStake(uint256 _decreaseStakeAmount) external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireClaimsManagerAddressIsSet(); require( _decreaseStakeAmount > 0, "ServiceProviderFactory: Requested stake decrease amount must be greater than zero" ); require( !_claimPending(msg.sender), "ServiceProviderFactory: No claim expected to be pending prior to stake transfer" ); Staking stakingContract = Staking( stakingAddress ); uint256 currentStakeAmount = stakingContract.totalStakedFor(msg.sender); // Prohibit decreasing stake to invalid bounds _validateBalanceInternal(msg.sender, (currentStakeAmount.sub(_decreaseStakeAmount))); decreaseStakeRequests[msg.sender] = DecreaseStakeRequest({ decreaseAmount: _decreaseStakeAmount, lockupExpiryBlock: block.number.add(decreaseStakeLockupDuration) }); return currentStakeAmount.sub(_decreaseStakeAmount); } /** * @notice Cancel a decrease stake request during the lockup * @dev Either called by the service provider via DelegateManager or governance during a slash action * @param _account - address of service provider */ function cancelDecreaseStakeRequest(address _account) external { _requireIsInitialized(); _requireDelegateManagerAddressIsSet(); require( msg.sender == _account || msg.sender == delegateManagerAddress, "ServiceProviderFactory: Only owner or DelegateManager" ); require( _decreaseRequestIsPending(_account), "ServiceProviderFactory: Decrease stake request must be pending" ); // Clear decrease stake request decreaseStakeRequests[_account] = DecreaseStakeRequest({ decreaseAmount: 0, lockupExpiryBlock: 0 }); } /** * @notice Called by user to decrease a stake after waiting the appropriate lockup period. * @return New total stake after decrease */ function decreaseStake() external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); require( _decreaseRequestIsPending(msg.sender), "ServiceProviderFactory: Decrease stake request must be pending" ); require( decreaseStakeRequests[msg.sender].lockupExpiryBlock <= block.number, "ServiceProviderFactory: Lockup must be expired" ); Staking stakingContract = Staking( stakingAddress ); // Decrease staked token amount for msg.sender stakingContract.unstakeFor(msg.sender, decreaseStakeRequests[msg.sender].decreaseAmount); // Query current stake uint256 newStakeAmount = stakingContract.totalStakedFor(msg.sender); // Update deployer total spDetails[msg.sender].deployerStake = ( spDetails[msg.sender].deployerStake.sub(decreaseStakeRequests[msg.sender].decreaseAmount) ); // Confirm both aggregate account balance and directly staked amount are valid // During registration this validation is bypassed since no endpoints remain if (spDetails[msg.sender].numberOfEndpoints > 0) { this.validateAccountStakeBalance(msg.sender); } // Indicate this service provider is within bounds spDetails[msg.sender].validBounds = true; // Clear decrease stake request delete decreaseStakeRequests[msg.sender]; emit UpdatedStakeAmount( msg.sender, newStakeAmount ); return newStakeAmount; } /** * @notice Update delegate owner wallet for a given endpoint * @param _serviceType - type of service to register, must be valid in ServiceTypeManager * @param _endpoint - url of the service to register - url of the service to register * @param _updatedDelegateOwnerWallet - address of new delegate wallet */ function updateDelegateOwnerWallet( bytes32 _serviceType, string calldata _endpoint, address _updatedDelegateOwnerWallet ) external { _requireIsInitialized(); uint256 spID = this.getServiceProviderIdFromEndpoint(_endpoint); require( serviceProviderInfo[_serviceType][spID].owner == msg.sender, "ServiceProviderFactory: Invalid update operation, wrong owner" ); serviceProviderInfo[_serviceType][spID].delegateOwnerWallet = _updatedDelegateOwnerWallet; emit DelegateOwnerWalletUpdated( msg.sender, _serviceType, spID, _updatedDelegateOwnerWallet ); } /** * @notice Update the endpoint for a given service * @param _serviceType - type of service to register, must be valid in ServiceTypeManager * @param _oldEndpoint - old endpoint currently registered * @param _newEndpoint - new endpoint to replace old endpoint * @return ID of updated service provider */ function updateEndpoint( bytes32 _serviceType, string calldata _oldEndpoint, string calldata _newEndpoint ) external returns (uint256) { _requireIsInitialized(); uint256 spId = this.getServiceProviderIdFromEndpoint(_oldEndpoint); require ( spId != 0, "ServiceProviderFactory: Could not find service provider with that endpoint" ); ServiceEndpoint memory serviceEndpoint = serviceProviderInfo[_serviceType][spId]; require( serviceEndpoint.owner == msg.sender, "ServiceProviderFactory: Invalid update endpoint operation, wrong owner" ); require( keccak256(bytes(serviceEndpoint.endpoint)) == keccak256(bytes(_oldEndpoint)), "ServiceProviderFactory: Old endpoint doesn't match what's registered for the service provider" ); // invalidate old endpoint serviceProviderEndpointToId[keccak256(bytes(serviceEndpoint.endpoint))] = 0; // update to new endpoint serviceEndpoint.endpoint = _newEndpoint; serviceProviderInfo[_serviceType][spId] = serviceEndpoint; serviceProviderEndpointToId[keccak256(bytes(_newEndpoint))] = spId; emit EndpointUpdated(_serviceType, msg.sender, _oldEndpoint, _newEndpoint, spId); return spId; } /** * @notice Update the deployer cut for a given service provider * @param _serviceProvider - address of service provider * @param _cut - new value for deployer cut */ function requestUpdateDeployerCut(address _serviceProvider, uint256 _cut) external { _requireIsInitialized(); require( msg.sender == _serviceProvider || msg.sender == governanceAddress, ERROR_ONLY_SP_GOVERNANCE ); require( (updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock == 0) && (updateDeployerCutRequests[_serviceProvider].newDeployerCut == 0), "ServiceProviderFactory: Update deployer cut operation pending" ); require( _cut <= DEPLOYER_CUT_BASE, "ServiceProviderFactory: Service Provider cut cannot exceed base value" ); updateDeployerCutRequests[_serviceProvider] = UpdateDeployerCutRequest({ lockupExpiryBlock: block.number + deployerCutLockupDuration, newDeployerCut: _cut }); } /** * @notice Cancel a pending request to update deployer cut * @param _serviceProvider - address of service provider */ function cancelUpdateDeployerCut(address _serviceProvider) external { _requireIsInitialized(); _requirePendingDeployerCutOperation(_serviceProvider); require( msg.sender == _serviceProvider || msg.sender == governanceAddress, ERROR_ONLY_SP_GOVERNANCE ); // Zero out request information delete updateDeployerCutRequests[_serviceProvider]; } /** * @notice Evalue request to update service provider cut of claims * @notice Update service provider cut as % of delegate claim, divided by the deployerCutBase. * @dev SPs will interact with this value as a percent, value translation done client side @dev A value of 5 dictates a 5% cut, with ( 5 / 100 ) * delegateReward going to an SP from each delegator each round. */ function updateDeployerCut(address _serviceProvider) external { _requireIsInitialized(); _requirePendingDeployerCutOperation(_serviceProvider); require( msg.sender == _serviceProvider || msg.sender == governanceAddress, ERROR_ONLY_SP_GOVERNANCE ); require( updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock <= block.number, "ServiceProviderFactory: Lockup must be expired" ); spDetails[_serviceProvider].deployerCut = ( updateDeployerCutRequests[_serviceProvider].newDeployerCut ); // Zero out request information delete updateDeployerCutRequests[_serviceProvider]; emit ServiceProviderCutUpdated(_serviceProvider, spDetails[_serviceProvider].deployerCut); } /** * @notice Update service provider balance * @dev Called by DelegateManager by functions modifying entire stake like claim and slash * @param _serviceProvider - address of service provider * @param _amount - new amount of direct state for service provider */ function updateServiceProviderStake( address _serviceProvider, uint256 _amount ) external { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireDelegateManagerAddressIsSet(); require( msg.sender == delegateManagerAddress, "ServiceProviderFactory: only callable by DelegateManager" ); // Update SP tracked total spDetails[_serviceProvider].deployerStake = _amount; _updateServiceProviderBoundStatus(_serviceProvider); } /// @notice Update service provider lockup duration function updateDecreaseStakeLockupDuration(uint256 _duration) external { _requireIsInitialized(); require( msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE ); _updateDecreaseStakeLockupDuration(_duration); emit DecreaseStakeLockupDurationUpdated(_duration); } /// @notice Update service provider lockup duration function updateDeployerCutLockupDuration(uint256 _duration) external { _requireIsInitialized(); require( msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE ); _updateDeployerCutLockupDuration(_duration); emit UpdateDeployerCutLockupDurationUpdated(_duration); } /// @notice Get denominator for deployer cut calculations function getServiceProviderDeployerCutBase() external view returns (uint256) { _requireIsInitialized(); return DEPLOYER_CUT_BASE; } /// @notice Get current deployer cut update lockup duration function getDeployerCutLockupDuration() external view returns (uint256) { _requireIsInitialized(); return deployerCutLockupDuration; } /// @notice Get total number of service providers for a given serviceType function getTotalServiceTypeProviders(bytes32 _serviceType) external view returns (uint256) { _requireIsInitialized(); return serviceProviderTypeIDs[_serviceType]; } /// @notice Get service provider id for an endpoint function getServiceProviderIdFromEndpoint(string calldata _endpoint) external view returns (uint256) { _requireIsInitialized(); return serviceProviderEndpointToId[keccak256(bytes(_endpoint))]; } /** * @notice Get service provider ids for a given service provider and service type * @return List of service ids of that type for a service provider */ function getServiceProviderIdsFromAddress(address _ownerAddress, bytes32 _serviceType) external view returns (uint256[] memory) { _requireIsInitialized(); return serviceProviderAddressToId[_ownerAddress][_serviceType]; } /** * @notice Get information about a service endpoint given its service id * @param _serviceType - type of service, must be a valid service from ServiceTypeManager * @param _serviceId - id of service */ function getServiceEndpointInfo(bytes32 _serviceType, uint256 _serviceId) external view returns (address owner, string memory endpoint, uint256 blockNumber, address delegateOwnerWallet) { _requireIsInitialized(); ServiceEndpoint memory serviceEndpoint = serviceProviderInfo[_serviceType][_serviceId]; return ( serviceEndpoint.owner, serviceEndpoint.endpoint, serviceEndpoint.blocknumber, serviceEndpoint.delegateOwnerWallet ); } /** * @notice Get information about a service provider given their address * @param _serviceProvider - address of service provider */ function getServiceProviderDetails(address _serviceProvider) external view returns ( uint256 deployerStake, uint256 deployerCut, bool validBounds, uint256 numberOfEndpoints, uint256 minAccountStake, uint256 maxAccountStake) { _requireIsInitialized(); return ( spDetails[_serviceProvider].deployerStake, spDetails[_serviceProvider].deployerCut, spDetails[_serviceProvider].validBounds, spDetails[_serviceProvider].numberOfEndpoints, spDetails[_serviceProvider].minAccountStake, spDetails[_serviceProvider].maxAccountStake ); } /** * @notice Get information about pending decrease stake requests for service provider * @param _serviceProvider - address of service provider */ function getPendingDecreaseStakeRequest(address _serviceProvider) external view returns (uint256 amount, uint256 lockupExpiryBlock) { _requireIsInitialized(); return ( decreaseStakeRequests[_serviceProvider].decreaseAmount, decreaseStakeRequests[_serviceProvider].lockupExpiryBlock ); } /** * @notice Get information about pending decrease stake requests for service provider * @param _serviceProvider - address of service provider */ function getPendingUpdateDeployerCutRequest(address _serviceProvider) external view returns (uint256 newDeployerCut, uint256 lockupExpiryBlock) { _requireIsInitialized(); return ( updateDeployerCutRequests[_serviceProvider].newDeployerCut, updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock ); } /// @notice Get current unstake lockup duration function getDecreaseStakeLockupDuration() external view returns (uint256) { _requireIsInitialized(); return decreaseStakeLockupDuration; } /** * @notice Validate that the total service provider balance is between the min and max stakes for all their registered services and validate direct stake for sp is above minimum * @param _serviceProvider - address of service provider */ function validateAccountStakeBalance(address _serviceProvider) external view { _requireIsInitialized(); _requireStakingAddressIsSet(); _validateBalanceInternal( _serviceProvider, Staking(stakingAddress).totalStakedFor(_serviceProvider) ); } /// @notice Get the Governance address function getGovernanceAddress() external view returns (address) { _requireIsInitialized(); return governanceAddress; } /// @notice Get the Staking address function getStakingAddress() external view returns (address) { _requireIsInitialized(); return stakingAddress; } /// @notice Get the DelegateManager address function getDelegateManagerAddress() external view returns (address) { _requireIsInitialized(); return delegateManagerAddress; } /// @notice Get the ServiceTypeManager address function getServiceTypeManagerAddress() external view returns (address) { _requireIsInitialized(); return serviceTypeManagerAddress; } /// @notice Get the ClaimsManager address function getClaimsManagerAddress() external view returns (address) { _requireIsInitialized(); return claimsManagerAddress; } /** * @notice Set the Governance address * @dev Only callable by Governance address * @param _governanceAddress - address for new Governance contract */ function setGovernanceAddress(address _governanceAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateGovernanceAddress(_governanceAddress); emit GovernanceAddressUpdated(_governanceAddress); } /** * @notice Set the Staking address * @dev Only callable by Governance address * @param _address - address for new Staking contract */ function setStakingAddress(address _address) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); stakingAddress = _address; emit StakingAddressUpdated(_address); } /** * @notice Set the DelegateManager address * @dev Only callable by Governance address * @param _address - address for new DelegateManager contract */ function setDelegateManagerAddress(address _address) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); delegateManagerAddress = _address; emit DelegateManagerAddressUpdated(_address); } /** * @notice Set the ServiceTypeManager address * @dev Only callable by Governance address * @param _address - address for new ServiceTypeManager contract */ function setServiceTypeManagerAddress(address _address) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); serviceTypeManagerAddress = _address; emit ServiceTypeManagerAddressUpdated(_address); } /** * @notice Set the ClaimsManager address * @dev Only callable by Governance address * @param _address - address for new ClaimsManager contract */ function setClaimsManagerAddress(address _address) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); claimsManagerAddress = _address; emit ClaimsManagerAddressUpdated(_address); } // ========================================= Internal Functions ========================================= /** * @notice Update status in spDetails if the bounds for a service provider is valid */ function _updateServiceProviderBoundStatus(address _serviceProvider) internal { // Validate bounds for total stake uint256 totalSPStake = Staking(stakingAddress).totalStakedFor(_serviceProvider); if (totalSPStake < spDetails[_serviceProvider].minAccountStake || totalSPStake > spDetails[_serviceProvider].maxAccountStake) { // Indicate this service provider is out of bounds spDetails[_serviceProvider].validBounds = false; } else { // Indicate this service provider is within bounds spDetails[_serviceProvider].validBounds = true; } } /** * @notice Set the governance address after confirming contract identity * @param _governanceAddress - Incoming governance address */ function _updateGovernanceAddress(address _governanceAddress) internal { require( Governance(_governanceAddress).isGovernanceAddress() == true, "ServiceProviderFactory: _governanceAddress is not a valid governance contract" ); governanceAddress = _governanceAddress; } /** * @notice Set the deployer cut lockup duration * @param _duration - incoming duration */ function _updateDeployerCutLockupDuration(uint256 _duration) internal { require( ClaimsManager(claimsManagerAddress).getFundingRoundBlockDiff() < _duration, "ServiceProviderFactory: Incoming duration must be greater than funding round block diff" ); deployerCutLockupDuration = _duration; } /** * @notice Set the decrease stake lockup duration * @param _duration - incoming duration */ function _updateDecreaseStakeLockupDuration(uint256 _duration) internal { Governance governance = Governance(governanceAddress); require( _duration > governance.getVotingPeriod() + governance.getExecutionDelay(), "ServiceProviderFactory: decreaseStakeLockupDuration duration must be greater than governance votingPeriod + executionDelay" ); decreaseStakeLockupDuration = _duration; } /** * @notice Compare a given amount input against valid min and max bounds for service provider * @param _serviceProvider - address of service provider * @param _amount - amount in wei to compare */ function _validateBalanceInternal(address _serviceProvider, uint256 _amount) internal view { require( _amount <= spDetails[_serviceProvider].maxAccountStake, "ServiceProviderFactory: Maximum stake amount exceeded" ); require( spDetails[_serviceProvider].deployerStake >= spDetails[_serviceProvider].minAccountStake, "ServiceProviderFactory: Minimum stake requirement not met" ); } /** * @notice Get whether a decrease request has been initiated for service provider * @param _serviceProvider - address of service provider * return Boolean of whether decrease request has been initiated */ function _decreaseRequestIsPending(address _serviceProvider) internal view returns (bool) { return ( (decreaseStakeRequests[_serviceProvider].lockupExpiryBlock > 0) && (decreaseStakeRequests[_serviceProvider].decreaseAmount > 0) ); } /** * @notice Boolean indicating whether a claim is pending for this service provider */ /** * @notice Get whether a claim is pending for this service provider * @param _serviceProvider - address of service provider * return Boolean of whether claim is pending */ function _claimPending(address _serviceProvider) internal view returns (bool) { return ClaimsManager(claimsManagerAddress).claimPending(_serviceProvider); } // ========================================= Private Functions ========================================= function _requirePendingDeployerCutOperation (address _serviceProvider) private view { require( (updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock != 0), "ServiceProviderFactory: No update deployer cut operation pending" ); } function _requireStakingAddressIsSet() private view { require( stakingAddress != address(0x00), "ServiceProviderFactory: stakingAddress is not set" ); } function _requireDelegateManagerAddressIsSet() private view { require( delegateManagerAddress != address(0x00), "ServiceProviderFactory: delegateManagerAddress is not set" ); } function _requireServiceTypeManagerAddressIsSet() private view { require( serviceTypeManagerAddress != address(0x00), "ServiceProviderFactory: serviceTypeManagerAddress is not set" ); } function _requireClaimsManagerAddressIsSet() private view { require( claimsManagerAddress != address(0x00), "ServiceProviderFactory: claimsManagerAddress is not set" ); } }
_account - address of service provider/ Clear decrease stake request
function cancelDecreaseStakeRequest(address _account) external { _requireIsInitialized(); _requireDelegateManagerAddressIsSet(); require( msg.sender == _account || msg.sender == delegateManagerAddress, "ServiceProviderFactory: Only owner or DelegateManager" ); require( _decreaseRequestIsPending(_account), "ServiceProviderFactory: Decrease stake request must be pending" ); decreaseStakeRequests[_account] = DecreaseStakeRequest({ decreaseAmount: 0, lockupExpiryBlock: 0 }); }
12,851,836
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: IAaveIncentivesController interface IAaveIncentivesController { /** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @param user The address of the user * @return The rewards **/ function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); /** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); /** * @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller must * be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager * @param amount Amount of rewards to claim * @param user Address to check and claim rewards * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewardsOnBehalf( address[] calldata assets, uint256 amount, address user, address to ) external returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @return the unclaimed user rewards */ function getUserUnclaimedRewards(address user) external view returns (uint256); /** * @dev for backward compatibility with previous implementation of the Incentives controller */ function REWARD_TOKEN() external view returns (address); function getDistributionEnd() external view returns (uint256); function getAssetData(address asset) external view returns ( uint256, uint256, uint256 ); } // Part: ILendingPoolAddressesProvider /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } // Part: IOptionalERC20 interface IOptionalERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // Part: IPriceOracle interface IPriceOracle { function getAssetPrice(address _asset) external view returns (uint256); function getAssetsPrices(address[] calldata _assets) external view returns (uint256[] memory); function getSourceOfAsset(address _asset) external view returns (address); function getFallbackOracle() external view returns (address); } // Part: IReserveInterestRateStrategy /** * @title IReserveInterestRateStrategyInterface interface * @dev Interface for the calculation of the interest rates * @author Aave */ interface IReserveInterestRateStrategy { function OPTIMAL_UTILIZATION_RATE() external view returns (uint256); function EXCESS_UTILIZATION_RATE() external view returns (uint256); function variableRateSlope1() external view returns (uint256); function variableRateSlope2() external view returns (uint256); function baseVariableBorrowRate() external view returns (uint256); function getMaxVariableBorrowRate() external view returns (uint256); function calculateInterestRates( address reserve, uint256 utilizationRate, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view returns ( uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate ); } // Part: IScaledBalanceToken interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } // Part: IStakedAave interface IStakedAave { function stake(address to, uint256 amount) external; function redeem(address to, uint256 amount) external; function cooldown() external; function claimRewards(address to, uint256 amount) external; function getTotalRewardsBalance(address) external view returns (uint256); function COOLDOWN_SECONDS() external view returns (uint256); function stakersCooldowns(address) external view returns (uint256); function UNSTAKE_WINDOW() external view returns (uint256); } // Part: ISwap interface ISwap { function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] memory path) external view returns (uint256[] memory amounts); } // Part: OpenZeppelin/openzeppelin-contracts@3.1.0/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/openzeppelin-contracts@3.1.0/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/openzeppelin-contracts@3.1.0/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/openzeppelin-contracts@3.1.0/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Part: WadRayMath /** * @title WadRayMath library * @author Aave * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { uint256 internal constant WAD = 1e18; uint256 internal constant halfWAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant halfRAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 **/ function ray() internal pure returns (uint256) { return RAY; } /** * @return One wad, 1e18 **/ function wad() internal pure returns (uint256) { return WAD; } /** * @return Half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return halfRAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return halfWAD; } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfWAD) / b); return (a * b + halfWAD) / WAD; } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / WAD); return (a * WAD + halfB) / b; } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfRAY) / b); return (a * b + halfRAY) / RAY; } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / RAY); return (a * RAY + halfB) / b; } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio); return result / WAD_RAY_RATIO; } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * WAD_RAY_RATIO; require(result / WAD_RAY_RATIO == a); return result; } } // Part: iearn-finance/yearn-vaults@0.4.3/HealthCheck interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } // Part: ILendingPool interface ILendingPool { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw( address indexed reserve, address indexed user, address indexed to, uint256 amount ); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled( address indexed reserve, address indexed user ); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled( address indexed reserve, address indexed user ); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate( address indexed reserve, address indexed user ); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress( address reserve, address rateStrategyAddress ) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProvider); function setPause(bool val) external; function paused() external view returns (bool); } // Part: IProtocolDataProvider interface IProtocolDataProvider { struct TokenData { string symbol; address tokenAddress; } function ADDRESSES_PROVIDER() external view returns (ILendingPoolAddressesProvider); function getAllReservesTokens() external view returns (TokenData[] memory); function getAllATokens() external view returns (TokenData[] memory); function getReserveConfigurationData(address asset) external view returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ); function getReserveData(address asset) external view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ); function getUserReserveData(address asset, address user) external view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ); function getReserveTokensAddresses(address asset) external view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); } // Part: IVariableDebtToken /** * @title IVariableDebtToken * @author Aave * @notice Defines the basic interface for a variable debt token. **/ interface IVariableDebtToken is IERC20, IScaledBalanceToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param onBehalfOf The address of the user on which behalf minting has been performed * @param value The amount to be minted * @param index The last index of the reserve **/ event Mint( address indexed from, address indexed onBehalfOf, uint256 value, uint256 index ); /** * @dev Mints debt token to the `onBehalfOf` address * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted when variable debt is burnt * @param user The user which debt has been burned * @param amount The amount of debt being burned * @param index The index of the user **/ event Burn(address indexed user, uint256 amount, uint256 index); /** * @dev Burns user variable debt * @param user The user which debt is burnt * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // Part: IVault interface IVault is IERC20 { function token() external view returns (address); function decimals() external view returns (uint256); function deposit() external; function pricePerShare() external view returns (uint256); function withdraw() external returns (uint256); function withdraw(uint256 amount) external returns (uint256); function withdraw( uint256 amount, address account, uint256 maxLoss ) external returns (uint256); function availableDepositLimit() external view returns (uint256); } // Part: OpenZeppelin/openzeppelin-contracts@3.1.0/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: iearn-finance/yearn-vaults@0.4.3/VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: IInitializableAToken /** * @title IInitializableAToken * @notice Interface for the initialize function on AToken * @author Aave **/ interface IInitializableAToken { /** * @dev Emitted when an aToken is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param treasury The address of the treasury * @param incentivesController The address of the incentives controller for this aToken * @param aTokenDecimals the decimals of the underlying * @param aTokenName the name of the aToken * @param aTokenSymbol the symbol of the aToken * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address treasury, address incentivesController, uint8 aTokenDecimals, string aTokenName, string aTokenSymbol, bytes params ); /** * @dev Initializes the aToken * @param pool The address of the lending pool where this aToken will be used * @param treasury The address of the Aave treasury, receiving the fees on this aToken * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's * @param aTokenName The name of the aToken * @param aTokenSymbol The symbol of the aToken */ function initialize( ILendingPool pool, address treasury, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) external; } // Part: iearn-finance/yearn-vaults@0.4.3/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; // health checks bool public doHealthCheck; address public healthCheck; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.4.3"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyVaultManagers() { require(msg.sender == vault.management() || msg.sender == governance(), "!authorized"); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyVaultManagers { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers { doHealthCheck = _doHealthCheck; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck"); } else { doHealthCheck = true; } emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyEmergencyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * ``` * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } * ``` */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // Part: IAToken interface IAToken is IERC20, IScaledBalanceToken, IInitializableAToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param value The amount being * @param index The new liquidity index of the reserve **/ event Mint(address indexed from, uint256 value, uint256 index); /** * @dev Mints `amount` aTokens to `user` * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted after aTokens are burned * @param from The owner of the aTokens, getting them burned * @param target The address that will receive the underlying * @param value The amount being burned * @param index The new liquidity index of the reserve **/ event Burn( address indexed from, address indexed target, uint256 value, uint256 index ); /** * @dev Emitted during the transfer action * @param from The user whose tokens are being transferred * @param to The recipient * @param value The amount being transferred * @param index The new liquidity index of the reserve **/ event BalanceTransfer( address indexed from, address indexed to, uint256 value, uint256 index ); /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external; /** * @dev Mints aTokens to the reserve treasury * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external; /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external; /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param user The recipient of the underlying * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address user, uint256 amount) external returns (uint256); /** * @dev Invoked to execute actions on the aToken side after a repayment. * @param user The user executing the repayment * @param amount The amount getting repaid **/ function handleRepayment(address user, uint256 amount) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() external view returns (address); } // Part: AaveLenderBorrowerLib library AaveLenderBorrowerLib { using SafeMath for uint256; using WadRayMath for uint256; struct CalcMaxDebtLocalVars { uint256 availableLiquidity; uint256 totalStableDebt; uint256 totalVariableDebt; uint256 totalDebt; uint256 utilizationRate; uint256 totalLiquidity; uint256 targetUtilizationRate; uint256 maxProtocolDebt; } struct IrsVars { uint256 optimalRate; uint256 baseRate; uint256 slope1; uint256 slope2; } uint256 internal constant MAX_BPS = 10_000; IProtocolDataProvider public constant protocolDataProvider = IProtocolDataProvider(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d); function lendingPool() public view returns (ILendingPool) { return ILendingPool( protocolDataProvider.ADDRESSES_PROVIDER().getLendingPool() ); } function priceOracle() public view returns (IPriceOracle) { return IPriceOracle( protocolDataProvider.ADDRESSES_PROVIDER().getPriceOracle() ); } function incentivesController( IAToken aToken, IVariableDebtToken variableDebtToken, bool isWantIncentivised, bool isInvestmentTokenIncentivised ) public view returns (IAaveIncentivesController) { if (isWantIncentivised) { return aToken.getIncentivesController(); } else if (isInvestmentTokenIncentivised) { return variableDebtToken.getIncentivesController(); } else { return IAaveIncentivesController(0); } } function toETH(uint256 _amount, address asset) public view returns (uint256) { return _amount.mul(priceOracle().getAssetPrice(asset)).div( uint256(10)**uint256(IOptionalERC20(asset).decimals()) ); } function fromETH(uint256 _amount, address asset) public view returns (uint256) { return _amount .mul(uint256(10)**uint256(IOptionalERC20(asset).decimals())) .div(priceOracle().getAssetPrice(asset)); } function calcMaxDebt(address _investmentToken, uint256 _acceptableCostsRay) public view returns ( uint256 currentProtocolDebt, uint256 maxProtocolDebt, uint256 targetU ) { // This function is used to calculate the maximum amount of debt that the protocol can take // to keep the cost of capital lower than the set acceptableCosts // This maxProtocolDebt will be used to decide if capital costs are acceptable or not // and to repay required debt to keep the rates below acceptable costs // Hack to avoid the stack too deep compiler error. CalcMaxDebtLocalVars memory vars; DataTypes.ReserveData memory reserveData = lendingPool().getReserveData(address(_investmentToken)); IReserveInterestRateStrategy irs = IReserveInterestRateStrategy( reserveData.interestRateStrategyAddress ); ( vars.availableLiquidity, // = total supply - total stable debt - total variable debt vars.totalStableDebt, // total debt paying stable interest rates vars.totalVariableDebt, // total debt paying stable variable rates , , , , , , ) = protocolDataProvider.getReserveData(address(_investmentToken)); vars.totalDebt = vars.totalStableDebt.add(vars.totalVariableDebt); vars.totalLiquidity = vars.availableLiquidity.add(vars.totalDebt); vars.utilizationRate = vars.totalDebt == 0 ? 0 : vars.totalDebt.rayDiv(vars.totalLiquidity); // Aave's Interest Rate Strategy Parameters (see docs) IrsVars memory irsVars; irsVars.optimalRate = irs.OPTIMAL_UTILIZATION_RATE(); irsVars.baseRate = irs.baseVariableBorrowRate(); // minimum cost of capital with 0 % of utilisation rate irsVars.slope1 = irs.variableRateSlope1(); // rate of increase of cost of debt up to Optimal Utilisation Rate irsVars.slope2 = irs.variableRateSlope2(); // rate of increase of cost of debt above Optimal Utilisation Rate // acceptableCosts should always be > baseVariableBorrowRate // If it's not this will revert since the strategist set the wrong // acceptableCosts value if ( vars.utilizationRate < irsVars.optimalRate && _acceptableCostsRay < irsVars.baseRate.add(irsVars.slope1) ) { // we solve Aave's Interest Rates equation for sub optimal utilisation rates // IR = BASERATE + SLOPE1 * CURRENT_UTIL_RATE / OPTIMAL_UTIL_RATE vars.targetUtilizationRate = ( _acceptableCostsRay.sub(irsVars.baseRate) ) .rayMul(irsVars.optimalRate) .rayDiv(irsVars.slope1); } else { // Special case where protocol is above utilization rate but we want // a lower interest rate than (base + slope1) if (_acceptableCostsRay < irsVars.baseRate.add(irsVars.slope1)) { return (toETH(vars.totalDebt, address(_investmentToken)), 0, 0); } // we solve Aave's Interest Rates equation for utilisation rates above optimal U // IR = BASERATE + SLOPE1 + SLOPE2 * (CURRENT_UTIL_RATE - OPTIMAL_UTIL_RATE) / (1-OPTIMAL_UTIL_RATE) vars.targetUtilizationRate = ( _acceptableCostsRay.sub(irsVars.baseRate.add(irsVars.slope1)) ) .rayMul(uint256(1e27).sub(irsVars.optimalRate)) .rayDiv(irsVars.slope2) .add(irsVars.optimalRate); } vars.maxProtocolDebt = vars .totalLiquidity .rayMul(vars.targetUtilizationRate) .rayDiv(1e27); return ( toETH(vars.totalDebt, address(_investmentToken)), toETH(vars.maxProtocolDebt, address(_investmentToken)), vars.targetUtilizationRate ); } function calculateAmountToRepay( uint256 amountETH, uint256 totalCollateralETH, uint256 totalDebtETH, uint256 warningLTV, uint256 targetLTV, address investmentToken, uint256 minThreshold ) public view returns (uint256) { if (amountETH == 0) { return 0; } // we check if the collateral that we are withdrawing leaves us in a risky range, we then take action uint256 amountToWithdrawETH = amountETH; // calculate the collateral that we are leaving after withdrawing uint256 newCollateral = totalCollateralETH > amountToWithdrawETH ? totalCollateralETH.sub(amountToWithdrawETH) : 0; uint256 ltvAfterWithdrawal = newCollateral > 0 ? totalDebtETH.mul(MAX_BPS).div(newCollateral) : type(uint256).max; // check if the new LTV is in UNHEALTHY range // remember that if balance > _amountNeeded, ltvAfterWithdrawal == 0 (0 risk) // this is not true but the effect will be the same if (ltvAfterWithdrawal <= warningLTV) { // no need of repaying debt because the LTV is ok return 0; } else if (ltvAfterWithdrawal == type(uint256).max) { // we are withdrawing 100% of collateral so we need to repay full debt return fromETH(totalDebtETH, address(investmentToken)); } // WARNING: this only works for a single collateral asset, otherwise liquidationThreshold might change depending on the collateral being withdrawn // e.g. we have USDC + WBTC as collateral, end liquidationThreshold will be different depending on which asset we withdraw uint256 newTargetDebt = targetLTV.mul(newCollateral).div(MAX_BPS); // if newTargetDebt is higher, we don't need to repay anything if (newTargetDebt > totalDebtETH) { return 0; } return fromETH( totalDebtETH.sub(newTargetDebt) < minThreshold ? totalDebtETH : totalDebtETH.sub(newTargetDebt), address(investmentToken) ); } function checkCooldown( bool isWantIncentivised, bool isInvestmentTokenIncentivised, address stkAave ) external view returns (bool) { if (!isWantIncentivised && !isInvestmentTokenIncentivised) { return false; } uint256 cooldownStartTimestamp = IStakedAave(stkAave).stakersCooldowns(address(this)); uint256 COOLDOWN_SECONDS = IStakedAave(stkAave).COOLDOWN_SECONDS(); uint256 UNSTAKE_WINDOW = IStakedAave(stkAave).UNSTAKE_WINDOW(); return cooldownStartTimestamp != 0 && block.timestamp > cooldownStartTimestamp.add(COOLDOWN_SECONDS) && block.timestamp <= cooldownStartTimestamp.add(COOLDOWN_SECONDS).add(UNSTAKE_WINDOW); } function shouldRebalance( address investmentToken, uint256 acceptableCostsRay, uint256 targetLTV, uint256 warningLTV, uint256 totalCollateralETH, uint256 totalDebtETH ) external view returns (bool) { uint256 currentLTV = totalDebtETH.mul(MAX_BPS).div(totalCollateralETH); (uint256 currentProtocolDebt, uint256 maxProtocolDebt, ) = calcMaxDebt(investmentToken, acceptableCostsRay); if ( (currentLTV < targetLTV && currentProtocolDebt < maxProtocolDebt && targetLTV.sub(currentLTV) > 1000) || // WE NEED TO TAKE ON MORE DEBT (we need a 10p.p (1000bps) difference) (currentLTV > warningLTV || currentProtocolDebt > maxProtocolDebt) // WE NEED TO REPAY DEBT BECAUSE OF UNHEALTHY RATIO OR BORROWING COSTS ) { return true; } // no call to super.tendTrigger as it would return false return false; } } // Part: Strategy contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; using WadRayMath for uint256; // max interest rate we can afford to pay for borrowing investment token // amount in Ray (1e27 = 100%) uint256 public acceptableCostsRay = WadRayMath.RAY; // max amount to borrow. used to manually limit amount (for yVault to keep APY) uint256 public maxTotalBorrowIT; bool public isWantIncentivised; bool public isInvestmentTokenIncentivised; // if set to true, the strategy will not try to repay debt by selling want bool public leaveDebtBehind; // Aave's referral code uint16 internal referral; // NOTE: LTV = Loan-To-Value = debt/collateral // Target LTV: ratio up to which which we will borrow uint16 public targetLTVMultiplier = 6_000; // Warning LTV: ratio at which we will repay uint16 public warningLTVMultiplier = 8_000; // 80% of liquidation LTV // support uint16 internal constant MAX_BPS = 10_000; // 100% uint16 internal constant MAX_MULTIPLIER = 9_000; // 90% IAToken internal aToken; IVariableDebtToken internal variableDebtToken; IVault public yVault; IERC20 internal investmentToken; ISwap public router; IStakedAave internal constant stkAave = IStakedAave(0x4da27a545c0c5B758a6BA100e3a049001de870f5); address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address internal constant AAVE = 0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9; uint256 internal minThreshold; uint256 public maxLoss; string internal strategyName; event RepayDebt(uint256 repayAmount, uint256 previousDebtBalance); constructor( address _vault, address _yVault, string memory _strategyName ) public BaseStrategy(_vault) { _initializeThis(_yVault, _strategyName); } // ----------------- PUBLIC VIEW FUNCTIONS ----------------- function name() external view override returns (string memory) { return strategyName; } function estimatedTotalAssets() public view override returns (uint256) { // not taking into account aave rewards (they are staked and not accesible) return balanceOfWant() // balance of want .add(balanceOfAToken()) // asset suplied as collateral .add( _fromETH( _toETH(_valueOfInvestment(), address(investmentToken)), address(want) ) ) // current value of assets deposited in vault .sub( _fromETH( _toETH(balanceOfDebt(), address(investmentToken)), address(want) ) ); // liabilities } // ----------------- SETTERS ----------------- // we put all together to save contract bytecode (!) function setStrategyParams( uint16 _targetLTVMultiplier, uint16 _warningLTVMultiplier, uint256 _acceptableCostsRay, uint16 _aaveReferral, uint256 _maxTotalBorrowIT, bool _isWantIncentivised, bool _isInvestmentTokenIncentivised, bool _leaveDebtBehind, uint256 _maxLoss ) external onlyEmergencyAuthorized { require( _warningLTVMultiplier <= MAX_MULTIPLIER && _targetLTVMultiplier <= _warningLTVMultiplier ); targetLTVMultiplier = _targetLTVMultiplier; warningLTVMultiplier = _warningLTVMultiplier; acceptableCostsRay = _acceptableCostsRay; maxTotalBorrowIT = _maxTotalBorrowIT; referral = _aaveReferral; isWantIncentivised = _isWantIncentivised; isInvestmentTokenIncentivised = _isInvestmentTokenIncentivised; leaveDebtBehind = _leaveDebtBehind; maxLoss = _maxLoss; } // Where to route token swaps // Access control is stricter in this method as it will be sent funds function setSwapRouter(ISwap _router) external onlyGovernance { router = _router; } function _initializeThis(address _yVault, string memory _strategyName) internal { yVault = IVault(_yVault); investmentToken = IERC20(IVault(_yVault).token()); (address _aToken, , ) = _protocolDataProvider().getReserveTokensAddresses(address(want)); aToken = IAToken(_aToken); (, , address _variableDebtToken) = _protocolDataProvider().getReserveTokensAddresses( address(investmentToken) ); variableDebtToken = IVariableDebtToken(_variableDebtToken); minThreshold = (10**(yVault.decimals())).div(100); // 0.01 minThreshold // Set default router to SushiSwap router = ISwap(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); strategyName = _strategyName; } function initialize( address _vault, address _yVault, string memory _strategyName ) public { address sender = msg.sender; _initialize(_vault, sender, sender, sender); _initializeThis(_yVault, _strategyName); } // ----------------- MAIN STRATEGY FUNCTIONS ----------------- function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { uint256 totalDebt = vault.strategies(address(this)).totalDebt; // claim rewards from Aave's Liquidity Mining Program _claimRewards(); // claim rewards from yVault _takeVaultProfit(); uint256 totalAssetsAfterProfit = estimatedTotalAssets(); _profit = totalAssetsAfterProfit > totalDebt ? totalAssetsAfterProfit.sub(totalDebt) : 0; uint256 _amountFreed; (_amountFreed, _loss) = liquidatePosition( _debtOutstanding.add(_profit) ); _debtPayment = Math.min(_debtOutstanding, _amountFreed); if (_loss > _profit) { // Example: // debtOutstanding 100, profit 50, _amountFreed 100, _loss 50 // loss should be 0, (50-50) // profit should endup in 0 _loss = _loss.sub(_profit); _profit = 0; } else { // Example: // debtOutstanding 100, profit 50, _amountFreed 140, _loss 10 // _profit should be 40, (50 profit - 10 loss) // loss should end up in be 0 _profit = _profit.sub(_loss); _loss = 0; } } function adjustPosition(uint256 _debtOutstanding) internal override { uint256 wantBalance = balanceOfWant(); // if we have enough want to deposit more into Aave, we do // NOTE: we do not skip the rest of the function if we don't as it may need to repay or take on more debt if (wantBalance > _debtOutstanding) { uint256 amountToDeposit = wantBalance.sub(_debtOutstanding); _depositToAave(amountToDeposit); } // NOTE: debt + collateral calcs are done in ETH ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, , ) = _getAaveUserAccountData(); // if there is no want deposited into aave, don't do nothing // this means no debt is borrowed from aave too if (totalCollateralETH == 0) { return; } uint256 currentLTV = totalDebtETH.mul(MAX_BPS).div(totalCollateralETH); uint256 targetLTV = _getTargetLTV(currentLiquidationThreshold); // 60% under liquidation Threshold uint256 warningLTV = _getWarningLTV(currentLiquidationThreshold); // 80% under liquidation Threshold // decide in which range we are and act accordingly: // SUBOPTIMAL(borrow) (e.g. from 0 to 60% liqLTV) // HEALTHY(do nothing) (e.g. from 60% to 80% liqLTV) // UNHEALTHY(repay) (e.g. from 80% to 100% liqLTV) // we use our target cost of capital to calculate how much debt we can take on / how much debt we need to repay // in order to bring costs back to an acceptable range // currentProtocolDebt => total amount of debt taken by all Aave's borrowers // maxProtocolDebt => amount of total debt at which the cost of capital is equal to our acceptable costs // if the current protocol debt is higher than the max protocol debt, we will repay debt ( uint256 currentProtocolDebt, uint256 maxProtocolDebt, uint256 targetUtilisationRay ) = AaveLenderBorrowerLib.calcMaxDebt( address(investmentToken), acceptableCostsRay ); if (targetLTV > currentLTV && currentProtocolDebt < maxProtocolDebt) { // SUBOPTIMAL RATIO: our current Loan-to-Value is lower than what we want // AND costs are lower than our max acceptable costs // we need to take on more debt uint256 targetDebtETH = totalCollateralETH.mul(targetLTV).div(MAX_BPS); uint256 amountToBorrowETH = targetDebtETH.sub(totalDebtETH); // safe bc we checked ratios amountToBorrowETH = Math.min( availableBorrowsETH, amountToBorrowETH ); // cap the amount of debt we are taking according to our acceptable costs // if with the new loan we are increasing our cost of capital over what is healthy if (currentProtocolDebt.add(amountToBorrowETH) > maxProtocolDebt) { // Can't underflow because it's checked in the previous if condition amountToBorrowETH = maxProtocolDebt.sub(currentProtocolDebt); } uint256 maxTotalBorrowETH = _toETH(maxTotalBorrowIT, address(investmentToken)); if (totalDebtETH.add(amountToBorrowETH) > maxTotalBorrowETH) { amountToBorrowETH = maxTotalBorrowETH > totalDebtETH ? maxTotalBorrowETH.sub(totalDebtETH) : 0; } // convert to InvestmentToken uint256 amountToBorrowIT = _fromETH(amountToBorrowETH, address(investmentToken)); if (amountToBorrowIT > 0) { _lendingPool().borrow( address(investmentToken), amountToBorrowIT, 2, referral, address(this) ); } } else if ( currentLTV > warningLTV || currentProtocolDebt > maxProtocolDebt ) { // UNHEALTHY RATIO // we may be in this case if the current cost of capital is higher than our max cost of capital // we repay debt to set it to targetLTV uint256 targetDebtETH = targetLTV.mul(totalCollateralETH).div(MAX_BPS); uint256 amountToRepayETH = targetDebtETH < totalDebtETH ? totalDebtETH.sub(targetDebtETH) : 0; if (maxProtocolDebt == 0) { amountToRepayETH = totalDebtETH; } else if (currentProtocolDebt > maxProtocolDebt) { // NOTE: take into account that we are withdrawing from yvVault which might have a GenLender lending to Aave // REPAY = (currentProtocolDebt - maxProtocolDebt) / (1 - TargetUtilisation) // coming from // TargetUtilisation = (totalDebt - REPAY) / (currentLiquidity - REPAY) // currentLiquidity = maxProtocolDebt / TargetUtilisation uint256 iterativeRepayAmountETH = currentProtocolDebt .sub(maxProtocolDebt) .mul(WadRayMath.RAY) .div(uint256(WadRayMath.RAY).sub(targetUtilisationRay)); amountToRepayETH = Math.max( amountToRepayETH, iterativeRepayAmountETH ); } emit RepayDebt(amountToRepayETH, totalDebtETH); uint256 amountToRepayIT = _fromETH(amountToRepayETH, address(investmentToken)); uint256 withdrawnIT = _withdrawFromYVault(amountToRepayIT); // we withdraw from investmentToken vault _repayInvestmentTokenDebt(withdrawnIT); // we repay the investmentToken debt with Aave } uint256 balanceIT = balanceOfInvestmentToken(); if (balanceIT > 0) { _checkAllowance( address(yVault), address(investmentToken), balanceIT ); yVault.deposit(); } } function liquidateAllPositions() internal override returns (uint256 _amountFreed) { (_amountFreed, ) = liquidatePosition(estimatedTotalAssets()); } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 balance = balanceOfWant(); // if we have enough want to take care of the liquidatePosition without actually liquidating positons if (balance >= _amountNeeded) { return (_amountNeeded, 0); } // NOTE: amountNeeded is in want // NOTE: repayment amount is in investmentToken // NOTE: collateral and debt calcs are done in ETH (always, see Aave docs) // We first repay whatever we need to repay to keep healthy ratios uint256 amountToRepayIT = _calculateAmountToRepay(_amountNeeded); uint256 withdrawnIT = _withdrawFromYVault(amountToRepayIT); // we withdraw from investmentToken vault _repayInvestmentTokenDebt(withdrawnIT); // we repay the investmentToken debt with Aave // it will return the free amount of want _withdrawWantFromAave(_amountNeeded); balance = balanceOfWant(); // we check if we withdrew less than expected AND should buy investmentToken with want (realising losses) if ( _amountNeeded > balance && balanceOfDebt() > 0 && // still some debt remaining balanceOfInvestmentToken().add(_valueOfInvestment()) == 0 && // but no capital to repay !leaveDebtBehind // if set to true, the strategy will not try to repay debt by selling want ) { // using this part of code will result in losses but it is necessary to unlock full collateral in case of wind down // we calculate how much want we need to fulfill the want request uint256 remainingAmountWant = _amountNeeded.sub(balance); // then calculate how much InvestmentToken we need to unlock collateral amountToRepayIT = _calculateAmountToRepay(remainingAmountWant); // we buy investmentToken with Want _buyInvestmentTokenWithWant(amountToRepayIT); // we repay debt to actually unlock collateral // after this, balanceOfDebt should be 0 _repayInvestmentTokenDebt(amountToRepayIT); // then we try withdraw once more _withdrawWantFromAave(remainingAmountWant); } uint256 totalAssets = balanceOfWant(); if (_amountNeeded > totalAssets) { _liquidatedAmount = totalAssets; _loss = _amountNeeded.sub(totalAssets); } else { _liquidatedAmount = _amountNeeded; } } function delegatedAssets() external view override returns (uint256) { // returns total debt borrowed in want (which is the delegatedAssets) return _fromETH( _toETH(balanceOfDebt(), address(investmentToken)), address(want) ); } function prepareMigration(address _newStrategy) internal override { // nothing to do since debt cannot be migrated } function harvestTrigger(uint256 callCost) public view override returns (bool) { // we harvest if: // 1. stakedAave is ready to be converted to Aave and sold return _checkCooldown() || super.harvestTrigger(_fromETH(callCost, address(want))); } function tendTrigger(uint256 callCost) public view override returns (bool) { // we adjust position if: // 1. LTV ratios are not in the HEALTHY range (either we take on more debt or repay debt) // 2. costs are not acceptable and we need to repay debt ( uint256 totalCollateralETH, uint256 totalDebtETH, , uint256 currentLiquidationThreshold, , ) = _getAaveUserAccountData(); uint256 targetLTV = _getTargetLTV(currentLiquidationThreshold); uint256 warningLTV = _getWarningLTV(currentLiquidationThreshold); return AaveLenderBorrowerLib.shouldRebalance( address(investmentToken), acceptableCostsRay, targetLTV, warningLTV, totalCollateralETH, totalDebtETH ); } // ----------------- INTERNAL FUNCTIONS SUPPORT ----------------- function _withdrawFromYVault(uint256 _amountIT) internal returns (uint256) { if (_amountIT == 0) { return 0; } // no need to check allowance bc the contract == token uint256 balancePrior = balanceOfInvestmentToken(); uint256 sharesToWithdraw = Math.min( _investmentTokenToYShares(_amountIT), yVault.balanceOf(address(this)) ); if (sharesToWithdraw == 0) { return 0; } yVault.withdraw(sharesToWithdraw, address(this), maxLoss); return balanceOfInvestmentToken().sub(balancePrior); } function _repayInvestmentTokenDebt(uint256 amount) internal { if (amount == 0) { return; } // we cannot pay more than loose balance amount = Math.min(amount, balanceOfInvestmentToken()); // we cannot pay more than we owe amount = Math.min(amount, balanceOfDebt()); _checkAllowance( address(_lendingPool()), address(investmentToken), amount ); if (amount > 0) { _lendingPool().repay( address(investmentToken), amount, uint256(2), address(this) ); } } function _claimRewards() internal { if (isInvestmentTokenIncentivised || isWantIncentivised) { // redeem AAVE from stkAave uint256 stkAaveBalance = IERC20(address(stkAave)).balanceOf(address(this)); if (stkAaveBalance > 0 && _checkCooldown()) { // claim AAVE rewards stkAave.claimRewards(address(this), type(uint256).max); stkAave.redeem(address(this), stkAaveBalance); } // sell AAVE for want // a minimum balance of 0.01 AAVE is required uint256 aaveBalance = IERC20(AAVE).balanceOf(address(this)); if (aaveBalance > 1e15) { _sellAForB(aaveBalance, address(AAVE), address(want)); } // claim rewards // only add to assets those assets that are incentivised address[] memory assets; if (isInvestmentTokenIncentivised && isWantIncentivised) { assets = new address[](2); assets[0] = address(aToken); assets[1] = address(variableDebtToken); } else if (isInvestmentTokenIncentivised) { assets = new address[](1); assets[0] = address(variableDebtToken); } else if (isWantIncentivised) { assets = new address[](1); assets[0] = address(aToken); } _incentivesController().claimRewards( assets, type(uint256).max, address(this) ); // request start of cooldown period uint256 cooldownStartTimestamp = IStakedAave(stkAave).stakersCooldowns(address(this)); uint256 COOLDOWN_SECONDS = IStakedAave(stkAave).COOLDOWN_SECONDS(); uint256 UNSTAKE_WINDOW = IStakedAave(stkAave).UNSTAKE_WINDOW(); if ( IERC20(address(stkAave)).balanceOf(address(this)) > 0 && (cooldownStartTimestamp == 0 || block.timestamp > cooldownStartTimestamp.add(COOLDOWN_SECONDS).add( UNSTAKE_WINDOW )) ) { stkAave.cooldown(); } } } //withdraw an amount including any want balance function _withdrawWantFromAave(uint256 amount) internal { uint256 balanceUnderlying = balanceOfAToken(); if (amount > balanceUnderlying) { amount = balanceUnderlying; } uint256 maxWithdrawal = Math.min(_maxWithdrawal(), want.balanceOf(address(aToken))); uint256 toWithdraw = Math.min(amount, maxWithdrawal); if (toWithdraw > 0) { _checkAllowance( address(_lendingPool()), address(aToken), toWithdraw ); _lendingPool().withdraw(address(want), toWithdraw, address(this)); } } function _maxWithdrawal() internal view returns (uint256) { (uint256 totalCollateralETH, uint256 totalDebtETH, , , uint256 ltv, ) = _getAaveUserAccountData(); uint256 minCollateralETH = ltv > 0 ? totalDebtETH.mul(MAX_BPS).div(ltv) : totalCollateralETH; if (minCollateralETH > totalCollateralETH) { return 0; } return _fromETH(totalCollateralETH.sub(minCollateralETH), address(want)); } function _calculateAmountToRepay(uint256 amount) internal view returns (uint256) { if (amount == 0) { return 0; } // we check if the collateral that we are withdrawing leaves us in a risky range, we then take action ( uint256 totalCollateralETH, uint256 totalDebtETH, , uint256 currentLiquidationThreshold, , ) = _getAaveUserAccountData(); uint256 warningLTV = _getWarningLTV(currentLiquidationThreshold); uint256 targetLTV = _getTargetLTV(currentLiquidationThreshold); uint256 amountETH = _toETH(amount, address(want)); return AaveLenderBorrowerLib.calculateAmountToRepay( amountETH, totalCollateralETH, totalDebtETH, warningLTV, targetLTV, address(investmentToken), minThreshold ); } function _depositToAave(uint256 amount) internal { if (amount == 0) { return; } ILendingPool lp = _lendingPool(); _checkAllowance(address(lp), address(want), amount); lp.deposit(address(want), amount, address(this), referral); } function _checkCooldown() internal view returns (bool) { return AaveLenderBorrowerLib.checkCooldown( isWantIncentivised, isInvestmentTokenIncentivised, address(stkAave) ); } function _checkAllowance( address _contract, address _token, uint256 _amount ) internal { if (IERC20(_token).allowance(address(this), _contract) < _amount) { IERC20(_token).safeApprove(_contract, 0); IERC20(_token).safeApprove(_contract, type(uint256).max); } } function _takeVaultProfit() internal { uint256 _debt = balanceOfDebt(); uint256 _valueInVault = _valueOfInvestment(); if (_debt >= _valueInVault) { return; } uint256 profit = _valueInVault.sub(_debt); uint256 ySharesToWithdraw = _investmentTokenToYShares(profit); if (ySharesToWithdraw > 0) { yVault.withdraw(ySharesToWithdraw, address(this), maxLoss); _sellAForB( balanceOfInvestmentToken(), address(investmentToken), address(want) ); } } // ----------------- INTERNAL CALCS ----------------- function balanceOfWant() internal view returns (uint256) { return want.balanceOf(address(this)); } function balanceOfInvestmentToken() internal view returns (uint256) { return investmentToken.balanceOf(address(this)); } function balanceOfAToken() internal view returns (uint256) { return aToken.balanceOf(address(this)); } function balanceOfDebt() internal view returns (uint256) { return variableDebtToken.balanceOf(address(this)); } function _valueOfInvestment() internal view returns (uint256) { return yVault.balanceOf(address(this)).mul(yVault.pricePerShare()).div( 10**yVault.decimals() ); } function _investmentTokenToYShares(uint256 amount) internal view returns (uint256) { return amount.mul(10**yVault.decimals()).div(yVault.pricePerShare()); } function _getAaveUserAccountData() internal view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) { return _lendingPool().getUserAccountData(address(this)); } function _getTargetLTV(uint256 liquidationThreshold) internal view returns (uint256) { return liquidationThreshold.mul(uint256(targetLTVMultiplier)).div(MAX_BPS); } function _getWarningLTV(uint256 liquidationThreshold) internal view returns (uint256) { return liquidationThreshold.mul(uint256(warningLTVMultiplier)).div( MAX_BPS ); } // ----------------- TOKEN CONVERSIONS ----------------- function getTokenOutPath(address _token_in, address _token_out) internal pure returns (address[] memory _path) { bool is_weth = _token_in == address(WETH) || _token_out == address(WETH); _path = new address[](is_weth ? 2 : 3); _path[0] = _token_in; if (is_weth) { _path[1] = _token_out; } else { _path[1] = address(WETH); _path[2] = _token_out; } } function _sellAForB( uint256 _amount, address tokenA, address tokenB ) internal { if (_amount == 0 || tokenA == tokenB) { return; } _checkAllowance(address(router), tokenA, _amount); router.swapExactTokensForTokens( _amount, 0, getTokenOutPath(tokenA, tokenB), address(this), now ); } function _buyInvestmentTokenWithWant(uint256 _amount) internal { if (_amount == 0 || address(investmentToken) == address(want)) { return; } _checkAllowance(address(router), address(want), _amount); router.swapTokensForExactTokens( _amount, type(uint256).max, getTokenOutPath(address(want), address(investmentToken)), address(this), now ); } function _toETH(uint256 _amount, address asset) internal view returns (uint256) { if ( _amount == 0 || _amount == type(uint256).max || address(asset) == address(WETH) // 1:1 change ) { return _amount; } return AaveLenderBorrowerLib.toETH(_amount, asset); } function ethToWant(uint256 _amtInWei) public view override returns (uint256) { return _fromETH(_amtInWei, address(want)); } function _fromETH(uint256 _amount, address asset) internal view returns (uint256) { if ( _amount == 0 || _amount == type(uint256).max || address(asset) == address(WETH) // 1:1 change ) { return _amount; } return AaveLenderBorrowerLib.fromETH(_amount, asset); } // ----------------- INTERNAL SUPPORT GETTERS ----------------- function _lendingPool() internal view returns (ILendingPool lendingPool) { return AaveLenderBorrowerLib.lendingPool(); } function _protocolDataProvider() internal view returns (IProtocolDataProvider protocolDataProvider) { return AaveLenderBorrowerLib.protocolDataProvider; } function _priceOracle() internal view returns (IPriceOracle) { return AaveLenderBorrowerLib.priceOracle(); } function _incentivesController() internal view returns (IAaveIncentivesController) { return AaveLenderBorrowerLib.incentivesController( aToken, variableDebtToken, isWantIncentivised, isInvestmentTokenIncentivised ); } function protectedTokens() internal view override returns (address[] memory) {} } // File: AaveLenderBorrowerCloner.sol contract AaveLenderBorrowerCloner { address public immutable original; event Cloned(address indexed clone); event Deployed(address indexed original); constructor( address _vault, address _yVault, bool _isWantIncentivised, bool _isInvestmentTokenIncentivised, string memory _strategyName ) public { Strategy _original = new Strategy(_vault, _yVault, _strategyName); emit Deployed(address(_original)); original = address(_original); Strategy(_original).setStrategyParams( 4_000, // targetLTVMultiplier (default: 4_000) 6_000, // warningLTVMultiplier default: 6_000 1e27, // acceptableCosts (default: 1e27) 7, // default: 7 (Yearn Aave Referal code) type(uint256).max, // 2**256-1 _isWantIncentivised, _isInvestmentTokenIncentivised, false, // leave debt behind (default: false) 1 // maxLoss (default: 1) ); Strategy(_original).setRewards(msg.sender); Strategy(_original).setKeeper(msg.sender); Strategy(_original).setStrategist(msg.sender); } function name() external pure returns (string memory) { return "Yearn-AaveLenderBorrowerCloner@0.4.3"; } function cloneAaveLenderBorrower( address _vault, address _strategist, address _rewards, address _keeper, address _yVault, bool _isWantIncentivised, bool _isInvestmentTokenIncentivised, string memory _strategyName ) external returns (address newStrategy) { // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(original); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore( clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } Strategy(newStrategy).initialize(_vault, _yVault, _strategyName); Strategy(newStrategy).setStrategyParams( 4_000, // targetLTVMultiplier (default: 4_000) 6_000, // warningLTVMultiplier default: 6_000 1e27, // acceptableCosts (default: 1e27) 7, // default: 7 (Yearn Aave Referal code) type(uint256).max, // max debt to take _isWantIncentivised, _isInvestmentTokenIncentivised, false, // leave debt behind (default: false) 1 // maxLoss (default: 1) ); Strategy(newStrategy).setKeeper(_keeper); Strategy(newStrategy).setRewards(_rewards); Strategy(newStrategy).setStrategist(_strategist); emit Cloned(newStrategy); } }
----------------- INTERNAL CALCS -----------------
function balanceOfWant() internal view returns (uint256) { return want.balanceOf(address(this)); }
1,105,779
pragma solidity ^0.4.21; /// @title ERC-165 Standard Interface Detection /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md interface ERC165 { function supportsInterface(bytes4 interfaceID) external view returns (bool); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /// @title ERC-721 Non-Fungible Token Standard /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md contract ERC721 is ERC165 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); function balanceOf(address _owner) external view returns (uint256); function ownerOf(uint256 _tokenId) external view returns (address); function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) public payable; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public payable; function transferFrom(address _from, address _to, uint256 _tokenId) external payable; function approve(address _approved, uint256 _tokenId) external payable; function setApprovalForAll(address _operator, bool _approved) external; function getApproved(uint256 _tokenId) external view returns (address); function isApprovedForAll(address _owner, address _operator) external view returns (bool); } /// @title ERC-721 Non-Fungible Token Standard interface ERC721TokenReceiver { function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4); } /// @title ERC-721 Non-Fungible Token Standard, optional metadata extension interface ERC721Metadata /* is ERC721 */ { function name() external pure returns (string _name); function symbol() external pure returns (string _symbol); function tokenURI(uint256 _tokenId) external view returns (string); } /// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension interface ERC721Enumerable /* is ERC721 */ { function totalSupply() external view returns (uint256); function tokenByIndex(uint256 _index) external view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256); } /// @title A reusable contract to comply with ERC-165 /// @author William Entriken (https://phor.net) contract PublishInterfaces is ERC165 { /// @dev Every interface that we support mapping(bytes4 => bool) internal supportedInterfaces; function PublishInterfaces() internal { supportedInterfaces[0x01ffc9a7] = true; // ERC165 } /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool) { return supportedInterfaces[interfaceID] && (interfaceID != 0xffffffff); } } /// @title The external contract that is responsible for generating metadata for GanTokens, /// it has one function that will return the data as bytes. contract Metadata { /// @dev Given a token Id, returns a string with metadata function getMetadata(uint256 _tokenId, string) public pure 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 GanNFT is ERC165, ERC721, ERC721Enumerable, PublishInterfaces, Ownable { function GanNFT() internal { supportedInterfaces[0x80ac58cd] = true; // ERC721 supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable supportedInterfaces[0x8153916a] = true; // ERC721 + 165 (not needed) } bytes4 private constant ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,uint256,bytes)")); // @dev claim price taken for each new GanToken // generating a new token will be free in the beinging and later changed uint256 public claimPrice = 0; // @dev max supply for token uint256 public maxSupply = 300; // The contract that will return tokens metadata Metadata public erc721Metadata; /// @dev list of all owned token ids uint256[] public tokenIds; /// @dev a mpping for all tokens mapping(uint256 => address) public tokenIdToOwner; /// @dev mapping to keep owner balances mapping(address => uint256) public ownershipCounts; /// @dev mapping to owners to an array of tokens that they own mapping(address => uint256[]) public ownerBank; /// @dev mapping to approved ids mapping(uint256 => address) public tokenApprovals; /// @dev The authorized operators for each address mapping (address => mapping (address => bool)) internal operatorApprovals; /// @notice A descriptive name for a collection of NFTs in this contract function name() external pure returns (string) { return "GanToken"; } /// @notice An abbreviated name for NFTs in this contract function symbol() external pure returns (string) { return "GT"; } /// @dev Set the address of the sibling contract that tracks metadata. /// Only the contract creater can call this. /// @param _contractAddress The location of the contract with meta data function setMetadataAddress(address _contractAddress) public onlyOwner { erc721Metadata = Metadata(_contractAddress); } modifier canTransfer(uint256 _tokenId, address _from, address _to) { address owner = tokenIdToOwner[_tokenId]; require(tokenApprovals[_tokenId] == _to || owner == _from || operatorApprovals[_to][_to]); _; } /// @notice checks to see if a sender owns a _tokenId /// @param _tokenId The identifier for an NFT modifier owns(uint256 _tokenId) { require(tokenIdToOwner[_tokenId] == msg.sender); _; } /// @dev This emits any time the ownership of a GanToken changes. event Transfer(address indexed _from, address indexed _to, uint256 _value); /// @dev This emits when the approved addresses for a GanToken is changed or reaffirmed. /// The zero address indicates there is no owner and it get reset on a transfer event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice allow the owner to set the supply max function setMaxSupply(uint max) external payable onlyOwner { require(max > tokenIds.length); maxSupply = max; } /// @notice allow the owner to set a new fee for creating a GanToken function setClaimPrice(uint256 price) external payable onlyOwner { claimPrice = price; } /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) external view returns (uint256 balance) { balance = ownershipCounts[_owner]; } /// @notice Gets the onwner of a an NFT /// @param _tokenId The identifier for an NFT /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = tokenIdToOwner[_tokenId]; } /// @notice returns all owners&#39; tokens will return an empty array /// if the address has no tokens /// @param _owner The address of the owner in question function tokensOfOwner(address _owner) external view returns (uint256[]) { uint256 tokenCount = ownershipCounts[_owner]; if (tokenCount == 0) { return new uint256[](0); } uint256[] memory result = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { result[i] = ownerBank[_owner][i]; } return result; } /// @dev creates a list of all the tokenIds function getAllTokenIds() external view returns (uint256[]) { uint256[] memory result = new uint256[](tokenIds.length); for (uint i = 0; i < result.length; i++) { result[i] = tokenIds[i]; } return result; } /// @notice Create a new GanToken with a id and attaches an owner /// @param _noise The id of the token that&#39;s being created function newGanToken(uint256 _noise) external payable { require(msg.sender != address(0)); require(tokenIdToOwner[_noise] == 0x0); require(tokenIds.length < maxSupply); require(msg.value >= claimPrice); tokenIds.push(_noise); ownerBank[msg.sender].push(_noise); tokenIdToOwner[_noise] = msg.sender; ownershipCounts[msg.sender]++; emit Transfer(address(0), msg.sender, 0); } /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) public payable { _safeTransferFrom(_from, _to, _tokenId, data); } /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "" /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) public payable { _safeTransferFrom(_from, _to, _tokenId, ""); } /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external payable { require(_to != 0x0); require(_to != address(this)); require(tokenApprovals[_tokenId] == msg.sender); require(tokenIdToOwner[_tokenId] == _from); _transfer(_tokenId, _to); } /// @notice Grant another address the right to transfer a specific token via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @dev The zero address indicates there is no approved address. /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @dev Required for ERC-721 compliance. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. function approve(address _to, uint256 _tokenId) external owns(_tokenId) payable { // Register the approval (replacing any previous approval). tokenApprovals[_tokenId] = _to; emit Approval(msg.sender, _to, _tokenId); } /// @notice Enable or disable approval for a third party ("operator") to manage /// all your asset. /// @dev Emits the ApprovalForAll event /// @param _operator Address to add to the set of authorized operators. /// @param _approved True if the operators is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external { operatorApprovals[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /// @notice Get the approved address for a single NFT /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view returns (address) { return tokenApprovals[_tokenId]; } /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool) { return operatorApprovals[_owner][_operator]; } /// @notice Count NFTs tracked by this contract /// @return A count of valid NFTs tracked by this contract, where each one of /// them has an assigned and queryable owner not equal to the zero address /// @dev Required for ERC-721 compliance. function totalSupply() external view returns (uint256) { return tokenIds.length; } /// @notice Enumerate valid NFTs /// @param _index A counter less than `totalSupply()` /// @return The token identifier for index the `_index`th NFT 0 if it doesn&#39;t exist, function tokenByIndex(uint256 _index) external view returns (uint256) { return tokenIds[_index]; } /// @notice Enumerate NFTs assigned to an owner /// @dev Throws if `_index` >= `balanceOf(_owner)` or if /// `_owner` is the zero address, representing invalid NFTs. /// @param _owner An address where we are interested in NFTs owned by them /// @param _index A counter less than `balanceOf(_owner)` /// @return The token identifier for the `_index`th NFT assigned to `_owner`, /// (sort order not specified) function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId) { require(_owner != address(0)); require(_index < ownerBank[_owner].length); _tokenId = ownerBank[_owner][_index]; } function _transfer(uint256 _tokenId, address _to) internal { require(_to != address(0)); address from = tokenIdToOwner[_tokenId]; uint256 tokenCount = ownershipCounts[from]; // remove from ownerBank and replace the deleted token id for (uint256 i = 0; i < tokenCount; i++) { uint256 ownedId = ownerBank[from][i]; if (_tokenId == ownedId) { delete ownerBank[from][i]; if (i != tokenCount) { ownerBank[from][i] = ownerBank[from][tokenCount - 1]; } break; } } ownershipCounts[from]--; ownershipCounts[_to]++; ownerBank[_to].push(_tokenId); tokenIdToOwner[_tokenId] = _to; tokenApprovals[_tokenId] = address(0); emit Transfer(from, _to, 1); } /// @dev Actually perform the safeTransferFrom function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) private canTransfer(_tokenId, _from, _to) { address owner = tokenIdToOwner[_tokenId]; require(owner == _from); require(_to != address(0)); require(_to != address(this)); _transfer(_tokenId, _to); // Do the callback after everything is done to avoid reentrancy attack uint256 codeSize; assembly { codeSize := extcodesize(_to) } if (codeSize == 0) { return; } bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, data); require(retval == ERC721_RECEIVED); } /// @dev Adapted from memcpy() by @arachnid (Nick Johnson <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5b4a7b4b6bdbbbcb195bbbaa1b1baa1fbbbb0a1">[email&#160;protected]</a>>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _memcpy(uint _dest, uint _src, uint _len) private pure { // Copy word-length chunks while possible for(; _len >= 32; _len -= 32) { assembly { mstore(_dest, mload(_src)) } _dest += 32; _src += 32; } // Copy remaining bytes 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)) } } /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b1d0c3d0d2d9dfd8d5f1dfdec5d5dec59fdfd4c5">[email&#160;protected]</a>>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private pure returns (string) { string memory outputString = new string(_stringLength); uint256 outputPtr; uint256 bytesPtr; assembly { outputPtr := add(outputString, 32) bytesPtr := _rawBytes } _memcpy(outputPtr, bytesPtr, _stringLength); return outputString; } /// @notice Returns a URI pointing to a metadata package for this token conforming to /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) /// @param _tokenId The ID number of the GanToken whose metadata should be returned. function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) { require(erc721Metadata != address(0)); uint256 count; bytes32[4] memory buffer; (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); return _toString(buffer, count); } } contract GanTokenMain is GanNFT { struct Offer { bool isForSale; uint256 tokenId; address seller; uint value; // in ether address onlySellTo; // specify to sell only to a specific person } struct Bid { bool hasBid; uint256 tokenId; address bidder; uint value; } /// @dev mapping of balances for address mapping(address => uint256) public pendingWithdrawals; /// @dev mapping of tokenId to to an offer mapping(uint256 => Offer) public ganTokenOfferedForSale; /// @dev mapping bids to tokenIds mapping(uint256 => Bid) public tokenBids; event BidForGanTokenOffered(uint256 tokenId, uint256 value, address sender); event BidWithdrawn(uint256 tokenId, uint256 value, address bidder); event GanTokenOfferedForSale(uint256 tokenId, uint256 minSalePriceInWei, address onlySellTo); event GanTokenNoLongerForSale(uint256 tokenId); /// @notice Allow a token owner to pull sale /// @param tokenId The id of the token that&#39;s created function ganTokenNoLongerForSale(uint256 tokenId) public payable owns(tokenId) { ganTokenOfferedForSale[tokenId] = Offer(false, tokenId, msg.sender, 0, 0x0); emit GanTokenNoLongerForSale(tokenId); } /// @notice Put a token up for sale /// @param tokenId The id of the token that&#39;s created /// @param minSalePriceInWei desired price of token function offerGanTokenForSale(uint tokenId, uint256 minSalePriceInWei) external payable owns(tokenId) { ganTokenOfferedForSale[tokenId] = Offer(true, tokenId, msg.sender, minSalePriceInWei, 0x0); emit GanTokenOfferedForSale(tokenId, minSalePriceInWei, 0x0); } /// @notice Create a new GanToken with a id and attaches an owner /// @param tokenId The id of the token that&#39;s being created function offerGanTokenForSaleToAddress(uint tokenId, address sendTo, uint256 minSalePriceInWei) external payable { require(tokenIdToOwner[tokenId] == msg.sender); ganTokenOfferedForSale[tokenId] = Offer(true, tokenId, msg.sender, minSalePriceInWei, sendTo); emit GanTokenOfferedForSale(tokenId, minSalePriceInWei, sendTo); } /// @notice Allows an account to buy a NFT gan token that is up for offer /// the token owner must set onlySellTo to the sender /// @param id the id of the token function buyGanToken(uint256 id) public payable { Offer memory offer = ganTokenOfferedForSale[id]; require(offer.isForSale); require(offer.onlySellTo == msg.sender && offer.onlySellTo != 0x0); require(msg.value == offer.value); require(tokenIdToOwner[id] == offer.seller); safeTransferFrom(offer.seller, offer.onlySellTo, id); ganTokenOfferedForSale[id] = Offer(false, id, offer.seller, 0, 0x0); pendingWithdrawals[offer.seller] += msg.value; } /// @notice Allows an account to enter a higher bid on a toekn /// @param tokenId the id of the token function enterBidForGanToken(uint256 tokenId) external payable { Bid memory existing = tokenBids[tokenId]; require(tokenIdToOwner[tokenId] != msg.sender); require(tokenIdToOwner[tokenId] != 0x0); require(msg.value > existing.value); if (existing.value > 0) { // Refund the failing bid pendingWithdrawals[existing.bidder] += existing.value; } tokenBids[tokenId] = Bid(true, tokenId, msg.sender, msg.value); emit BidForGanTokenOffered(tokenId, msg.value, msg.sender); } /// @notice Allows the owner of a token to accept an outstanding bid for that token /// @param tokenId The id of the token that&#39;s being created /// @param price The desired price of token in wei function acceptBid(uint256 tokenId, uint256 price) external payable { require(tokenIdToOwner[tokenId] == msg.sender); Bid memory bid = tokenBids[tokenId]; require(bid.value != 0); require(bid.value == price); safeTransferFrom(msg.sender, bid.bidder, tokenId); tokenBids[tokenId] = Bid(false, tokenId, address(0), 0); pendingWithdrawals[msg.sender] += bid.value; } /// @notice Check is a given id is on sale /// @param tokenId The id of the token in question /// @return a bool whether of not the token is on sale function isOnSale(uint256 tokenId) external view returns (bool) { return ganTokenOfferedForSale[tokenId].isForSale; } /// @notice Gets all the sale data related to a token /// @param tokenId The id of the token /// @return sale information function getSaleData(uint256 tokenId) public view returns (bool isForSale, address seller, uint value, address onlySellTo) { Offer memory offer = ganTokenOfferedForSale[tokenId]; isForSale = offer.isForSale; seller = offer.seller; value = offer.value; onlySellTo = offer.onlySellTo; } /// @notice Gets all the bid data related to a token /// @param tokenId The id of the token /// @return bid information function getBidData(uint256 tokenId) view public returns (bool hasBid, address bidder, uint value) { Bid memory bid = tokenBids[tokenId]; hasBid = bid.hasBid; bidder = bid.bidder; value = bid.value; } /// @notice Allows a bidder to withdraw their bid /// @param tokenId The id of the token function withdrawBid(uint256 tokenId) external payable { Bid memory bid = tokenBids[tokenId]; require(tokenIdToOwner[tokenId] != msg.sender); require(tokenIdToOwner[tokenId] != 0x0); require(bid.bidder == msg.sender); emit BidWithdrawn(tokenId, bid.value, msg.sender); uint amount = bid.value; tokenBids[tokenId] = Bid(false, tokenId, 0x0, 0); // Refund the bid money msg.sender.transfer(amount); } /// @notice Allows a sender to withdraw any amount in the contrat function withdraw() external { uint256 amount = pendingWithdrawals[msg.sender]; // Remember to zero the pending refund before // sending to prevent re-entrancy attacks pendingWithdrawals[msg.sender] = 0; msg.sender.transfer(amount); } }
Check is a given id is on sale tokenId The id of the token in question return a bool whether of not the token is on sale
function isOnSale(uint256 tokenId) external view returns (bool) { return ganTokenOfferedForSale[tokenId].isForSale; }
7,691,948
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./helpers/opensea/meta-transactions/ContentMixin.sol"; import "./helpers/opensea/meta-transactions/NativeMetaTransaction.sol"; contract OwnableDelegateProxy {} /** * Used to delegate ownership of a contract to another address, to save on unneeded transactions to approve contract use for users */ contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } abstract contract OpenseaExtension is ContextMixin, NativeMetaTransaction { using SafeMath for uint256; address proxyRegistryAddress; constructor(address _proxyRegistryAddress) { proxyRegistryAddress = _proxyRegistryAddress; } function _setProxyRegistry(address _proxyRegistryAddress) internal { proxyRegistryAddress = _proxyRegistryAddress; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function _isApprovedForAll(address owner, address operator) internal view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function __msgSender() internal view returns (address sender) { return ContextMixin.msgSender(); } }
Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings./ Whitelist OpenSea proxy contract for easy trading.
function _isApprovedForAll(address owner, address operator) internal view returns (bool) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } }
12,786,183
// contracts/MyNFT.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; contract NeverFightTwice is VRFConsumerBase, IERC721Receiver { bytes32 internal keyHash; uint256 internal fee; address public VRFCoordinator; // rinkeby: 0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B address public LinkToken; // rinkeby: 0x01BE23585060835E02B77ef475b0Cc51aA1e0709a struct NFT { address owner; address NFTcontract; uint256 tokenId; } NFT[] public NFTs; mapping (bytes32 => NFT) requestIdToNFT; mapping (address => uint256) betterToSeed; event Win(address _better); event Lose(address _better); event Bet(address _NFTContract, address _better, uint256 _tokenId); /** * Constructor inherits VRFConsumerBase * * Network: Rinkeby * Chainlink VRF Coordinator address: 0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B * LINK token address: 0x01BE23585060835E02B77ef475b0Cc51aA1e0709 * Key Hash: 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311 */ constructor(address _VRFCoordinator, address _LinkToken, bytes32 _keyHash) public VRFConsumerBase(_VRFCoordinator, _LinkToken) { VRFCoordinator = _VRFCoordinator; // the contract address that's going to verify the numbers returned by the oracle is actually random keyHash = _keyHash; fee = 0.1 * 10**18; // 0.1 LINK } // before this, we need to send LINK tokens to this contract function bet(address _NFTContract, address _better, uint256 _tokenId) public returns (bytes32) { bytes32 requestId = requestRandomness(keyHash, fee, betterToSeed[_better]); // requestRandomness is imported from VRFConsumerBase requestIdToNFT[requestId] = NFT(_better, _NFTContract, _tokenId); emit Bet(_NFTContract, _better, _tokenId); return requestId; } function setBetSeed(uint256 _seed) public { betterToSeed[msg.sender] = _seed; } // only the requested chainlink oracle can call this function function fulfillRandomness (bytes32 requestId, uint256 randomNumber) internal override { NFT memory nft = requestIdToNFT[requestId]; if(randomNumber.mod(2) == 0) { // bettwe lose all NFTs, save this NFT in our database NFTs.push( NFT( address(this), // owner is this contract now nft.NFTcontract, nft.tokenId ) ); emit Lose(nft.owner); } else { // better win another k NFTs // use the random number to find an NFT // send the NFT to the better ERC721(nft.NFTcontract).safeTransferFrom(address(this), nft.owner, nft.tokenId); uint256 winningNFTId = randomNumber.mod(NFTs.length); NFT memory winningNFT = NFTs[winningNFTId]; // remove element NFTs[winningNFTId] = NFTs[NFTs.length - 1]; // Move the last element into the place to delete NFTs.pop(); // Remove the last element ERC721(winningNFT.NFTcontract).safeTransferFrom(address(this), winningNFT.owner, winningNFT.tokenId); emit Win(nft.owner); } } // @param _operator The address which called `safeTransferFrom` function // @param _from The address which previously owned the token function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes memory) public override returns (bytes4) { setBetSeed(uint256(msg.sender)); bet(_operator, _from, _tokenId); return this.onERC721Received.selector; } }
before this, we need to send LINK tokens to this contract
function bet(address _NFTContract, address _better, uint256 _tokenId) public returns (bytes32) { requestIdToNFT[requestId] = NFT(_better, _NFTContract, _tokenId); emit Bet(_NFTContract, _better, _tokenId); return requestId; }
5,517,839
./full_match/1/0x5C73a5F7b4C513CF5aE9F37fA31F44Cb74A7f818/sources/RengaGoblins.sol
Set max mint per wallet (onlyOwner)/
function setMaxMintPerWallet(uint256 _maxMint) external onlyOwner { maxMintPerWallet = _maxMint; }
16,506,546
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; pragma experimental ABIEncoderV2; //Openzeppelin import "./openzeppelin-solidity/contracts/SafeMath.sol"; import "./openzeppelin-solidity/contracts/ERC20/SafeERC20.sol"; import "./openzeppelin-solidity/contracts/ERC1155/IERC1155.sol"; import "./openzeppelin-solidity/contracts/ERC1155/ERC1155Holder.sol"; //Inheritance import './interfaces/IMarketplace.sol'; //Interfaces import './interfaces/IAddressResolver.sol'; import './interfaces/ISettings.sol'; import './interfaces/IAssetHandler.sol'; import './interfaces/ICappedPool.sol'; import './interfaces/IRouter.sol'; contract Marketplace is IMarketplace, ERC1155Holder { using SafeMath for uint; using SafeERC20 for IERC20; IAddressResolver public immutable ADDRESS_RESOLVER; mapping (uint => MarketplaceListing) public marketplaceListings; //starts at index 1; increases without bounds uint public numberOfMarketplaceListings; mapping (address => mapping (address => uint)) public userToListingIndex; //max 1 listing per user per pool //Address of the pool's manager (used for sending manager's fee) //Set to address(0) if invalid pool mapping (address => address) public poolManagers; constructor(address _addressResolver) { ADDRESS_RESOLVER = IAddressResolver(_addressResolver); } /* ========== VIEWS ========== */ /** * @dev Given the address of a user and a pool address, returns the index of the marketplace listing * @notice Returns 0 if user doesn't have a listing in the given pool * @param user Address of the user * @param poolAddress Address of the pool's token * @return uint Index of the user's marketplace listing */ function getListingIndex(address user, address poolAddress) external view override returns (uint) { require(user != address(0), "Marketplace: invalid user address"); require(poolAddress != address(0), "Marketplace: invalid pool address"); return userToListingIndex[poolAddress][user]; } /** * @dev Given the index of a marketplace listing, returns the listing's data * @param index Index of the marketplace listing * @return (address, address, uint, uint, uint) Pool token for sale, address of the seller, pool token's class, number of tokens for sale, USD per token */ function getMarketplaceListing(uint index) external view override indexInRange(index) returns (address, address, uint, uint, uint) { MarketplaceListing memory listing = marketplaceListings[index]; return (listing.poolAddress, listing.seller, listing.tokenClass, listing.numberOfTokens, listing.price); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @dev Purchases the specified number of tokens from the marketplace listing * @param poolAddress Address of the pool token for sale * @param index Index of the marketplace listing * @param numberOfTokens Number of tokens to purchase */ function purchase(address poolAddress, uint index, uint numberOfTokens) external override isValidPool(poolAddress) { require(marketplaceListings[index].exists, "Listing doesn't exist"); require(numberOfTokens > 0 && numberOfTokens <= marketplaceListings[index].numberOfTokens, "Quantity out of bounds"); require(msg.sender != marketplaceListings[index].seller, "Cannot buy your own position"); address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address routerAddress = ADDRESS_RESOLVER.getContractAddress("Router"); address TGEN = ADDRESS_RESOLVER.getContractAddress("TGEN"); uint protocolFee = ISettings(settingsAddress).getParameterValue("MarketplaceProtocolFee"); uint managerFee = ISettings(settingsAddress).getParameterValue("MarketplaceAssetManagerFee"); address stableCoinAddress = IAssetHandler(ADDRESS_RESOLVER.getContractAddress("AssetHandler")).getStableCoinAddress(); uint amountOfUSD = marketplaceListings[index].price.mul(numberOfTokens); IERC20(stableCoinAddress).safeTransferFrom(msg.sender, address(this), amountOfUSD); //Transfer mcUSD to seller IERC20(stableCoinAddress).safeTransfer(marketplaceListings[index].seller, amountOfUSD.mul(10000 - protocolFee - managerFee).div(10000)); //Swap protocol fee for TGEN and send to xTGEN contract uint256 initialTGEN = IERC20(TGEN).balanceOf(address(this)); IRouter(routerAddress).swapAssetForTGEN(stableCoinAddress, amountOfUSD.mul(protocolFee).div(10000)); IERC20(TGEN).safeTransfer(ADDRESS_RESOLVER.getContractAddress("xTGEN"), IERC20(TGEN).balanceOf(address(this)).sub(initialTGEN)); //Pay manager fee IERC20(stableCoinAddress).safeTransfer(ICappedPool(poolAddress).manager(), amountOfUSD.mul(managerFee).div(10000)); //Transfer tokens to buyer IERC1155(poolAddress).setApprovalForAll(msg.sender, true); IERC1155(poolAddress).safeTransferFrom(address(this), msg.sender, marketplaceListings[index].tokenClass, numberOfTokens, ""); //Update marketplace listing if (numberOfTokens == marketplaceListings[index].numberOfTokens) { _removeListing(marketplaceListings[index].seller, poolAddress, index); } else { marketplaceListings[index].numberOfTokens = marketplaceListings[index].numberOfTokens.sub(numberOfTokens); } emit Purchased(msg.sender, poolAddress, index, numberOfTokens, marketplaceListings[index].price); } /** * @dev Creates a new marketplace listing with the given price and quantity * @param poolAddress Address of the pool token for sale * @param tokenClass The class of the pool's token * @param numberOfTokens Number of tokens to sell * @param price USD per token */ function createListing(address poolAddress, uint tokenClass, uint numberOfTokens, uint price) external override isValidPool(poolAddress) { require(userToListingIndex[poolAddress][msg.sender] == 0, "Already have a marketplace listing for this pool"); require(price > 0, "Price must be greater than 0"); require(tokenClass > 0 && tokenClass < 5, "Token class must be between 1 and 4"); require(numberOfTokens > 0 && numberOfTokens <= IERC1155(poolAddress).balanceOf(msg.sender, tokenClass), "Quantity out of bounds"); numberOfMarketplaceListings = numberOfMarketplaceListings.add(1); userToListingIndex[poolAddress][msg.sender] = numberOfMarketplaceListings; marketplaceListings[numberOfMarketplaceListings] = MarketplaceListing(poolAddress, msg.sender, true, tokenClass, numberOfTokens, price); //Transfer tokens to marketplace IERC1155(poolAddress).safeTransferFrom(msg.sender, address(this), tokenClass, numberOfTokens, ""); emit CreatedListing(msg.sender, poolAddress, numberOfMarketplaceListings, tokenClass, numberOfTokens, price); } /** * @dev Removes the marketplace listing at the given index * @param poolAddress Address of the pool's token for sale * @param index Index of the marketplace listing */ function removeListing(address poolAddress, uint index) external override isValidPool(poolAddress) indexInRange(index) onlySeller(poolAddress, index) { uint numberOfTokens = marketplaceListings[index].numberOfTokens; _removeListing(msg.sender, poolAddress, index); //Transfer tokens to seller IERC1155(poolAddress).setApprovalForAll(msg.sender, true); IERC1155(poolAddress).safeTransferFrom(address(this), msg.sender, marketplaceListings[index].tokenClass, numberOfTokens, ""); emit RemovedListing(msg.sender, poolAddress, index); } /** * @dev Updates the price of the given marketplace listing * @param poolAddress Address of the pool's token for sale * @param index Index of the marketplace listing * @param newPrice USD per token */ function updatePrice(address poolAddress, uint index, uint newPrice) external override isValidPool(poolAddress) indexInRange(index) onlySeller(poolAddress, index) { require(newPrice > 0, "New price must be greater than 0"); marketplaceListings[index].price = newPrice; emit UpdatedPrice(msg.sender, poolAddress, index, newPrice); } /** * @dev Updates the number of tokens for sale of the given marketplace listing * @param poolAddress Address of the pool's token for sale * @param index Index of the marketplace listing * @param newQuantity Number of tokens to sell */ function updateQuantity(address poolAddress, uint index, uint newQuantity) external override isValidPool(poolAddress) indexInRange(index) onlySeller(poolAddress, index) { require(newQuantity > 0 && newQuantity <= IERC1155(poolAddress).balanceOf(msg.sender, marketplaceListings[index].tokenClass), "Quantity out of bounds"); uint oldQuantity = marketplaceListings[index].numberOfTokens; marketplaceListings[index].numberOfTokens = newQuantity; if (newQuantity > oldQuantity) { //Transfer tokens to marketplace IERC1155(poolAddress).safeTransferFrom(msg.sender, address(this), marketplaceListings[index].tokenClass, newQuantity.sub(oldQuantity), ""); } else if (oldQuantity < newQuantity) { //Transfer tokens to seller IERC1155(poolAddress).setApprovalForAll(msg.sender, true); IERC1155(poolAddress).safeTransferFrom(address(this), msg.sender, marketplaceListings[index].tokenClass, oldQuantity.sub(newQuantity), ""); } emit UpdatedQuantity(msg.sender, poolAddress, index, newQuantity); } /* ========== INTERNAL FUNCTIONS ========== */ /** * @dev Sets the marketplace listing's 'exists' variable to false and resets quantity. * @param user Address of the seller. * @param poolAddress Address of the pool's token. * @param index Index of the marketplace listing. */ function _removeListing(address user, address poolAddress, uint index) internal { marketplaceListings[index].exists = false; marketplaceListings[index].numberOfTokens = 0; userToListingIndex[poolAddress][user] = 0; } /* ========== MODIFIERS ========== */ modifier indexInRange(uint index) { require(index > 0 && index <= numberOfMarketplaceListings, "Marketplace: Index out of range"); _; } modifier onlySeller(address poolAddress, uint index) { require(index == userToListingIndex[poolAddress][msg.sender], "Marketplace: Only the seller can call this function"); _; } modifier isValidPool(address pool) { require(ADDRESS_RESOLVER.checkIfPoolAddressIsValid(pool), "Marketplace: Invalid pool"); _; } }
Purchases the specified number of tokens from the marketplace listing poolAddress Address of the pool token for sale index Index of the marketplace listing numberOfTokens Number of tokens to purchase/Transfer mcUSD to sellerSwap protocol fee for TGEN and send to xTGEN contractPay manager feeTransfer tokens to buyerUpdate marketplace listing
function purchase(address poolAddress, uint index, uint numberOfTokens) external override isValidPool(poolAddress) { require(marketplaceListings[index].exists, "Listing doesn't exist"); require(numberOfTokens > 0 && numberOfTokens <= marketplaceListings[index].numberOfTokens, "Quantity out of bounds"); require(msg.sender != marketplaceListings[index].seller, "Cannot buy your own position"); address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address routerAddress = ADDRESS_RESOLVER.getContractAddress("Router"); address TGEN = ADDRESS_RESOLVER.getContractAddress("TGEN"); uint protocolFee = ISettings(settingsAddress).getParameterValue("MarketplaceProtocolFee"); uint managerFee = ISettings(settingsAddress).getParameterValue("MarketplaceAssetManagerFee"); address stableCoinAddress = IAssetHandler(ADDRESS_RESOLVER.getContractAddress("AssetHandler")).getStableCoinAddress(); uint amountOfUSD = marketplaceListings[index].price.mul(numberOfTokens); IERC20(stableCoinAddress).safeTransferFrom(msg.sender, address(this), amountOfUSD); IERC20(stableCoinAddress).safeTransfer(marketplaceListings[index].seller, amountOfUSD.mul(10000 - protocolFee - managerFee).div(10000)); uint256 initialTGEN = IERC20(TGEN).balanceOf(address(this)); IRouter(routerAddress).swapAssetForTGEN(stableCoinAddress, amountOfUSD.mul(protocolFee).div(10000)); IERC20(TGEN).safeTransfer(ADDRESS_RESOLVER.getContractAddress("xTGEN"), IERC20(TGEN).balanceOf(address(this)).sub(initialTGEN)); IERC20(stableCoinAddress).safeTransfer(ICappedPool(poolAddress).manager(), amountOfUSD.mul(managerFee).div(10000)); IERC1155(poolAddress).setApprovalForAll(msg.sender, true); IERC1155(poolAddress).safeTransferFrom(address(this), msg.sender, marketplaceListings[index].tokenClass, numberOfTokens, ""); if (numberOfTokens == marketplaceListings[index].numberOfTokens) { _removeListing(marketplaceListings[index].seller, poolAddress, index); } else { marketplaceListings[index].numberOfTokens = marketplaceListings[index].numberOfTokens.sub(numberOfTokens); } emit Purchased(msg.sender, poolAddress, index, numberOfTokens, marketplaceListings[index].price); }
1,753,828
pragma solidity ^0.5.0; import { LocalizationPreferences} from "/ethereum-localized-messaging/contracts/LocalizationPreferences.sol"; import { FissionLocalization } from "./localization/FissionLocalization.sol"; /** * @title The FISSION Status Code Library * * @dev Implementation of broadly applicable status codes for smart contracts. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1066.md */ library FISSION { ///////////////////////////// Decomposed Enums ///////////////////////////// /// @dev The category component of an ERC-1066 status code (ie: the columns) enum Category { Generic, Permission, Find, Negotiation, Availability, Finance, x60, x70, x80, x90, ApplicationSpecific, xB0, xC0, xD0, Cryptography, OffChain } /// @dev The reason component of an ERC-1066 status code (ie: the rows) enum Reason { Failure, Success, AwaitingOthers, Accepted, LowerLimit, ActionRequested, UpperLimit, x06, x07, Inapplicable, x09, x0A, x0B, x0C, x0D, x0E, Informational } //////////////////////////// Simple Status Enum //////////////////////////// /// @dev ERC-1066 status codes encoded as human-readable enums enum Status { // 0x0* Failure, Success, AwatingOthers, Accepted, LowerLimit, RecieverActionRequested, UpperLimit, RESERVEDx07, Inapplicable, RESERVEDx09, RESERVEDx0A, RESERVEDx0B, RESERVEDx0C, RESERVEDx0D, RESERVEDx0E, Informational, // 0x1* Disallowed_Stop, Allowed_Go, AwaitingOthersPermission, PermissionRequested, TooOpen_Insecure, NeedsYourPermission_RequestForContinuation, Revoked, RESERVEDx17, NotApplicatableToCurrentState, RESERVEDx19, RESERVEDx1A, RESERVEDx1B, RESERVEDx1C, RESERVEDx1D, RESERVEDx1E, PermissionDetails_ControlConditions, // 0x2* NotFound_Unequal_OutOfRange, Found_Equal_InRange, AwaitingMatch, MatchRequestSent, BelowRange_Underflow, RequestForMatch, Above_Range_Overflow, RESERVEDx27, Duplicate_Conflict_Collision, RESERVEDx29, RESERVEDx2A, RESERVEDx2B, RESERVEDx2C, RESERVEDx2D, RESERVEDx2E, MatchingInformation, // 0x3* SenderDisagrees_Nay, SenderAgrees_Yea, AwaitingRatification, OfferSent_Voted, QuorumNotReached, ReceiversRatificationRequested, OfferOrVoteLimitReached, RESERVEDx37, AlreadyVoted, RESERVEDx39, RESERVEDx3A, RESERVEDx3B, RESERVEDx3C, RESERVEDx3D, RESERVEDx3E, NegotiationRules_ParticipationInformation, // 0x4* Unavailable, Available, Paused, Queued, NotAvailableYet, AwaitingYourAvailability, Expired, RESERVEDx47, AlreadyDone, RESERVEDx49, RESERVEDx4A, RESERVEDx4B, RESERVEDx4C, RESERVEDx4D, RESERVEDx4E, AvailabilityRules_Information, // 0x5* TransferFailed, TransferSuccessful, AwaitingPaymentFromOthers, Hold_Escrow, InsufficientFunds, FundsRequested, TransferVolumeExceeded, RESERVEDx57, FundsNotRequired, RESERVEDx59, RESERVEDx5A, RESERVEDx5B, RESERVEDx5C, RESERVEDx5D, RESERVEDx5E, FinancialInformation, // 0x6* RESERVEDx60, RESERVEDx61, RESERVEDx62, RESERVEDx63, RESERVEDx64, RESERVEDx65, RESERVEDx66, RESERVEDx67, RESERVEDx68, RESERVEDx69, RESERVEDx6A, RESERVEDx6B, RESERVEDx6C, RESERVEDx6D, RESERVEDx6E, RESERVEDx6F, // 0x7* RESERVEDx70, RESERVEDx71, RESERVEDx72, RESERVEDx73, RESERVEDx74, RESERVEDx75, RESERVEDx76, RESERVEDx77, RESERVEDx78, RESERVEDx79, RESERVEDx7A, RESERVEDx7B, RESERVEDx7C, RESERVEDx7D, RESERVEDx7E, RESERVEDx7F, // 0x8* RESERVEDx80, RESERVEDx81, RESERVEDx82, RESERVEDx83, RESERVEDx84, RESERVEDx85, RESERVEDx86, RESERVEDx87, RESERVEDx88, RESERVEDx89, RESERVEDx8A, RESERVEDx8B, RESERVEDx8C, RESERVEDx8D, RESERVEDx8E, RESERVEDx8F, // 0x9* RESERVEDx90, RESERVEDx91, RESERVEDx92, RESERVEDx93, RESERVEDx94, RESERVEDx95, RESERVEDx96, RESERVEDx97, RESERVEDx98, RESERVEDx99, RESERVEDx9A, RESERVEDx9B, RESERVEDx9C, RESERVEDx9D, RESERVEDx9E, RESERVEDx9F, // 0xA* ApplicationSpecificFailure, ApplicationSpecificSuccess, ApplicationSpecificAwatingOthers, ApplicationSpecificAccepted, ApplicationSpecificLowerLimit, ApplicationSpecificRecieverActionRequested, ApplicationSpecificUpperLimit, RESERVEDxA7, ApplicationSpecific_Inapplicable, RESERVEDxA9, RESERVEDxAA, RESERVEDxAB, RESERVEDxAC, RESERVEDxAD, RESERVEDxAE, ApplicationSpecificInformational, // 0xB* RESERVEDxB0, RESERVEDxB1, RESERVEDxB2, RESERVEDxB3, RESERVEDxB4, RESERVEDxB5, RESERVEDxB6, RESERVEDxB7, RESERVEDxB8, RESERVEDxB9, RESERVEDxBA, RESERVEDxBB, RESERVEDxBC, RESERVEDxBD, RESERVEDxBE, RESERVEDxBF, // 0xC* RESERVEDxC0, RESERVEDxC1, RESERVEDxC2, RESERVEDxC3, RESERVEDxC4, RESERVEDxC5, RESERVEDxC6, RESERVEDxC7, RESERVEDxC8, RESERVEDxC9, RESERVEDxCA, RESERVEDxCB, RESERVEDxCC, RESERVEDxCD, RESERVEDxCE, RESERVEDxCF, // 0xD* RESERVEDxD0, RESERVEDxD1, RESERVEDxD2, RESERVEDxD3, RESERVEDxD4, RESERVEDxD5, RESERVEDxD6, RESERVEDxD7, RESERVEDxD8, RESERVEDxD9, RESERVEDxDA, RESERVEDxDB, RESERVEDxDC, RESERVEDxDD, RESERVEDxDE, RESERVEDxDF, // 0xE* DecryptFailure, DecryptSuccess, AwaitingOtherSignaturesOrKeys, Signed, Unsigned_Untrusted, SignatureRequired, KnownToBeCompromised, RESERVEDxE7, AlreadySigned_NotEncrypted, RESERVEDxE9, RESERVEDxEA, RESERVEDxEB, RESERVEDxEC, RESERVEDxED, RESERVEDxEE, Cryptography_ID_ProofMetadata, // 0xF* OffChainFailure, OffChainSuccess, AwatingOffChainProcess, OffChainProcessStarted, OffChainServiceUnreachable, OffChainActionRequired, OffChainExpiry_LimitReached, RESERVEDxF7, DuplicateOffChainRequest, RESERVEDxF9, RESERVEDxFA, RESERVEDxFB, RESERVEDxFC, RESERVEDxFD, RESERVEDxFE, OffChainInformation } ////////////////////////////// Construction //////////////////////////////// /** * @dev Coerce a status enum into a standard status byte * * @param statusEnum Status enum tag * @return status Binary ERC-1066 status code */ function code(Status statusEnum) public pure returns (byte status) { return byte(uint8(statusEnum)); } /** * @dev Construct a status code from a category and reason. * * @param category Category nibble * @param reason Reason nibble * @return status Binary ERC-1066 status code */ function code(byte category, byte reason) public pure returns (byte status) { return (category << 4) | (byte(0x0F) & reason); } /** * @dev Construct a status code from a category and reason. * * @param category The category * @param reason The reason * @return status Binary ERC-1066 status code */ function code(uint8 category, uint8 reason) public pure returns (byte status) { return byte(uint8((category << 4) + reason)); } /** * @dev Construct a status code from category and reason enums * * @param category Category nibble * @param reason Reason nibble * @return status Binary ERC-1066 status code */ function code(Category category, Reason reason) public pure returns (byte status) { return code(uint8(category), uint8(reason)); } /** * @dev Construct an application-specific status code * * @param appReason Application-specific reason nibble * @return status Binary ERC-1066 status code */ function appCode(byte appReason) public pure returns (byte status) { return (byte(0xA0) | appReason); } /** * @dev Construct an application-specific status code * * @param appReason Application-specific reason * @return status Binary ERC-1066 status code */ function appCode(uint8 appReason) public pure returns (byte status) { return byte(160 + appReason); } /** * @dev Construct an application-specific status code * * @param appReason Application-specific reason enum * @return status Binary ERC-1066 status code */ function appCode(Reason appReason) public pure returns (byte status) { return appCode(uint8(appReason)); } /////////////////////////////// Get Nibbles //////////////////////////////// /** * @dev Extract the category from a status code * * @param status Binary ERC-1066 status code * @return category Category nibble */ function categoryOf(byte status) public pure returns (byte category) { return status >> 4; } /** * @dev Extract the category from a status code enum * * @param status Status enum * @return category Category nibble */ function categoryOf(Status status) public pure returns (byte category) { return categoryOf(byte(uint8(status))); } /** * @dev Extract the reason from a status code * * @param status Binary ERC-1066 status code * @return reason Reason nibble */ function reasonOf(byte status) public pure returns (byte reason) { return status & 0x0F; } /** * @dev Extract the reason from a status code enum * * @param status Status enum * @return reason Reason nibble */ function reasonOf(Status status) public pure returns (byte reason) { return reasonOf(byte(uint8(status))); } /** * @dev Decompose a status code into its category and reason nibbles * * @param status Binary ERC-1066 status code * @return { * "category": "Category nibble", * "reason": "Reason nibble" * } */ function split(byte status) public returns (byte category, byte reason) { return (categoryOf(status), reasonOf(status)); } ////////////////////////////// Localization //////////////////////////////// /** * @dev Lookup an ERC-1444 localization for a particular status code * * @param status Binary ERC-1066 status code * @param prefs The localization registry / proxy contract * @return { * "found": "If the loicalization string was found (`false` if a fallback was used)", * "message": "The localization string" * } */ function localizeBy(byte status, LocalizationPreferences prefs) view public returns (bool found, string memory message) { return prefs.textFor(status); } ////////////////////////// Check Common Statuses /////////////////////////// /** * @dev Check if a status code is non-blocking (ie: an odd number) * * @param status Binary ERC-1066 status code * @return okay A boolean representing if the status code * is okay / nonblocking */ function isOk(byte status) public pure returns (bool okay) { return (uint8(status) % 2) == 1; } /** * @dev Check if a status code is blocking (ie: an even number) * * @param status Binary ERC-1066 status code * @return blocking A boolean representing if the status code is blocking */ function isBlocking(byte status) public pure returns (bool blocking) { return !isOk(status); } /** * @dev Check if a status code represents success (ie: 0x*1) * * @param status Binary ERC-1066 status code * @return successful A boolean representing if the status code * represents success */ function isSuccess(byte status) public pure returns (bool successful) { return reasonOf(status) == 0x01; } /** * @dev Check if a status code represents failure (ie: 0x*0) * * @param status Binary ERC-1066 status code * @return failure A boolean representing if the status code * represents failure */ function isFailure(byte status) public pure returns (bool failure) { return reasonOf(status) == 0x00; } /** * @dev Check if a status code belongs to a particular category * * @param status Binary ERC-1066 status code * @param category Category nibble * @return belongs A boolean representing if the status code belongs to * the target category */ function isCategory(byte status, byte category) public pure returns (bool belongs) { return categoryOf(status) == category; } /** * @dev Check if a status code belongs to a particular category * * @param status Binary ERC-1066 status code * @param category Category enum * @return belongs A boolean representing if the status code belongs to * the target category */ function isCategory(byte status, Category category) public pure returns (bool belongs) { return categoryOf(status) == byte(uint8(category)); } /** * @dev Check if a Status enum belongs to a particular category * * @param status Status enum * @param category Category enum * @return belongs A boolean representing if the status enum belongs to * the target category */ function isCategory(Status status, Category category) public pure returns (bool belongs) { return categoryOf(status) == byte(uint8(category)); } /** * @dev Check if a status code has a particular reason * * @param status Binary ERC-1066 status code * @param reason Reason nibble * @return belongs A boolean representing if the status code has * the target reason */ function isReason(byte status, byte reason) public pure returns (bool belongs) { return reasonOf(status) == reason; } /** * @dev Check if a status code belongs to a particular category * * @param status Binary ERC-1066 status code * @param reason Reason enum * @return belongs A boolean representing if the status code has * the target reason */ function isReason(byte status, Reason reason) public pure returns (bool belongs) { return reasonOf(status) == byte(uint8(reason)); } /** * @dev Check if a Status enum has a particular reason * * @param status Status enum * @param reason Reason enum * @return belongs A boolean representing if the status code has * the target reason */ function isReason(Status status, Reason reason) public pure returns (bool belongs) { return reasonOf(status) == byte(uint8(reason)); } ///////////////////////////////// Requires ///////////////////////////////// /** * @dev Require that a status code be nonblocking, otherwise `revert` * * @param status Binary ERC-1066 status code */ function requireOk(byte status) public pure { require(isOk(status), "Blocking status code"); // TODO: use translation singleton } /** * @dev Require that a status code be nonblocking, * otherwise `revert` with message * * @param status Binary ERC-1066 status code * @param message Revert message */ function requireOk(byte status, string memory message) public pure { require(isOk(status), message); } /** * @dev Require that a status code be nonblocking, * otherwise `revert` with an ERC-1444 automatically localized message * * @param status Binary ERC-1066 status code * @param prefs Localization preference registry */ function requireOk(byte status, LocalizationPreferences prefs) public view { (bool _, string memory message) = localizeBy(status, prefs); requireOk(status, message); } /** * @dev Require that a status code represent success, otherwise `revert` * * @param status Binary ERC-1066 status code */ function requireSuccess(byte status) public pure { require(isSuccess(status), "Unsuccessful status code reason"); } /** * @dev Require that a status code represent success, * otherwise `revert` with message * * @param status Binary ERC-1066 status code * @param message Revert message */ function requireSuccess(byte status, string memory message) public pure { require(isSuccess(status), message); } /** * @dev Require that a status code represent success, * otherwise `revert` with an ERC-1444 automatically localized message * * @param status Binary ERC-1066 status code * @param prefs Localization preference registry */ function requireSuccess(byte status, LocalizationPreferences prefs) public view { (bool _, string memory message) = localizeBy(status, prefs); requireSuccess(status, message); } /** * @dev Require that a status code belongs to a particular category, * otherwise `revert` * * @param status Binary ERC-1066 status code * @param category Required category nibble */ function requireCategory(byte status, byte category) public view { require(isCategory(status, category)); } /** * @dev Require that a status code belongs to a particular category, * otherwise `revert` with message * * @param status Binary ERC-1066 status code * @param category Required category nibble * @param message Revert message */ function requireCategory(byte status, byte category, string memory message) public view { require(isCategory(status, category), message); } /** * @dev Require that a status code belongs to a particular category, * otherwise `revert` with an ERC-1444 automatically localized message * * @param status Binary ERC-1066 status code * @param category Required category nibble * @param prefs Localization preference registry */ function requireCategory( byte status, byte category, LocalizationPreferences prefs ) public view { (bool _, string memory message) = localizeBy(status, prefs); requireCategory(status, category, message); } /** * @dev Require that a status code has a particular reason, * otherwise `revert` * * @param status Binary ERC-1066 status code * @param reason Required reason nibble */ function requireReason(byte status, byte reason) public view { require(isReason(status, reason)); } /** * @dev Require that a status code has a particular reason, * otherwise `revert` with message * * @param status Binary ERC-1066 status code * @param reason Required reason nibble * @param message Revert message */ function requireReason(byte status, byte reason, string memory message) public view { require(isReason(status, reason), message); } /** * @dev Require that a status code has a particular reason, * otherwise `revert` with an ERC-1444 automatically localized message * * @param status Binary ERC-1066 status code * @param reason Required reason nibble * @param prefs Localization preference registry */ function requireReason( byte status, byte reason, LocalizationPreferences prefs ) public view { (bool _, string memory message) = localizeBy(status, prefs); requireReason(status, reason, message); } }
Construct an application-specific status code appReason Application-specific reason return status Binary ERC-1066 status code/
function appCode(uint8 appReason) public pure returns (byte status) { return byte(160 + appReason); }
1,769,153
./partial_match/1/0x207793a5a08e1da37b44c874a5006D32cF1d52C8/sources/XFTanon.sol
Interface for Oracle.sol contract/
interface IOracle { function getCost( uint256 _amount, address _chainlinkFeed, address _xftPool ) external view returns (uint256); function getCostSimpleShift( uint256 _amount, address _chainlinkFeed, address _xftPool, address _tokenPool ) external view returns (uint256); function getTokensForAmount( address _pool, uint32 _interval, address _chainlinkFeed, uint256 _amount, bool _ethLeftSide, address _weth9 ) external view returns (uint256); function ethLeftSide(address _chainlinkFeed) external view returns (bool); function getTokensRaw( address _xftPool, address _tokenPool, uint32 _interval, uint256 _amount, address _weth9 ) external view returns (uint256); function isTokenBelowThreshold( uint256 _threshold, address _pool, uint32 _interval, address _chainlinkFeed, bool _ethLeftSide, address _weth9 ) external view returns (bool); }
16,004,832
// Version of Solidity compiler this program was written for pragma solidity ^0.5.11; interface IBEP20 { /** * @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); } // Crypto mini game contract contract CryptoMiniGame { address payable owner; string public name; struct Game { address addr; uint amountBet; uint8 guess; bool winner; uint ContractBalance; } Game[] lastPlayedBullBearGames; Game[] lastPlayedOneTwoThreeGames; Game[] lastPlayedLotteryGames; //Log game result //Bull bear game: (Bull 0 or bear 1) in order to display it on frontend //Lottery game: (00 => 0 or 01 => 1 .... 09 => 9) in order to display it on frontend //One two three game: (Rock 0 or Paper 1 or Scissors 2) in order to display it on frontend event BullBearGameResult(uint8 side); event LottryGameResult(uint8 side); event OneTwoThreeGameResult(uint8 side); // Contract constructor run only on contract creation. Set owner. constructor() public { owner = msg.sender; name = "Crypro Mini Game dApp"; } IBEP20 GAME_TOKEN = IBEP20(0x680A702b15E20F710D92Ca50A53F1F596474C2D3); //add this modifier to functions, which should only be accessible by the owner modifier onlyOwner { require(msg.sender == owner, "This function can only be launched by the owner"); _; } //Play the Bull Bear game! function BullBearGame(uint8 guess, uint256 amount) public payable returns(bool){ require(guess == 0 || guess == 1, "Variable 'guess' should be either 0 ('Bull') or 1 ('Bear')"); //require(msg.value > 0, "Bet more than 0"); amount = amount*100000000; //require(amount <= address(this).balance - amount, "You cannot bet more than what is available in the Contract Balance"); //require(IERC20(GAME_TOKEN).allowance(address(msg.sender), address(this)) >= amount, "insufficient allowance amount"); IBEP20(GAME_TOKEN).transferFrom(address(msg.sender),address(this), amount); //address(this).balance is increased by msg.value even before code is executed. Thus "address(this).balance-msg.value" //Create a random number. Use the mining difficulty & the player's address, hash it, convert this hex to int, divide by modulo 2 which results in either 0 or 1 and return as uint8 uint8 result = uint8(uint256(keccak256(abi.encodePacked(block.difficulty, msg.sender, block.timestamp)))%2); bool won = false; if (guess == result) { //Won! IBEP20(GAME_TOKEN).transfer(address(msg.sender), amount*18/10); won = true; } emit BullBearGameResult(result); lastPlayedBullBearGames.push(Game(msg.sender, amount, guess, won, IBEP20(GAME_TOKEN).balanceOf(address(this)))); return won; //Return value can only be used by other functions, but not within web3.js (as of 2019) } //Get amount of games played so far function getBullBearGameCount() public view returns(uint) { return lastPlayedBullBearGames.length; } //Get stats about a certain played game, e.g. address of player, amount bet, won or lost, and CMG Token in the contract balance at this point in time function getBullBearGameEntry(uint index) public view returns(address addr, uint amountBet, uint8 guess, bool winner, uint ContractBalance) { return ( lastPlayedBullBearGames[index].addr, lastPlayedBullBearGames[index].amountBet, lastPlayedBullBearGames[index].guess, lastPlayedBullBearGames[index].winner, lastPlayedBullBearGames[index].ContractBalance ); } //Play the Lottery game! function LotteryGame(uint8 guess, uint256 amount) public payable returns(bool){ require(guess == 0 || guess == 1 || guess == 2 || guess == 3 || guess == 4 || guess == 5 || guess == 6 || guess == 7 || guess == 8 || guess == 9, "Variable 'guess' should be either 0 ('00') or 1 ('01') or 2 ('02') or 3 ('03') or 4 ('04') or 5 ('05') or 6 ('06') or 7 ('07') or 8 ('08') or 9 ('09')"); //require(msg.value > 0, "Bet more than 0"); amount = amount*100000000; //require(amount <= address(this).balance - amount, "You cannot bet more than what is available in the Contract balance"); //require(IERC20(GAME_TOKEN).allowance(address(msg.sender), address(this)) >= amount, "insufficient allowance amount"); IBEP20(GAME_TOKEN).transferFrom(address(msg.sender),address(this), amount); //address(this).balance is increased by msg.value even before code is executed. Thus "address(this).balance-msg.value" //Create a random number. Use the mining difficulty & the player's address, hash it, convert this hex to int, divide by modulo 2 which results in either 0 or 1 and return as uint8 uint8 result = uint8(uint256(keccak256(abi.encodePacked(block.difficulty, msg.sender, block.timestamp)))%10); bool won = false; if (guess == result) { //Won! IBEP20(GAME_TOKEN).transfer(address(msg.sender), amount*180/10); won = true; } emit LotteryGameResult(result); lastPlayedLotteryGames.push(Game(msg.sender, amount, guess, won, IBEP20(GAME_TOKEN).balanceOf(address(this)))); return won; //Return value can only be used by other functions, but not within web3.js (as of 2019) } //Get amount of Lottery games played so far function getLotteryGameCount() public view returns(uint) { return lastPlayedLotteryGames.length; } //Get stats about a certain played game, e.g. address of player, amount bet, won or lost, and CMG Token in the Contract balance at this point in time function getLotteryGameEntry(uint index) public view returns(address addr, uint amountBet, uint8 guess, bool winner, uint ContractBalance) { return ( lastPlayedLotteryGames[index].addr, lastPlayedLotteryGames[index].amountBet, lastPlayedLotteryGames[index].guess, lastPlayedLotteryGames[index].winner, lastPlayedLotteryGames[index].ContractBalance ); } //Play the One two three game! function OneTwoThreeGame(uint8 guess, uint256 amount) public payable returns(bool){ require(guess == 0 || guess == 1 || guess == 2, "Variable 'guess' should be either 0 ('Rock') or 1 ('Paper') or 2 ('Scissors')"); //require(msg.value > 0, "Bet more than 0"); amount = amount*100000000; //require(amount <= address(this).balance - amount, "You cannot bet more than what is available in the Contract balance"); //require(IERC20(GAME_TOKEN).allowance(address(msg.sender), address(this)) >= amount, "insufficient allowance amount"); IBEP20(GAME_TOKEN).transferFrom(address(msg.sender),address(this), amount); //address(this).balance is increased by msg.value even before code is executed. Thus "address(this).balance-msg.value" //Create a random number. Use the mining difficulty & the player's address, hash it, convert this hex to int, divide by modulo 2 which results in either 0 or 1 and return as uint8 uint8 result = uint8(uint256(keccak256(abi.encodePacked(block.difficulty, msg.sender, block.timestamp)))%3); uint8 won = 0; if (guess == result) { //Draw! IBEP20(GAME_TOKEN).transfer(address(msg.sender), amount); won = 0; } else if (guess - result == -1 || guess - result == 2) { //Lost won = -1; } else if (guess - result == 1 || guess - result == -2) { //Lost IBEP20(GAME_TOKEN).transfer(address(msg.sender), amount*19/10); won = 1; } emit OneTwoThreeGameResult(result); lastPlayedOneTwoThreeGames.push(Game(msg.sender, amount, guess, won, IBEP20(GAME_TOKEN).balanceOf(address(this)))); return won; //Return value can only be used by other functions, but not within web3.js (as of 2019) } //Get amount of One two three games played so far function getOneTwoThreeGameCount() public view returns(uint) { return lastOneTwoThreeGames.length; } //Get stats about a certain played One two three game, e.g. address of player, amount bet, won or lost, and CMG Token in the Contract balance at this point in time function getOneTwoThreeGameEntry(uint index) public view returns(address addr, uint amountBet, uint8 guess, bool winner, uint ContractBalance) { return ( lastOneTwoThreeGames[index].addr, lastOneTwoThreeGames[index].amountBet, lastOneTwoThreeGames[index].guess, lastOneTwoThreeGames[index].winner, lastOneTwoThreeGames[index].ContractBalance ); } // Contract destructor (Creator of contract can also destroy it and receives remaining ether of contract address). //Advantage compared to "withdraw": SELFDESTRUCT opcode uses negative gas because the operation frees up space on //the blockchain by clearing all of the contract's data function destroy() external onlyOwner { selfdestruct(owner); } //Withdraw money from contract function withdraw(uint amount) external onlyOwner { require(amount < address(this).balance, "You cannot withdraw more than what is available in the contract"); owner.transfer(amount); } // Accept any incoming amount function () external payable {} }
Get stats about a certain played game, e.g. address of player, amount bet, won or lost, and CMG Token in the contract balance at this point in time
function getBullBearGameEntry(uint index) public view returns(address addr, uint amountBet, uint8 guess, bool winner, uint ContractBalance) { return ( lastPlayedBullBearGames[index].addr, lastPlayedBullBearGames[index].amountBet, lastPlayedBullBearGames[index].guess, lastPlayedBullBearGames[index].winner, lastPlayedBullBearGames[index].ContractBalance ); }
2,542,057
/** *Submitted for verification at Etherscan.io on 2022-03-27 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; // File: contracts/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. * * Source: Openzeppelin */ abstract contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(msg.sender); } /** * @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() == msg.sender, "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() external 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) external 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); } } /** * Source: Openzeppelin */ /** * @dev String operations. */ library Strings { /** * @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); } } // OpenZeppelin Contracts v4.4.0 (utils/cryptography/ECDSA.sol) /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0)); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered) = tryRecover(hash, signature); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0)); } if (v != 27 && v != 28) { return (address(0)); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0)); } return (signer); } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // File: contracts/Address.sol /** * Source: Openzeppelin */ /** * @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; } } // File: contracts/IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: contracts/IERC165.sol // https://eips.ethereum.org/EIPS/eip-165 interface IERC165 { /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool); } // File: contracts/IERC2981.sol /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981 is IERC165 { /** * @dev Called with the sale price to determine how much royalty is owed and to whom. * @param tokenId - the NFT asset queried for royalty information * @param salePrice - the sale price of the NFT asset specified by `tokenId` * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for `salePrice` */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // File: contracts/ERC165.sol /** * Source: Openzeppelin */ /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: contracts/IERC721.sol // https://eips.ethereum.org/EIPS/eip-721, http://erc721.org/ /// @title ERC-721 Non-Fungible Token Standard /// @dev See https://eips.ethereum.org/EIPS/eip-721 /// Note: the ERC-165 identifier for this interface is 0x80ac58cd. interface IERC721 is IERC165 { /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256); /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) external view returns (address); /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) external; /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external; /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external; /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) external; /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external; /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view returns (address); /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool); } // File: contracts/IERC721Metadata.sol /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: contracts/ERC721.sol /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. * Made for efficiancy! */ contract ERC721 is ERC165, IERC721, IERC721Metadata, Ownable { using Address for address; using Strings for uint256; uint16 public totalSupply; address public proxyRegistryAddress; string private baseURI; // Mapping from token ID to owner address mapping(uint256 => address) internal _owners; // Mapping owner address to token count mapping(address => uint256) internal _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; constructor(address _openseaProxyRegistry, string memory _baseURI) { proxyRegistryAddress = _openseaProxyRegistry; baseURI = _baseURI; } /** * @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); } function getBaseURI() external view returns(string memory) { return baseURI; } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view 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 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() external pure override returns (string memory) { return "Psychonaut TEST"; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() external pure override returns (string memory) { return "PAD"; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) external view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(baseURI, tokenId.toString(), ".json")); } function setBaseURI(string memory uri) external onlyOwner { baseURI = uri; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) external override { address owner = _owners[tokenId]; require(to != owner, "ERC721: approval to current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view 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) external override { _setApprovalForAll(msg.sender, operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return _operatorApprovals[owner][operator]; } function setOpenseaProxyRegistry(address addr) external onlyOwner { proxyRegistryAddress = addr; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) external override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, 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 ) external override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { require(_isApprovedOrOwner(msg.sender, 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 */ 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 = _owners[tokenId]; return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @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(uint256 amount, address to) internal { uint tokenId = totalSupply; _balances[to] += amount; for (uint i; i < amount; i++) { tokenId++; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } totalSupply += uint16(amount); require( _checkOnERC721Received(address(0), to, tokenId, ""), "ERC721: transfer to non ERC721Receiver implementer" ); // checking it once will make sure that the address can recieve NFTs } /** * @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(_owners[tokenId] == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from]--; _balances[to]++; _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(msg.sender, 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; } } } contract OwnableDelegateProxy {} /** * Used to delegate ownership of a contract to another address, to save on unneeded transactions to approve contract use for users */ contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // File: contracts/Psycho.sol contract Psycho is Ownable, IERC2981, ERC721 { bool private _onlyMintList; bool private _mintingEnabled; address public devWallet; address public teamWallet; mapping (address => uint8) private amountMinted; constructor( address _openseaProxyRegistry, string memory _tempBaseURI ) ERC721(_openseaProxyRegistry, _tempBaseURI) { } function mintFromReserve(uint amount, address to) external onlyOwner { require(amount + totalSupply < 501); _mint(amount, to); } function batchMintFromReserve(uint[] memory amount, address[] memory to) external onlyOwner { uint length = amount.length; require(length == to.length, "array length missmatch"); uint tokenId = totalSupply; uint total; uint cAmount; address cTo; for (uint i; i < length; i++) { assembly { cAmount := mload(add(add(amount, 0x20), mul(i, 0x20))) cTo := mload(add(add(to, 0x20), mul(i, 0x20))) } require(!Address.isContract(cTo), "Cannot mint to contracts!"); _balances[cTo] += cAmount; for (uint f; f < cAmount; f++) { tokenId++; _owners[tokenId] = cTo; emit Transfer(address(0), cTo, tokenId); } total += cAmount; } require(tokenId <= 500, "Exceeds reserve!"); totalSupply += uint16(total); } modifier mintFunc(uint amount, uint price) { require(totalSupply + amount < 7778, "Request exceeds max supply!"); require(msg.value == amount * price, "ETH Amount is not correct!"); _; _mint(amount, msg.sender); } modifier mintlistFunc(uint amount) { require(_onlyMintList, "Minting is not enabled!"); _; amountMinted[msg.sender] += uint8(amount); } function mint(uint256 amount) external payable mintFunc(amount, 1e17) { require(_mintingEnabled, "Minting is not enabled!"); require(amount < 21 && amount != 0, "Invalid request amount!"); } function mintlistMint(bytes calldata sig, uint256 amount) external payable mintlistFunc(amount) mintFunc(amount, 9e16) { require(checkMintlist(sig), "User not on mintlist!"); require(amount + amountMinted[msg.sender] < 4 && amount != 0, "Request exceeds max per wallet!"); } function checkMintlist(bytes calldata sig) private view returns(bool) { return( _checkSig(keccak256(abi.encodePacked(msg.sender)), sig) || IERC721(0x3302F0674f316584092C15B865b9e5C8f10751D2).balanceOf(msg.sender) > 0 ); } function vipMintlistMint(uint256 amount, bytes calldata sig) external payable mintlistFunc(amount) mintFunc(amount, 8e16) { require(checkVipMintlist(sig), "User not on VIP mintlist!"); require(amount + amountMinted[msg.sender] < 6 && amount != 0, "Request exceeds max per wallet!"); } function checkVipMintlist(bytes calldata sig) private view returns(bool) { return( _checkSig(keccak256(abi.encodePacked(msg.sender, "VIP")), sig) || IERC721(0x60E4d786628Fea6478F785A6d7e704777c86a7c6).balanceOf(msg.sender) > 0 || IERC721(0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D).balanceOf(msg.sender) > 0 || IERC721(0x8a90CAb2b38dba80c64b7734e58Ee1dB38B8992e).balanceOf(msg.sender) > 0 ); } function _checkSig(bytes32 hash, bytes memory sig) private view returns(bool) { return ECDSA.recover( ECDSA.toEthSignedMessageHash(hash), sig ) == owner(); } function checkSig(address wallet, bytes3 list, bytes memory sig) external view returns(bool) { return list != bytes3(0) ? _checkSig(keccak256(abi.encodePacked(wallet, list)), sig) : _checkSig(keccak256(abi.encodePacked(wallet)), sig); } function getMsg(address wallet, bytes3 list) external pure returns(bytes32) { return list != bytes3(0) ? keccak256(abi.encodePacked(wallet, list)) : keccak256(abi.encodePacked(wallet)); } function getSalesStatus() external view returns(bool onlyWhitelist, bool mintingEnabled) { onlyWhitelist = _onlyMintList; mintingEnabled = _mintingEnabled; } /** * @notice returns royalty info for EIP2981 supporting marketplaces * @dev Called with the sale price to determine how much royalty is owed and to whom. * @param tokenId - the NFT asset queried for royalty information * @param salePrice - the sale price of the NFT asset specified by `tokenId` * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for `salePrice` */ function royaltyInfo(uint tokenId, uint salePrice) external view override returns(address receiver, uint256 royaltyAmount) { require(_exists(tokenId), "Royality querry for non-existant token!"); return(owner(), (salePrice * 7) / 100); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } function setDevWallet(address addr) onlyOwner external { devWallet = addr; } function setTeamWallet(address addr) onlyOwner external { teamWallet = addr; } function withdraw() onlyOwner external { uint bal = address(this).balance; (bool success1, ) = payable(msg.sender).call{value: bal * 2 / 10, gas: 2600}(""); (bool success2, ) = payable(teamWallet).call{value: bal * 4 / 10, gas: 2600}(""); (bool success3, ) = payable(devWallet).call{value: bal * 4 / 10, gas: 2600}(""); require( success1 && success2 && success3, "One of the transfers failed!" ); } /** * @notice toggles pre sale * @dev enables the pre sale functions. NEVER USE THIS AFTER ENABLING THE PUBLIC SALE FUNCTIONS UNLESS ITS NECESSARY */ function togglePresale() external onlyOwner { _onlyMintList = !_onlyMintList; } /** * @notice toggles the public sale * @dev enables/disables public sale functions and disables pre sale functions */ function togglePublicSale() external onlyOwner { _onlyMintList = false; _mintingEnabled = !_mintingEnabled; } function tokensOfOwner(address owner) external view returns(uint[] memory) { uint[] memory tokens = new uint[](balanceOf(owner)); uint x; for (uint i = 1; i <= totalSupply; i++) { if (_owners[i] == owner) { tokens[x] = i; x++; } } return tokens; } }
toggles pre sale enables the pre sale functions. NEVER USE THIS AFTER ENABLING THE PUBLIC SALE FUNCTIONS UNLESS ITS NECESSARY/
function togglePresale() external onlyOwner { _onlyMintList = !_onlyMintList; }
6,757,965
pragma solidity ^0.4.24; /* ETHEREUM WORLD CUP : 14th June - 15th July 2018 [Russia] - designed and implemented by Norsefire. - thanks to Etherguy and oguzhanox for debugging and front-end respectively. Rules are as follows: * Entry to the game costs 0.2018 Ether. Use the register function when sending this. - Any larger or smaller amount of Ether, will be rejected. * 90% of the entry fee will go towards the prize fund, with 10% forming a fee. Of this fee, half goes to the developer, and half goes directly to Giveth (giveth.io/donate). The entry fee is the only Ether you will need to send for the duration of the tournament, barring the gas you spend for placing predictions. * Buying an entry allows the sender to place predictions on each game in the World Cup, barring those which have already kicked off prior to the time a participant enters. * Predictions can be made (or changed!) at any point up until the indicated kick-off time. * Selecting the correct result for any given game awards the player one point. In the first stage, a participant can also select a draw. This is not available from the RO16 onwards. * If a participant reaches a streak of three or more correct predictions in a row, they receive two points for every correct prediction from the third game until the streak is broken. * If a participant reaches a streak of *five* or more correct predictions in a row, they receive four points for every correct prediction from the fifth game until the streak is broken. * In the event of a tie, the following algorithm is used to decide rankings: - Compare the sum totals of the scores over the last 32 games. - If this produces a draw as well, compare results of the last 16 games. - This repeats until comparing the results of the final. - If it&#39;s a dead heat throughout, a coin-flip (or some equivalent method) will be used to determine the winner. Prizes: FIRST PLACE: 40% of Ether contained within the pot. SECOND PLACE: 30% of Ether contained within the pot. THIRD PLACE: 20% of Ether contained within the pot. FOURTH PLACE: 10% of Ether contained within the pot. Participant Teams and Groups: [Group D] AR - Argentina [Group C] AU - Australia [Group G] BE - Belgium [Group E] BR - Brazil [Group E] CH - Switzerland [Group H] CO - Colombia [Group E] CR - Costa Rica [Group E] CS - Serbia [Group F] DE - Germany [Group C] DK - Denmark [Group A] EG - Egypt [Group G] EN - England [Group B] ES - Spain [Group C] FR - France [Group D] HR - Croatia [Group B] IR - Iran [Group D] IS - Iceland [Group H] JP - Japan [Group F] KR - Republic of Korea [Group B] MA - Morocco [Group F] MX - Mexico [Group D] NG - Nigeria [Group G] PA - Panama [Group C] PE - Peru [Group H] PL - Poland [Group B] PT - Portugal [Group A] RU - Russia [Group A] SA - Saudi Arabia [Group F] SE - Sweden [Group H] SN - Senegal [Group G] TN - Tunisia [Group A] UY - Uruguay */ contract ZeroBTCInterface { function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); } contract ZeroBTCWorldCup { using SafeMath for uint; /* CONSTANTS */ address internal constant administrator = 0x4F4eBF556CFDc21c3424F85ff6572C77c514Fcae; address internal constant givethAddress = 0x5ADF43DD006c6C36506e2b2DFA352E60002d22Dc; address internal constant BTCTKNADDR = 0xB6eD7644C69416d67B522e20bC294A9a9B405B31; ZeroBTCInterface public BTCTKN; string name = "EtherWorldCup"; string symbol = "EWC"; uint internal constant entryFee = 2018e15; uint internal constant ninetyPercent = 18162e14; uint internal constant fivePercent = 1009e14; uint internal constant tenPercent = 2018e14; /* VARIABLES */ mapping (string => int8) worldCupGameID; mapping (int8 => bool) gameFinished; // Is a game no longer available for predictions to be made? mapping (int8 => uint) gameLocked; // A result is either the two digit code of a country, or the word "DRAW". // Country codes are listed above. mapping (int8 => string) gameResult; int8 internal latestGameFinished; uint internal prizePool; uint internal givethPool; uint internal adminPool; int registeredPlayers; mapping (address => bool) playerRegistered; mapping (address => mapping (int8 => bool)) playerMadePrediction; mapping (address => mapping (int8 => string)) playerPredictions; mapping (address => int8[64]) playerPointArray; mapping (address => int8) playerGamesScored; mapping (address => uint) playerStreak; address[] playerList; /* DEBUG EVENTS */ event Registration( address _player ); event PlayerLoggedPrediction( address _player, int _gameID, string _prediction ); event PlayerUpdatedScore( address _player, int _lastGamePlayed ); event Comparison( address _player, uint _gameID, string _myGuess, string _result, bool _correct ); event StartAutoScoring( address _player ); event StartScoring( address _player, uint _gameID ); event DidNotPredict( address _player, uint _gameID ); event RipcordRefund( address _player ); /* CONSTRUCTOR */ constructor () public { // First stage games: these are known in advance. // Thursday 14th June, 2018 worldCupGameID["RU-SA"] = 1; // Russia vs Saudi Arabia gameLocked[1] = 1528988400; // Friday 15th June, 2018 worldCupGameID["EG-UY"] = 2; // Egypt vs Uruguay worldCupGameID["MA-IR"] = 3; // Morocco vs Iran worldCupGameID["PT-ES"] = 4; // Portugal vs Spain gameLocked[2] = 1529064000; gameLocked[3] = 1529074800; gameLocked[4] = 1529085600; // Saturday 16th June, 2018 worldCupGameID["FR-AU"] = 5; // France vs Australia worldCupGameID["AR-IS"] = 6; // Argentina vs Iceland worldCupGameID["PE-DK"] = 7; // Peru vs Denmark worldCupGameID["HR-NG"] = 8; // Croatia vs Nigeria gameLocked[5] = 1529143200; gameLocked[6] = 1529154000; gameLocked[7] = 1529164800; gameLocked[8] = 1529175600; // Sunday 17th June, 2018 worldCupGameID["CR-CS"] = 9; // Costa Rica vs Serbia worldCupGameID["DE-MX"] = 10; // Germany vs Mexico worldCupGameID["BR-CH"] = 11; // Brazil vs Switzerland gameLocked[9] = 1529236800; gameLocked[10] = 1529247600; gameLocked[11] = 1529258400; // Monday 18th June, 2018 worldCupGameID["SE-KR"] = 12; // Sweden vs Korea worldCupGameID["BE-PA"] = 13; // Belgium vs Panama worldCupGameID["TN-EN"] = 14; // Tunisia vs England gameLocked[12] = 1529323200; gameLocked[13] = 1529334000; gameLocked[14] = 1529344800; // Tuesday 19th June, 2018 worldCupGameID["CO-JP"] = 15; // Colombia vs Japan worldCupGameID["PL-SN"] = 16; // Poland vs Senegal worldCupGameID["RU-EG"] = 17; // Russia vs Egypt gameLocked[15] = 1529409600; gameLocked[16] = 1529420400; gameLocked[17] = 1529431200; // Wednesday 20th June, 2018 worldCupGameID["PT-MA"] = 18; // Portugal vs Morocco worldCupGameID["UR-SA"] = 19; // Uruguay vs Saudi Arabia worldCupGameID["IR-ES"] = 20; // Iran vs Spain gameLocked[18] = 1529496000; gameLocked[19] = 1529506800; gameLocked[20] = 1529517600; // Thursday 21st June, 2018 worldCupGameID["DK-AU"] = 21; // Denmark vs Australia worldCupGameID["FR-PE"] = 22; // France vs Peru worldCupGameID["AR-HR"] = 23; // Argentina vs Croatia gameLocked[21] = 1529582400; gameLocked[22] = 1529593200; gameLocked[23] = 1529604000; // Friday 22nd June, 2018 worldCupGameID["BR-CR"] = 24; // Brazil vs Costa Rica worldCupGameID["NG-IS"] = 25; // Nigeria vs Iceland worldCupGameID["CS-CH"] = 26; // Serbia vs Switzerland gameLocked[24] = 1529668800; gameLocked[25] = 1529679600; gameLocked[26] = 1529690400; // Saturday 23rd June, 2018 worldCupGameID["BE-TN"] = 27; // Belgium vs Tunisia worldCupGameID["KR-MX"] = 28; // Korea vs Mexico worldCupGameID["DE-SE"] = 29; // Germany vs Sweden gameLocked[27] = 1529755200; gameLocked[28] = 1529766000; gameLocked[29] = 1529776800; // Sunday 24th June, 2018 worldCupGameID["EN-PA"] = 30; // England vs Panama worldCupGameID["JP-SN"] = 31; // Japan vs Senegal worldCupGameID["PL-CO"] = 32; // Poland vs Colombia gameLocked[30] = 1529841600; gameLocked[31] = 1529852400; gameLocked[32] = 1529863200; // Monday 25th June, 2018 worldCupGameID["UR-RU"] = 33; // Uruguay vs Russia worldCupGameID["SA-EG"] = 34; // Saudi Arabia vs Egypt worldCupGameID["ES-MA"] = 35; // Spain vs Morocco worldCupGameID["IR-PT"] = 36; // Iran vs Portugal gameLocked[33] = 1529935200; gameLocked[34] = 1529935200; gameLocked[35] = 1529949600; gameLocked[36] = 1529949600; // Tuesday 26th June, 2018 worldCupGameID["AU-PE"] = 37; // Australia vs Peru worldCupGameID["DK-FR"] = 38; // Denmark vs France worldCupGameID["NG-AR"] = 39; // Nigeria vs Argentina worldCupGameID["IS-HR"] = 40; // Iceland vs Croatia gameLocked[37] = 1530021600; gameLocked[38] = 1530021600; gameLocked[39] = 1530036000; gameLocked[40] = 1530036000; // Wednesday 27th June, 2018 worldCupGameID["KR-DE"] = 41; // Korea vs Germany worldCupGameID["MX-SE"] = 42; // Mexico vs Sweden worldCupGameID["CS-BR"] = 43; // Serbia vs Brazil worldCupGameID["CH-CR"] = 44; // Switzerland vs Costa Rica gameLocked[41] = 1530108000; gameLocked[42] = 1530108000; gameLocked[43] = 1530122400; gameLocked[44] = 1530122400; // Thursday 28th June, 2018 worldCupGameID["JP-PL"] = 45; // Japan vs Poland worldCupGameID["SN-CO"] = 46; // Senegal vs Colombia worldCupGameID["PA-TN"] = 47; // Panama vs Tunisia worldCupGameID["EN-BE"] = 48; // England vs Belgium gameLocked[45] = 1530194400; gameLocked[46] = 1530194400; gameLocked[47] = 1530208800; gameLocked[48] = 1530208800; // Second stage games and onwards. The string values for these will be overwritten // as the tournament progresses. This is the order that will be followed for the // purposes of calculating winning streaks, as per the World Cup website. // Round of 16 // Saturday 30th June, 2018 worldCupGameID["1C-2D"] = 49; // 1C vs 2D worldCupGameID["1A-2B"] = 50; // 1A vs 2B gameLocked[49] = 1530367200; gameLocked[50] = 1530381600; // Sunday 1st July, 2018 worldCupGameID["1B-2A"] = 51; // 1B vs 2A worldCupGameID["1D-2C"] = 52; // 1D vs 2C gameLocked[51] = 1530453600; gameLocked[52] = 1530468000; // Monday 2nd July, 2018 worldCupGameID["1E-2F"] = 53; // 1E vs 2F worldCupGameID["1G-2H"] = 54; // 1G vs 2H gameLocked[53] = 1530540000; gameLocked[54] = 1530554400; // Tuesday 3rd July, 2018 worldCupGameID["1F-2E"] = 55; // 1F vs 2E worldCupGameID["1H-2G"] = 56; // 1H vs 2G gameLocked[55] = 1530626400; gameLocked[56] = 1530640800; // Quarter Finals // Friday 6th July, 2018 worldCupGameID["W49-W50"] = 57; // W49 vs W50 worldCupGameID["W53-W54"] = 58; // W53 vs W54 gameLocked[57] = 1530885600; gameLocked[58] = 1530900000; // Saturday 7th July, 2018 worldCupGameID["W55-W56"] = 59; // W55 vs W56 worldCupGameID["W51-W52"] = 60; // W51 vs W52 gameLocked[59] = 1530972000; gameLocked[60] = 1530986400; // Semi Finals // Tuesday 10th July, 2018 worldCupGameID["W57-W58"] = 61; // W57 vs W58 gameLocked[61] = 1531245600; // Wednesday 11th July, 2018 worldCupGameID["W59-W60"] = 62; // W59 vs W60 gameLocked[62] = 1531332000; // Third Place Playoff // Saturday 14th July, 2018 worldCupGameID["L61-L62"] = 63; // L61 vs L62 gameLocked[63] = 1531576800; // Grand Final // Sunday 15th July, 2018 worldCupGameID["W61-W62"] = 64; // W61 vs W62 gameLocked[64] = 1531666800; // Set initial variables. latestGameFinished = 0; } /* PUBLIC-FACING COMPETITION INTERACTIONS */ // Register to participate in the competition. Apart from gas costs from // making predictions and updating your score if necessary, this is the // only Ether you will need to spend throughout the tournament. function register() public payable { address _customerAddress = msg.sender; require( !playerRegistered[_customerAddress] && tx.origin == _customerAddress); // Receive the entry fee tokens. require(BTCTKN.transferFrom(_customerAddress, address(this), entryFee)); registeredPlayers = SafeMath.addint256(registeredPlayers, 1); playerRegistered[_customerAddress] = true; playerGamesScored[_customerAddress] = 0; playerList.push(_customerAddress); require(playerRegistered[_customerAddress]); prizePool = prizePool.add(ninetyPercent); givethPool = givethPool.add(fivePercent); adminPool = adminPool.add(fivePercent); emit Registration(_customerAddress); } // Make a prediction for a game. An example would be makePrediction(1, "DRAW") // if you anticipate a draw in the game between Russia and Saudi Arabia, // or makePrediction(2, "UY") if you expect Uruguay to beat Egypt. // The "DRAW" option becomes invalid after the group stage games have been played. function makePrediction(int8 _gameID, string _prediction) public { address _customerAddress = msg.sender; uint predictionTime = now; require(playerRegistered[_customerAddress] && !gameFinished[_gameID] && predictionTime < gameLocked[_gameID]); // No draws allowed after the qualification stage. if (_gameID > 48 && equalStrings(_prediction, "DRAW")) { revert(); } else { playerPredictions[_customerAddress][_gameID] = _prediction; playerMadePrediction[_customerAddress][_gameID] = true; emit PlayerLoggedPrediction(_customerAddress, _gameID, _prediction); } } // What is the current score of a given tournament participant? function showPlayerScores(address _participant) view public returns (int8[64]) { return playerPointArray[_participant]; } function seekApproval() public returns (bool) { BTCTKN.approve(address(this), entryFee); } // What was the last game ID that has had an official score registered for it? function gameResultsLogged() view public returns (int) { return latestGameFinished; } // Sum up the individual scores throughout the tournament and produce a final result. function calculateScore(address _participant) view public returns (int16) { int16 finalScore = 0; for (int8 i = 0; i < latestGameFinished; i++) { uint j = uint(i); int16 gameScore = playerPointArray[_participant][j]; finalScore = SafeMath.addint16(finalScore, gameScore); } return finalScore; } // How many people are taking part in the tournament? function countParticipants() public view returns (int) { return registeredPlayers; } // Keeping this open for anyone to update anyone else so that at the end of // the tournament we can force a score update for everyone using a script. function updateScore(address _participant) public { int8 lastPlayed = latestGameFinished; require(lastPlayed > 0); // Most recent game scored for this participant. int8 lastScored = playerGamesScored[_participant]; // Most recent game played in the tournament (sets bounds for scoring iteration). mapping (int8 => bool) madePrediction = playerMadePrediction[_participant]; mapping (int8 => string) playerGuesses = playerPredictions[_participant]; for (int8 i = lastScored; i < lastPlayed; i++) { uint j = uint(i); uint k = j.add(1); uint streak = playerStreak[_participant]; emit StartScoring(_participant, k); if (!madePrediction[int8(k)]) { playerPointArray[_participant][j] = 0; playerStreak[_participant] = 0; emit DidNotPredict(_participant, k); } else { string storage playerResult = playerGuesses[int8(k)]; string storage actualResult = gameResult[int8(k)]; bool correctGuess = equalStrings(playerResult, actualResult); emit Comparison(_participant, k, playerResult, actualResult, correctGuess); if (!correctGuess) { // The guess was wrong. playerPointArray[_participant][j] = 0; playerStreak[_participant] = 0; } else { // The guess was right. streak = streak.add(1); playerStreak[_participant] = streak; if (streak >= 5) { // On a long streak - four points. playerPointArray[_participant][j] = 4; } else { if (streak >= 3) { // On a short streak - two points. playerPointArray[_participant][j] = 2; } // Not yet at a streak - standard one point. else { playerPointArray[_participant][j] = 1; } } } } } playerGamesScored[_participant] = lastPlayed; } // Invoke this function to get *everyone* up to date score-wise. // This is probably best used at the end of the tournament, to ensure // that prizes are awarded to the correct addresses. // Note: this is going to be VERY gas-intensive. Use it if you&#39;re desperate // to see how you square up against everyone else if they&#39;re slow to // update their own scores. Alternatively, if there&#39;s just one or two // stragglers, you can just call updateScore for them alone. function updateAllScores() public { uint allPlayers = playerList.length; for (uint i = 0; i < allPlayers; i++) { address _toScore = playerList[i]; emit StartAutoScoring(_toScore); updateScore(_toScore); } } // Which game ID has a player last computed their score up to // using the updateScore function? function playerLastScoredGame(address _player) public view returns (int8) { return playerGamesScored[_player]; } // Is a player registered? function playerIsRegistered(address _player) public view returns (bool) { return playerRegistered[_player]; } // What was the official result of a game? function correctResult(int8 _gameID) public view returns (string) { return gameResult[_gameID]; } // What was the caller&#39;s prediction for a given game? function playerGuess(int8 _gameID) public view returns (string) { return playerPredictions[msg.sender][_gameID]; } // Lets us calculate what a participants score would be if they ran updateScore. // Does NOT perform any state update. function viewScore(address _participant) public view returns (uint) { int8 lastPlayed = latestGameFinished; // Most recent game played in the tournament (sets bounds for scoring iteration). mapping (int8 => bool) madePrediction = playerMadePrediction[_participant]; mapping (int8 => string) playerGuesses = playerPredictions[_participant]; uint internalResult = 0; uint internalStreak = 0; for (int8 i = 0; i < lastPlayed; i++) { uint j = uint(i); uint k = j.add(1); uint streak = internalStreak; if (!madePrediction[int8(k)]) { internalStreak = 0; } else { string storage playerResult = playerGuesses[int8(k)]; string storage actualResult = gameResult[int8(k)]; bool correctGuess = equalStrings(playerResult, actualResult); if (!correctGuess) { internalStreak = 0; } else { // The guess was right. internalStreak++; streak++; if (streak >= 5) { // On a long streak - four points. internalResult += 4; } else { if (streak >= 3) { // On a short streak - two points. internalResult += 2; } // Not yet at a streak - standard one point. else { internalResult += 1; } } } } } return internalResult; } /* ADMINISTRATOR FUNCTIONS FOR COMPETITION MAINTENANCE */ modifier isAdministrator() { address _sender = msg.sender; if (_sender == administrator) { _; } else { revert(); } } function _btcToken(address _tokenContract) private pure returns (bool) { return _tokenContract == BTCTKNADDR; // Returns "true" if this is the 0xBTC Token Contract } // As new fixtures become known through progression or elimination, they&#39;re added here. function addNewGame(string _opponents, int8 _gameID) isAdministrator public { worldCupGameID[_opponents] = _gameID; } // When the result of a game is known, enter the result. function logResult(int8 _gameID, string _winner) isAdministrator public { require((int8(0) < _gameID) && (_gameID <= 64) && _gameID == latestGameFinished + 1); // No draws allowed after the qualification stage. if (_gameID > 48 && equalStrings(_winner, "DRAW")) { revert(); } else { require(!gameFinished[_gameID]); gameFinished [_gameID] = true; gameResult [_gameID] = _winner; latestGameFinished = _gameID; assert(gameFinished[_gameID]); } } // Concludes the tournament and issues the prizes, then self-destructs. function concludeTournament(address _first // 40% Ether. , address _second // 30% Ether. , address _third // 20% Ether. , address _fourth) // 10% Ether. isAdministrator public { // Don&#39;t hand out prizes until the final&#39;s... actually been played. require(gameFinished[64] && playerIsRegistered(_first) && playerIsRegistered(_second) && playerIsRegistered(_third) && playerIsRegistered(_fourth)); // Determine 10% of the prize pool to distribute to winners. uint tenth = prizePool.div(10); // Determine the prize allocations. uint firstPrize = tenth.mul(4); uint secondPrize = tenth.mul(3); uint thirdPrize = tenth.mul(2); // Send the first three prizes. BTCTKN.approve(_first, firstPrize); BTCTKN.transferFrom(address(this), _first, firstPrize); BTCTKN.approve(_second, secondPrize); BTCTKN.transferFrom(address(this), _second, secondPrize); BTCTKN.approve(_third, thirdPrize); BTCTKN.transferFrom(address(this), _third, thirdPrize); // Send the tokens raised to Giveth. BTCTKN.approve(givethAddress, givethPool); BTCTKN.transferFrom(address(this), givethAddress, givethPool); // Send the tokens assigned to developer. BTCTKN.approve(administrator, adminPool); BTCTKN.transferFrom(address(this), administrator, adminPool); // Since there might be rounding errors, fourth place gets everything else. uint fourthPrize = ((prizePool.sub(firstPrize)).sub(secondPrize)).sub(thirdPrize); BTCTKN.approve(_fourth, fourthPrize); BTCTKN.transferFrom(address(this), _fourth, fourthPrize); selfdestruct(administrator); } // The emergency escape hatch in case something has gone wrong. // Given the small amount of individual coins per participant, it would // be far more expensive in gas than what&#39;s sent back if required. // You&#39;re going to have to take it on trust that I (the dev, duh), will // sort out refunds. Let&#39;s pray to Suarez it doesn&#39;t need pulling. function pullRipCord() isAdministrator public { uint totalPool = (prizePool.add(givethPool)).add(adminPool); BTCTKN.approve(administrator, totalPool); BTCTKN.transferFrom(address(this), administrator, totalPool); selfdestruct(administrator); } /* INTERNAL FUNCTIONS */ // Gateway check - did you send exactly the right amount? function _isCorrectBuyin(uint _buyin) private pure returns (bool) { return _buyin == entryFee; } // Internal comparison between strings, returning 0 if equal, 1 otherwise. function compare(string _a, string _b) private pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } /// Compares two strings and returns true if and only if they are equal. function equalStrings(string _a, string _b) pure private returns (bool) { return compare(_a, _b) == 0; } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function addint16(int16 a, int16 b) internal pure returns (int16) { int16 c = a + b; assert(c >= a); return c; } function addint256(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; assert(c >= a); return c; } }
Gateway check - did you send exactly the right amount?
function _isCorrectBuyin(uint _buyin) private pure returns (bool) { return _buyin == entryFee; }
7,826,964
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; import "@yield-protocol/utils-v2/contracts/access/AccessControl.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastBytes32Bytes6.sol"; import "@yield-protocol/utils-v2/contracts/token/IERC20Metadata.sol"; import "@yield-protocol/vault-interfaces/IOracle.sol"; import "../../constants/Constants.sol"; import "./AggregatorV3Interface.sol"; /** * @title ChainlinkMultiOracle * @notice Chainlink only uses USD or ETH as a quote in the aggregators, and we will use only ETH */ contract ChainlinkMultiOracle is IOracle, AccessControl, Constants { using CastBytes32Bytes6 for bytes32; event SourceSet(bytes6 indexed baseId, IERC20Metadata base, bytes6 indexed quoteId, IERC20Metadata quote, address indexed source); struct Source { address source; uint8 baseDecimals; uint8 quoteDecimals; bool inverse; } mapping(bytes6 => mapping(bytes6 => Source)) public sources; /// @dev Set or reset an oracle source and its inverse function setSource(bytes6 baseId, IERC20Metadata base, bytes6 quoteId, IERC20Metadata quote, address source) external auth { sources[baseId][quoteId] = Source({ source: source, baseDecimals: base.decimals(), quoteDecimals: quote.decimals(), inverse: false }); emit SourceSet(baseId, base, quoteId, quote, source); if (baseId != quoteId) { sources[quoteId][baseId] = Source({ source: source, baseDecimals: quote.decimals(), // We are reversing the base and the quote quoteDecimals: base.decimals(), inverse: true }); emit SourceSet(quoteId, quote, baseId, base, source); } } /// @dev Convert amountBase base into quote at the latest oracle price. function peek(bytes32 baseId, bytes32 quoteId, uint256 amountBase) external view virtual override returns (uint256 amountQuote, uint256 updateTime) { if (baseId == quoteId) return (amountBase, block.timestamp); if (baseId == ETH || quoteId == ETH) (amountQuote, updateTime) = _peek(baseId.b6(), quoteId.b6(), amountBase); else (amountQuote, updateTime) = _peekThroughETH(baseId.b6(), quoteId.b6(), amountBase); } /// @dev Convert amountBase base into quote at the latest oracle price, updating state if necessary. Same as `peek` for this oracle. function get(bytes32 baseId, bytes32 quoteId, uint256 amountBase) external virtual override returns (uint256 amountQuote, uint256 updateTime) { if (baseId == quoteId) return (amountBase, block.timestamp); if (baseId == ETH || quoteId == ETH) (amountQuote, updateTime) = _peek(baseId.b6(), quoteId.b6(), amountBase); else (amountQuote, updateTime) = _peekThroughETH(baseId.b6(), quoteId.b6(), amountBase); } /// @dev Convert amountBase base into quote at the latest oracle price. function _peek(bytes6 baseId, bytes6 quoteId, uint256 amountBase) private view returns (uint amountQuote, uint updateTime) { int price; uint80 roundId; uint80 answeredInRound; Source memory source = sources[baseId][quoteId]; require (source.source != address(0), "Source not found"); (roundId, price,, updateTime, answeredInRound) = AggregatorV3Interface(source.source).latestRoundData(); require(price > 0, "Chainlink price <= 0"); require(updateTime != 0, "Incomplete round"); require(answeredInRound >= roundId, "Stale price"); if (source.inverse == true) { // ETH/USDC: 1 ETH (*10^18) * (1^6)/(286253688799857 ETH per USDC) = 3493404763 USDC wei amountQuote = amountBase * (10 ** source.quoteDecimals) / uint(price); } else { // USDC/ETH: 3000 USDC (*10^6) * 286253688799857 ETH per USDC / 10^6 = 858761066399571000 ETH wei amountQuote = amountBase * uint(price) / (10 ** source.baseDecimals); } } /// @dev Convert amountBase base into quote at the latest oracle price, using ETH as an intermediate step. function _peekThroughETH(bytes6 baseId, bytes6 quoteId, uint256 amountBase) private view returns (uint amountQuote, uint updateTime) { (uint256 ethAmount, uint256 updateTime1) = _peek(baseId, ETH, amountBase); (amountQuote, updateTime) = _peek(ETH, quoteId, ethAmount); if (updateTime1 < updateTime) updateTime = updateTime1; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "hardhat/console.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes4` identifier. These are expected to be the * signatures for all the functions in the contract. Special roles should be exposed * in the external API and be unique: * * ``` * bytes4 public constant ROOT = 0x00000000; * ``` * * Roles represent restricted access to a function call. For that purpose, use {auth}: * * ``` * function foo() public auth { * ... * } * ``` * * 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 `ROOT`, 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 `ROOT` 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. */ contract AccessControl { struct RoleData { mapping (address => bool) members; bytes4 adminRole; } mapping (bytes4 => RoleData) private _roles; bytes4 public constant ROOT = 0x00000000; bytes4 public constant ROOT4146650865 = 0x00000000; // Collision protection for ROOT, test with ROOT12007226833() bytes4 public constant LOCK = 0xFFFFFFFF; // Used to disable further permissioning of a function bytes4 public constant LOCK8605463013 = 0xFFFFFFFF; // Collision protection for LOCK, test with LOCK10462387368() /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role * * `ROOT` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes4 indexed role, bytes4 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call. */ event RoleGranted(bytes4 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(bytes4 indexed role, address indexed account, address indexed sender); /** * @dev Give msg.sender the ROOT role and create a LOCK role with itself as the admin role and no members. * Calling setRoleAdmin(msg.sig, LOCK) means no one can grant that msg.sig role anymore. */ constructor () { _grantRole(ROOT, msg.sender); // Grant ROOT to msg.sender _setRoleAdmin(LOCK, LOCK); // Create the LOCK role by setting itself as its own admin, creating an independent role tree } /** * @dev Each function in the contract has its own role, identified by their msg.sig signature. * ROOT can give and remove access to each function, lock any further access being granted to * a specific action, or even create other roles to delegate admin control over a function. */ modifier auth() { require (_hasRole(msg.sig, msg.sender), "Access denied"); _; } /** * @dev Allow only if the caller has been granted the admin role of `role`. */ modifier admin(bytes4 role) { require (_hasRole(_getRoleAdmin(role), msg.sender), "Only admin"); _; } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes4 role, address account) external view returns (bool) { return _hasRole(role, account); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes4 role) external view returns (bytes4) { return _getRoleAdmin(role); } /** * @dev Sets `adminRole` as ``role``'s admin role. * If ``role``'s admin role is not `adminRole` emits a {RoleAdminChanged} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function setRoleAdmin(bytes4 role, bytes4 adminRole) external virtual admin(role) { _setRoleAdmin(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(bytes4 role, address account) external virtual admin(role) { _grantRole(role, account); } /** * @dev Grants all of `role` in `roles` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - For each `role` in `roles`, the caller must have ``role``'s admin role. */ function grantRoles(bytes4[] memory roles, address account) external virtual { for (uint256 i = 0; i < roles.length; i++) { require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin"); _grantRole(roles[i], account); } } /** * @dev Sets LOCK as ``role``'s admin role. LOCK has no members, so this disables admin management of ``role``. * Emits a {RoleAdminChanged} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function lockRole(bytes4 role) external virtual admin(role) { _setRoleAdmin(role, LOCK); } /** * @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(bytes4 role, address account) external virtual admin(role) { _revokeRole(role, account); } /** * @dev Revokes all of `role` in `roles` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - For each `role` in `roles`, the caller must have ``role``'s admin role. */ function revokeRoles(bytes4[] memory roles, address account) external virtual { for (uint256 i = 0; i < roles.length; i++) { require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin"); _revokeRole(roles[i], 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(bytes4 role, address account) external virtual { require(account == msg.sender, "Renounce only for self"); _revokeRole(role, account); } function _hasRole(bytes4 role, address account) internal view returns (bool) { return _roles[role].members[account]; } function _getRoleAdmin(bytes4 role) internal view returns (bytes4) { return _roles[role].adminRole; } function _setRoleAdmin(bytes4 role, bytes4 adminRole) internal virtual { if (_getRoleAdmin(role) != adminRole) { _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, adminRole); } } function _grantRole(bytes4 role, address account) internal { if (!_hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, msg.sender); } } function _revokeRole(bytes4 role, address account) internal { if (_hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, msg.sender); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library CastBytes32Bytes6 { function b6(bytes32 x) internal pure returns (bytes6 y){ require (bytes32(y = bytes6(x)) == x, "Cast overflow"); } } // SPDX-License-Identifier: MIT // Taken from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/IERC20Metadata.sol pragma solidity ^0.8.0; import "./IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IOracle { /** * @notice Doesn't refresh the price, but returns the latest value available without doing any transactional operations: * @return value in wei */ function peek(bytes32 base, bytes32 quote, uint256 amount) external view returns (uint256 value, uint256 updateTime); /** * @notice Does whatever work or queries will yield the most up-to-date price, and returns it. * @return value in wei */ function get(bytes32 base, bytes32 quote, uint256 amount) external returns (uint256 value, uint256 updateTime); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; contract Constants { bytes32 CHI = "CHI"; bytes32 RATE = "RATE"; bytes6 ETH = "00"; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: 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.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); }
Convert amountBase base into quote at the latest oracle price. ETH/USDC: 1 ETH (10^18) (1^6)/(286253688799857 ETH per USDC) = 3493404763 USDC wei USDC/ETH: 3000 USDC (10^6) 286253688799857 ETH per USDC / 10^6 = 858761066399571000 ETH wei
function _peek(bytes6 baseId, bytes6 quoteId, uint256 amountBase) private view returns (uint amountQuote, uint updateTime) { int price; uint80 roundId; uint80 answeredInRound; Source memory source = sources[baseId][quoteId]; require (source.source != address(0), "Source not found"); (roundId, price,, updateTime, answeredInRound) = AggregatorV3Interface(source.source).latestRoundData(); require(price > 0, "Chainlink price <= 0"); require(updateTime != 0, "Incomplete round"); require(answeredInRound >= roundId, "Stale price"); if (source.inverse == true) { amountQuote = amountBase * (10 ** source.quoteDecimals) / uint(price); amountQuote = amountBase * uint(price) / (10 ** source.baseDecimals); } }
14,412,879
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.4; import "../../openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "../../openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "../../openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "../../openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "../../openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "../interface/IPoolCreator.sol"; abstract contract RewardDistribution is Initializable, ContextUpgradeable { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; IPoolCreator public poolCreator; IERC20Upgradeable public rewardToken; uint256 public periodFinish; uint256 public rewardRate; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; address public rewardDistribution; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; event RewardPaid(address indexed user, uint256 reward); event RewardAdded(uint256 reward, uint256 periodFinish); event RewardRateChanged(uint256 previousRate, uint256 currentRate, uint256 periodFinish); modifier updateReward(address account) { _updateReward(account); _; } modifier onlyOwnerOfPoolCreator() { require(_msgSender() == poolCreator.owner(), "caller must be owner of pool creator"); _; } // virtual methods function balanceOf(address account) public view virtual returns (uint256); function totalSupply() public view virtual returns (uint256); function __RewardDistribution_init_unchained(address rewardToken_, address poolCreator_) internal initializer { rewardToken = IERC20Upgradeable(rewardToken_); poolCreator = IPoolCreator(poolCreator_); } /** * @notice Set reward distribution rate. If there is unfinished distribution, the end block will be changed * according to change of newRewardRate. * * @param newRewardRate New reward distribution rate. */ function setRewardRate(uint256 newRewardRate) external virtual onlyOwnerOfPoolCreator updateReward(address(0)) { if (newRewardRate == 0) { periodFinish = block.number; } else if (periodFinish != 0) { periodFinish = periodFinish.sub(lastUpdateTime).mul(rewardRate).div(newRewardRate).add( block.number ); } emit RewardRateChanged(rewardRate, newRewardRate, periodFinish); rewardRate = newRewardRate; } /** * @notice Add new distributable reward to current pool, this will extend an exist distribution or * start a new distribution if previous one is already ended. * * @param reward Amount of reward to add. */ function notifyRewardAmount(uint256 reward) external virtual onlyOwnerOfPoolCreator updateReward(address(0)) { require(rewardRate > 0, "rewardRate is zero"); uint256 period = reward.div(rewardRate); // already finished or not initialized if (block.number > periodFinish) { lastUpdateTime = block.number; periodFinish = block.number.add(period); emit RewardAdded(reward, periodFinish); } else { // not finished or not initialized periodFinish = periodFinish.add(period); emit RewardAdded(reward, periodFinish); } } /** * @notice Return end block if last distribution is done or current timestamp. */ function lastBlockRewardApplicable() public view returns (uint256) { return block.number <= periodFinish ? block.number : periodFinish; } /** * @notice Return the per token amount of reward. * The expected reward of user is: [amount of share] x rewardPerToken - claimedReward. */ function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastBlockRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div( totalSupply() ) ); } /** * @notice Return real time reward of account. */ function earned(address account) public view returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } /** * @notice Claim all remaining reward of account. */ function getReward() public updateReward(_msgSender()) { address account = _msgSender(); uint256 reward = earned(account); if (reward > 0) { rewards[account] = 0; rewardToken.safeTransfer(account, reward); emit RewardPaid(account, reward); } } function _updateReward(address account) internal { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastBlockRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } } bytes32[50] private __gap; }
Set reward distribution rate. If there is unfinished distribution, the end block will be changed according to change of newRewardRate. newRewardRate New reward distribution rate./
function setRewardRate(uint256 newRewardRate) external virtual onlyOwnerOfPoolCreator updateReward(address(0)) { if (newRewardRate == 0) { periodFinish = block.number; periodFinish = periodFinish.sub(lastUpdateTime).mul(rewardRate).div(newRewardRate).add( block.number ); } emit RewardRateChanged(rewardRate, newRewardRate, periodFinish); rewardRate = newRewardRate; }
13,046,206
./full_match/23294/0x58C75783300dda3a0E168dA991321F7113809309/sources/contracts/CharacterNftContract.sol
PUBLIC GETTERS REGION
function getVaultAddress() public view returns (address) { return _vaultAddress; }
3,843,067
pragma solidity ^0.5.0; import "./ERC20Interface.sol"; //import "ERC20Interface.sol"; /// @title Kyber Network interface interface KyberNetworkProxyInterface { function maxGasPrice() external view returns(uint); function getUserCapInWei(address user) external view returns(uint); function getUserCapInTokenWei(address user, ERC20 token) external view returns(uint); function enabled() external view returns(bool); function info(bytes32 id) external view returns(uint); function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) external view returns (uint expectedRate, uint slippageRate); function tradeWithHint(ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId, bytes calldata hint) external payable returns(uint); }
Kyber Network interface
interface KyberNetworkProxyInterface { function maxGasPrice() external view returns(uint); function getUserCapInWei(address user) external view returns(uint); function getUserCapInTokenWei(address user, ERC20 token) external view returns(uint); function enabled() external view returns(bool); function info(bytes32 id) external view returns(uint); function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) external view returns (uint expectedRate, uint slippageRate); function tradeWithHint(ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId, bytes calldata hint) external payable returns(uint); }
5,516,842
./full_match/1/0x0000000000aDEaD599C11A0C9a7475B67852c1D0/sources/contracts/RaffleV2.sol
entries The entries to enter./
function _enterRaffles(EntryCalldata[] calldata entries) private returns (address feeTokenAddress, uint208 expectedValue) { uint256 count = entries.length; for (uint256 i; i < count; ) { EntryCalldata calldata entry = entries[i]; address recipient = entry.recipient == address(0) ? msg.sender : entry.recipient; uint256 raffleId = entry.raffleId; Raffle storage raffle = raffles[raffleId]; if (i == 0) { feeTokenAddress = raffle.feeTokenAddress; revert InvalidCurrency(); } if (entry.pricingOptionIndex >= raffle.pricingOptions.length) { revert InvalidIndex(); } _validateRaffleStatus(raffle, RaffleStatus.Open); if (block.timestamp >= raffle.cutoffTime) { revert CutoffTimeReached(); } uint40 entriesCount; uint208 price; { PricingOption memory pricingOption = raffle.pricingOptions[entry.pricingOptionIndex]; uint40 multiplier = entry.count; if (multiplier == 0) { revert InvalidCount(); } entriesCount = pricingOption.entriesCount * multiplier; price = pricingOption.price * multiplier; uint40 newParticipantEntriesCount = rafflesParticipantsStats[raffleId][recipient].entriesCount + entriesCount; if (newParticipantEntriesCount > raffle.maximumEntriesPerParticipant) { revert MaximumEntriesPerParticipantReached(); } rafflesParticipantsStats[raffleId][recipient].entriesCount = newParticipantEntriesCount; } expectedValue += price; uint256 raffleEntriesCount = raffle.entries.length; uint40 currentEntryIndex; if (raffleEntriesCount == 0) { currentEntryIndex = uint40(_unsafeSubtract(entriesCount, 1)); currentEntryIndex = raffle.entries[_unsafeSubtract(raffleEntriesCount, 1)].currentEntryIndex + entriesCount; } if (raffle.isMinimumEntriesFixed) { if (currentEntryIndex >= raffle.minimumEntries) { revert MaximumEntriesReached(); } } _pushEntry(raffle, currentEntryIndex, recipient); raffle.claimableFees += price; rafflesParticipantsStats[raffleId][msg.sender].amountPaid += price; emit EntrySold(raffleId, msg.sender, recipient, entriesCount, price); if (currentEntryIndex >= _unsafeSubtract(raffle.minimumEntries, 1)) { _drawWinners(raffleId, raffle); } unchecked { ++i; } } }
16,609,668
pragma solidity ^0.5.0; import "../TransferManager.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./ManualApprovalTransferManagerStorage.sol"; /** * @title Transfer Manager module for manually approving transactions between accounts */ contract ManualApprovalTransferManager is ManualApprovalTransferManagerStorage, TransferManager { using SafeMath for uint256; event AddManualApproval( address indexed _from, address indexed _to, uint256 _allowance, uint256 _expiryTime, bytes32 _description, address indexed _addedBy ); event ModifyManualApproval( address indexed _from, address indexed _to, uint256 _expiryTime, uint256 _allowance, bytes32 _description, address indexed _edittedBy ); event RevokeManualApproval( address indexed _from, address indexed _to, address indexed _addedBy ); /** * @notice Constructor * @param _securityToken Address of the security token */ constructor(address _securityToken, address _polyToken) public Module(_securityToken, _polyToken) { } /** * @notice This function returns the signature of configure function */ function getInitFunction() public pure returns(bytes4) { return bytes4(0); } /** * @notice Used to verify the transfer transaction and allow a manually approved transqaction to bypass other restrictions * @param _from Address of the sender * @param _to Address of the receiver * @param _amount The amount of tokens to transfer */ function executeTransfer( address _from, address _to, uint256 _amount, bytes calldata /* _data */ ) external onlySecurityToken returns(Result) { (Result success, bytes32 esc) = _verifyTransfer(_from, _to, _amount); if (esc != bytes32(0)) { uint256 index = approvalIndex[_from][_to] - 1; ManualApproval storage approval = approvals[index]; approval.allowance = approval.allowance.sub(_amount); } return (success); } /** * @notice Used to verify the transfer transaction and allow a manually approved transqaction to bypass other restrictions * @param _from Address of the sender * @param _to Address of the receiver * @param _amount The amount of tokens to transfer */ function verifyTransfer( address _from, address _to, uint256 _amount, bytes memory /* _data */ ) public view returns(Result, bytes32) { return _verifyTransfer(_from, _to, _amount); } function _verifyTransfer( address _from, address _to, uint256 _amount ) internal view returns(Result, bytes32) { uint256 index = approvalIndex[_from][_to]; if (!paused && index != 0) { index--; //Actual index is storedIndex - 1 ManualApproval memory approval = approvals[index]; if ((approval.expiryTime >= now) && (approval.allowance >= _amount)) { return (Result.VALID, bytes32(uint256(address(this)) << 96)); } } return (Result.NA, bytes32(0)); } /** * @notice Adds a pair of addresses to manual approvals * @param _from is the address from which transfers are approved * @param _to is the address to which transfers are approved * @param _allowance is the approved amount of tokens * @param _expiryTime is the time until which the transfer is allowed * @param _description Description about the manual approval */ function addManualApproval( address _from, address _to, uint256 _allowance, uint256 _expiryTime, bytes32 _description ) external withPerm(ADMIN) { _addManualApproval(_from, _to, _allowance, _expiryTime, _description); } function _addManualApproval(address _from, address _to, uint256 _allowance, uint256 _expiryTime, bytes32 _description) internal { require(_expiryTime > now, "Invalid expiry time"); require(_allowance > 0, "Invalid allowance"); if (approvalIndex[_from][_to] != 0) { uint256 index = approvalIndex[_from][_to] - 1; require(approvals[index].expiryTime < now || approvals[index].allowance == 0, "Approval already exists"); _revokeManualApproval(_from, _to); } approvals.push(ManualApproval(_from, _to, _allowance, _expiryTime, _description)); approvalIndex[_from][_to] = approvals.length; emit AddManualApproval(_from, _to, _allowance, _expiryTime, _description, msg.sender); } /** * @notice Adds mutiple manual approvals in batch * @param _from is the address array from which transfers are approved * @param _to is the address array to which transfers are approved * @param _allowances is the array of approved amounts * @param _expiryTimes is the array of the times until which eath transfer is allowed * @param _descriptions is the description array for these manual approvals */ function addManualApprovalMulti( address[] memory _from, address[] memory _to, uint256[] memory _allowances, uint256[] memory _expiryTimes, bytes32[] memory _descriptions ) public withPerm(ADMIN) { _checkInputLengthArray(_from, _to, _allowances, _expiryTimes, _descriptions); for (uint256 i = 0; i < _from.length; i++){ _addManualApproval(_from[i], _to[i], _allowances[i], _expiryTimes[i], _descriptions[i]); } } /** * @notice Modify the existing manual approvals * @param _from is the address from which transfers are approved * @param _to is the address to which transfers are approved * @param _expiryTime is the time until which the transfer is allowed * @param _changeInAllowance is the change in allowance * @param _description Description about the manual approval * @param _increase tells whether the allowances will be increased (true) or decreased (false). * or any value when there is no change in allowances */ function modifyManualApproval( address _from, address _to, uint256 _expiryTime, uint256 _changeInAllowance, bytes32 _description, bool _increase ) external withPerm(ADMIN) { _modifyManualApproval(_from, _to, _expiryTime, _changeInAllowance, _description, _increase); } function _modifyManualApproval( address _from, address _to, uint256 _expiryTime, uint256 _changeInAllowance, bytes32 _description, bool _increase ) internal { /*solium-disable-next-line security/no-block-members*/ require(_expiryTime > now, "Invalid expiry time"); uint256 index = approvalIndex[_from][_to]; require(index != 0, "Approval not present"); index--; //Index is stored in an incremented form. 0 represnts non existant. ManualApproval storage approval = approvals[index]; uint256 allowance = approval.allowance; uint256 expiryTime = approval.expiryTime; require(allowance != 0 && expiryTime > now, "Not allowed"); if (_changeInAllowance > 0) { if (_increase) { // Allowance get increased allowance = allowance.add(_changeInAllowance); } else { // Allowance get decreased if (_changeInAllowance >= allowance) { allowance = 0; } else { allowance = allowance - _changeInAllowance; } } approval.allowance = allowance; } // Greedy storage technique if (expiryTime != _expiryTime) { approval.expiryTime = _expiryTime; } if (approval.description != _description) { approval.description = _description; } emit ModifyManualApproval(_from, _to, _expiryTime, allowance, _description, msg.sender); } /** * @notice Adds mutiple manual approvals in batch * @param _from is the address array from which transfers are approved * @param _to is the address array to which transfers are approved * @param _expiryTimes is the array of the times until which eath transfer is allowed * @param _changeInAllowance is the array of change in allowances * @param _descriptions is the description array for these manual approvals * @param _increase Array of bools that tells whether the allowances will be increased (true) or decreased (false). * or any value when there is no change in allowances */ function modifyManualApprovalMulti( address[] memory _from, address[] memory _to, uint256[] memory _expiryTimes, uint256[] memory _changeInAllowance, bytes32[] memory _descriptions, bool[] memory _increase ) public withPerm(ADMIN) { _checkInputLengthArray(_from, _to, _changeInAllowance, _expiryTimes, _descriptions); require(_increase.length == _changeInAllowance.length, "Input length array mismatch"); for (uint256 i = 0; i < _from.length; i++) { _modifyManualApproval(_from[i], _to[i], _expiryTimes[i], _changeInAllowance[i], _descriptions[i], _increase[i]); } } /** * @notice Removes a pairs of addresses from manual approvals * @param _from is the address from which transfers are approved * @param _to is the address to which transfers are approved */ function revokeManualApproval(address _from, address _to) external withPerm(ADMIN) { _revokeManualApproval(_from, _to); } function _revokeManualApproval(address _from, address _to) internal { uint256 index = approvalIndex[_from][_to]; require(index != 0, "Approval not exist"); // find the record in active approvals array & delete it index--; //Index is stored after incrementation so that 0 represents non existant index uint256 lastApprovalIndex = approvals.length - 1; if (index != lastApprovalIndex) { approvals[index] = approvals[lastApprovalIndex]; approvalIndex[approvals[index].from][approvals[index].to] = index + 1; } delete approvalIndex[_from][_to]; approvals.length--; emit RevokeManualApproval(_from, _to, msg.sender); } /** * @notice Removes mutiple pairs of addresses from manual approvals * @param _from is the address array from which transfers are approved * @param _to is the address array to which transfers are approved */ function revokeManualApprovalMulti(address[] calldata _from, address[] calldata _to) external withPerm(ADMIN) { require(_from.length == _to.length, "Input array length mismatch"); for(uint256 i = 0; i < _from.length; i++){ _revokeManualApproval(_from[i], _to[i]); } } function _checkInputLengthArray( address[] memory _from, address[] memory _to, uint256[] memory _expiryTimes, uint256[] memory _allowances, bytes32[] memory _descriptions ) internal pure { require(_from.length == _to.length && _to.length == _allowances.length && _allowances.length == _expiryTimes.length && _expiryTimes.length == _descriptions.length, "Input array length mismatch" ); } /** * @notice Returns the all active approvals corresponds to an address * @param _user Address of the holder corresponds to whom list of manual approvals * need to return * @return address[] addresses from * @return address[] addresses to * @return uint256[] allowances provided to the approvals * @return uint256[] expiry times provided to the approvals * @return bytes32[] descriptions provided to the approvals */ function getActiveApprovalsToUser(address _user) external view returns(address[] memory, address[] memory, uint256[] memory, uint256[] memory, bytes32[] memory) { uint256 counter = 0; uint256 approvalsLength = approvals.length; for (uint256 i = 0; i < approvalsLength; i++) { if ((approvals[i].from == _user || approvals[i].to == _user) && approvals[i].expiryTime >= now) counter ++; } address[] memory from = new address[](counter); address[] memory to = new address[](counter); uint256[] memory allowance = new uint256[](counter); uint256[] memory expiryTime = new uint256[](counter); bytes32[] memory description = new bytes32[](counter); counter = 0; for (uint256 i = 0; i < approvalsLength; i++) { if ((approvals[i].from == _user || approvals[i].to == _user) && approvals[i].expiryTime >= now) { from[counter]=approvals[i].from; to[counter]=approvals[i].to; allowance[counter]=approvals[i].allowance; expiryTime[counter]=approvals[i].expiryTime; description[counter]=approvals[i].description; counter ++; } } return (from, to, allowance, expiryTime, description); } /** * @notice Get the details of the approval corresponds to _from & _to addresses * @param _from Address of the sender * @param _to Address of the receiver * @return uint256 expiryTime of the approval * @return uint256 allowance provided to the approval * @return uint256 Description provided to the approval */ function getApprovalDetails(address _from, address _to) external view returns(uint256, uint256, bytes32) { uint256 index = approvalIndex[_from][_to]; if (index != 0) { index--; if (index < approvals.length) { ManualApproval storage approval = approvals[index]; return( approval.expiryTime, approval.allowance, approval.description ); } } return (uint256(0), uint256(0), bytes32(0)); } /** * @notice Returns the current number of active approvals */ function getTotalApprovalsLength() external view returns(uint256) { return approvals.length; } /** * @notice Get the details of all approvals * @return address[] addresses from * @return address[] addresses to * @return uint256[] allowances provided to the approvals * @return uint256[] expiry times provided to the approvals * @return bytes32[] descriptions provided to the approvals */ function getAllApprovals() external view returns(address[] memory, address[] memory, uint256[] memory, uint256[] memory, bytes32[] memory) { uint256 approvalsLength = approvals.length; address[] memory from = new address[](approvalsLength); address[] memory to = new address[](approvalsLength); uint256[] memory allowance = new uint256[](approvalsLength); uint256[] memory expiryTime = new uint256[](approvalsLength); bytes32[] memory description = new bytes32[](approvalsLength); for (uint256 i = 0; i < approvalsLength; i++) { from[i]=approvals[i].from; to[i]=approvals[i].to; allowance[i]=approvals[i].allowance; expiryTime[i]=approvals[i].expiryTime; description[i]=approvals[i].description; } return (from, to, allowance, expiryTime, description); } /** * @notice Returns the permissions flag that are associated with ManualApproval transfer manager */ function getPermissions() public view returns(bytes32[] memory) { bytes32[] memory allPermissions = new bytes32[](1); allPermissions[0] = ADMIN; return allPermissions; } }
Removes mutiple pairs of addresses from manual approvals _from is the address array from which transfers are approved _to is the address array to which transfers are approved/
function revokeManualApprovalMulti(address[] calldata _from, address[] calldata _to) external withPerm(ADMIN) { require(_from.length == _to.length, "Input array length mismatch"); for(uint256 i = 0; i < _from.length; i++){ _revokeManualApproval(_from[i], _to[i]); } }
13,034,589
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import {Context} from "@openzeppelin/contracts/utils/Context.sol"; import {ERC165Storage} from "@openzeppelin/contracts/utils/introspection/ERC165Storage.sol"; import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {Pausable} from "@openzeppelin/contracts/security/Pausable.sol"; import {IKODAV3} from "../core/IKODAV3.sol"; import {Konstants} from "../core/Konstants.sol"; import {IERC2981} from "../core/IERC2981.sol"; import {IKOAccessControlsLookup} from "../access/IKOAccessControlsLookup.sol"; import {ICollabRoyaltiesRegistry} from "./ICollabRoyaltiesRegistry.sol"; import {ICollabFundsHandler} from "./handlers/ICollabFundsHandler.sol"; contract CollabRoyaltiesRegistry is Pausable, Konstants, ERC165Storage, IERC2981, ICollabRoyaltiesRegistry { // Admin Events event KODASet(address koda); event AccessControlsSet(address accessControls); event RoyaltyAmountSet(uint256 royaltyAmount); event EmergencyClearRoyalty(uint256 editionId); event HandlerAdded(address handler); event HandlerRemoved(address handler); // Normal Events event RoyaltyRecipientCreated(address creator, address handler, address deployedHandler, address[] recipients, uint256[] splits); event RoyaltiesHandlerSetup(uint256 editionId, address deployedHandler); event FutureRoyaltiesHandlerSetup(uint256 editionId, address deployedHandler); IKODAV3 public koda; IKOAccessControlsLookup public accessControls; // @notice A controlled list of proxies which can be used byt eh KO protocol mapping(address => bool) public isHandlerWhitelisted; // @notice A list of initialised/deployed royalties recipients mapping(address => bool) public deployedRoyaltiesHandlers; /// @notice Funds handler to edition ID mapping - once set all funds are sent here on every sale, including EIP-2981 invocations mapping(uint256 => address) public editionRoyaltiesHandlers; /// @notice KO secondary sale royalty amount uint256 public royaltyAmount = 12_50000; // 12.5% as represented in eip-2981 /// @notice precision 100.00000% uint256 public modulo = 100_00000; modifier onlyContractOrCreator(uint256 _editionId) { require( koda.getCreatorOfEdition(_editionId) == _msgSender() || accessControls.hasContractRole(_msgSender()), "Caller not creator or contract" ); _; } modifier onlyContractOrAdmin() { require( accessControls.hasAdminRole(_msgSender()) || accessControls.hasContractRole(_msgSender()), "Caller not admin or contract" ); _; } modifier onlyAdmin() { require(accessControls.hasAdminRole(_msgSender()), "Caller not admin"); _; } constructor(IKOAccessControlsLookup _accessControls) { accessControls = _accessControls; // _INTERFACE_ID_ERC2981 _registerInterface(0x2a55205a); } /// @notice Set the IKODAV3 dependency - can't be passed to constructor due to circular dependency function setKoda(IKODAV3 _koda) external onlyAdmin { koda = _koda; emit KODASet(address(koda)); } /// @notice Set the IKOAccessControlsLookup dependency. function setAccessControls(IKOAccessControlsLookup _accessControls) external onlyAdmin { accessControls = _accessControls; emit AccessControlsSet(address(accessControls)); } /// @notice Admin setter for changing the default royalty amount function setRoyaltyAmount(uint256 _amount) external onlyAdmin() { require(_amount > 1, "Amount to low"); royaltyAmount = _amount; emit RoyaltyAmountSet(royaltyAmount); } /// @notice Add a new cloneable funds handler function addHandler(address _handler) external onlyAdmin() { // Revert if handler already whitelisted require(isHandlerWhitelisted[_handler] == false, "Handler already registered"); // whitelist handler isHandlerWhitelisted[_handler] = true; // Emit event emit HandlerAdded(_handler); } /// @notice Remove a cloneable funds handler function removeHandler(address _handler) external onlyAdmin() { // remove handler from whitelist isHandlerWhitelisted[_handler] = false; // Emit event emit HandlerRemoved(_handler); } //////////////////////////// /// Royalties setup logic // //////////////////////////// /// @notice Sets up a royalties funds handler /// @dev Can only be called once with the same args as this creates a new contract and we dont want to /// override any currently deployed instance /// @dev Can only be called by an approved artist function createRoyaltiesRecipient( address _handler, address[] calldata _recipients, uint256[] calldata _splits ) external override whenNotPaused returns (address deployedHandler) { validateHandlerArgs(_handler, _recipients, _splits); // Clone funds handler as Minimal deployedHandler with a deterministic address deployedHandler = deployCloneableHandler(_handler, _recipients, _splits); // Emit event emit RoyaltyRecipientCreated(_msgSender(), _handler, deployedHandler, _recipients, _splits); } /// @notice Allows a deployed handler to be set against an edition /// @dev Can be called by edition creator or another approved contract /// @dev Can only be called once per edition /// @dev Provided handler account must already be deployed function useRoyaltiesRecipient(uint256 _editionId, address _deployedHandler) external override whenNotPaused onlyContractOrCreator(_editionId) { // Ensure not already defined i.e. dont overwrite deployed contact require(editionRoyaltiesHandlers[_editionId] == address(0), "Funds handler already registered"); // Ensure there actually was a registration require(deployedRoyaltiesHandlers[_deployedHandler], "No deployed handler found"); // Register the deployed handler for the edition ID editionRoyaltiesHandlers[_editionId] = _deployedHandler; // Emit event emit RoyaltiesHandlerSetup(_editionId, _deployedHandler); } /// @notice Allows an admin set a predetermined royalties recipient against an edition /// @dev assumes the called has provided the correct args and a valid edition function usePredeterminedRoyaltiesRecipient( uint256 _editionId, address _handler, address[] calldata _recipients, uint256[] calldata _splits ) external override whenNotPaused onlyContractOrAdmin { // Ensure not already defined i.e. dont overwrite deployed contact require(editionRoyaltiesHandlers[_editionId] == address(0), "Funds handler already registered"); // Determine salt bytes32 salt = keccak256(abi.encode(_recipients, _splits)); address futureDeployedHandler = Clones.predictDeterministicAddress(_handler, salt); // Register the same proxy for the new edition id editionRoyaltiesHandlers[_editionId] = futureDeployedHandler; // Emit event emit FutureRoyaltiesHandlerSetup(_editionId, futureDeployedHandler); } function createAndUseRoyaltiesRecipient( uint256 _editionId, address _handler, address[] calldata _recipients, uint256[] calldata _splits ) external override whenNotPaused onlyContractOrAdmin returns (address deployedHandler) { validateHandlerArgs(_handler, _recipients, _splits); // Confirm the handler has not already been created address expectedAddress = Clones.predictDeterministicAddress(_handler, keccak256(abi.encode(_recipients, _splits))); require(!deployedRoyaltiesHandlers[expectedAddress], "Already deployed the royalties handler"); // Clone funds handler as Minimal deployedHandler with a deterministic address deployedHandler = deployCloneableHandler(_handler, _recipients, _splits); // Emit event emit RoyaltyRecipientCreated(_msgSender(), _handler, deployedHandler, _recipients, _splits); // Register the deployed handler for the edition ID editionRoyaltiesHandlers[_editionId] = deployedHandler; // Emit event emit RoyaltiesHandlerSetup(_editionId, deployedHandler); } function deployCloneableHandler(address _handler, address[] calldata _recipients, uint256[] calldata _splits) internal returns (address deployedHandler) { // Confirm the handler has not already been created address expectedAddress = Clones.predictDeterministicAddress(_handler, keccak256(abi.encode(_recipients, _splits))); require(!deployedRoyaltiesHandlers[expectedAddress], "Already deployed the royalties handler"); // Clone funds handler as Minimal deployedHandler with a deterministic address deployedHandler = Clones.cloneDeterministic( _handler, keccak256(abi.encode(_recipients, _splits)) ); // Initialize handler ICollabFundsHandler(deployedHandler).init(_recipients, _splits); // Verify that it was initialized properly require( ICollabFundsHandler(deployedHandler).totalRecipients() == _recipients.length, "Funds handler created incorrectly" ); // Record the deployed handler deployedRoyaltiesHandlers[deployedHandler] = true; } function validateHandlerArgs(address _handler, address[] calldata _recipients, uint256[] calldata _splits) internal view { // Require more than 1 recipient require(_recipients.length > 1, "Collab must have more than one funds recipient"); // Recipient and splits array lengths must match require(_recipients.length == _splits.length, "Recipients and splits lengths must match"); // Ensure the handler is know and approved require(isHandlerWhitelisted[_handler], "Handler is not whitelisted"); } /// @notice Allows for the royalty creator to predetermine the recipient address for the funds to be sent to /// @dev It does not deploy it, only allows to predetermine the address function predictedRoyaltiesHandler(address _handler, address[] calldata _recipients, uint256[] calldata _splits) public override view returns (address) { bytes32 salt = keccak256(abi.encode(_recipients, _splits)); return Clones.predictDeterministicAddress(_handler, salt); } /// @notice ability to clear royalty in an emergency situation - this would then default all royalties to the original creator /// @dev Only callable from admin function emergencyResetRoyaltiesHandler(uint256 _editionId) public onlyAdmin { editionRoyaltiesHandlers[_editionId] = address(0); emit EmergencyClearRoyalty(_editionId); } //////////////////// /// Query Methods // //////////////////// /// @notice Is the given token part of an edition that has a collab royalties contract setup? function hasRoyalties(uint256 _tokenId) external override view returns (bool) { // Get the associated edition id for the given token id uint256 editionId = _editionFromTokenId(_tokenId); // Get the proxy registered to the previous edition id address proxy = editionRoyaltiesHandlers[editionId]; // Ensure there actually was a registration return proxy != address(0); } /// @notice Get the proxy for a given edition's funds handler function getRoyaltiesReceiver(uint256 _editionId) external override view returns (address _receiver) { _receiver = editionRoyaltiesHandlers[_editionId]; require(_receiver != address(0), "Edition not setup"); } /// @notice Gets the funds handler proxy address and royalty amount for given edition id function royaltyInfo(uint256 _editionId, uint256 _value) external override view returns (address _receiver, uint256 _royaltyAmount) { _receiver = editionRoyaltiesHandlers[_editionId]; require(_receiver != address(0), "Edition not setup"); _royaltyAmount = (_value / modulo) * royaltyAmount; } }
Remove a cloneable funds handler remove handler from whitelist Emit event
function removeHandler(address _handler) external onlyAdmin() { isHandlerWhitelisted[_handler] = false; emit HandlerRemoved(_handler); }
12,615,227
./full_match/1/0x001eb0D277d5B24A306582387Cfc16Fa37a1375C/sources/contracts/core/VaultAuction.sol
calculate amounts that will be exchanged during auction boundaries positions boundaries liquidityEthUsdc target liquidity for ETH:USDC pool liquidityOsqthEth target liquidity for oSQTH:ETH pool/
function _getTargets( Constants.Boundaries memory boundaries, uint128 liquidityEthUsdc, uint128 liquidityOsqthEth ) internal view returns ( uint256, uint256, uint256 ) { (uint256 ethAmount, uint256 usdcAmount, uint256 osqthAmount) = IVaultTreasury(vaultTreasury) .allAmountsForLiquidity(boundaries, liquidityEthUsdc, liquidityOsqthEth); return (ethAmount, usdcAmount, osqthAmount); }
5,006,996
./full_match/42/0x0465Eb72EEDBf56ecF183293eE5b81E9506A2fd3/sources/browser/Oliever/StakingWiithoutBotg.sol
require(inEpochWindow()); This comparison also ensures there is no reentrancy. require(lastEpochTimestampSec.add(minEpochTimeIntervalSec) < now); Snap the Epoch time to the start of this window. lastEpochTimestampSec = now.sub( now.mod(minEpochTimeIntervalSec)).add(epochWindowOffsetSec);
function mintDistributeRewards() public { if (mintedRewardToken == 0) { mintedRewardToken = (rewardToken.cap()).mul(45).div(1000); } uint256 decreaseAmount = 0; if (epochStatus == 0 && epoch != 0) { decreaseAmount = mintedRewardToken.mul(4461).div(100000); } mintedRewardToken = mintedRewardToken.sub(decreaseAmount); for (uint256 i = 0; i < 1; i++) updatePoolAllocationPoints(0, 100, true);
16,236,171
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMWNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMM0;,dXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMNl. ,kNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMNl ;OWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMNl. .c0WMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMXl.....lKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMXl... .oXWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMXl .'..,dXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMXc..;;'. ,kNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMXc. .'''..:OWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMXc.,x00Oo'.c0WMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMXc.,c:;,.. .lKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMXc .,;:cc,.'dXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMXc.'loooooc'.'xNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMN000OKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMXc......... ,kNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWKk0XXKOOXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMXc .:OWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXkOXKKXX0kXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMX: .c0WMMMMWNKOxdolccccccccloodkOKXWWNXOxK0doxOKxxNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMX: .oK0kl;'............... ..,;;;:xKX0dlcoxkOO0XXXNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMK: ............ .....'',,,,,,,,,,'......... .....':okxloO0xodOOO0000NMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMK: .......... .',,,,,,,,,,,,................''....':oxdlcloxOXXKOkXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMK: ..........''. .,,,,,,,,,,,'....;cc;'.........,,'....;xK0OxdxKXKOONMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMK:..;::::;;;,,'. .,,,,,,,,,,,,'.,kNNKOxl,..''...',,,,'..;kXXXXX0OOKNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMK:........ .',,,,,,,,,,,,..kWO:'..','..','.',,,,,,...oKXXOk0WMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWx. .',,,,,,,,,,,,'.;KK;........ .',,,,,,,,,,'..:kkOXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMK; ..,,,,,,,,,,,,,,,.'OO'.. ... ..,,,,,,,,,,,. 'xWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNc .''......',,,,,,,,,,,,,,,,,..l0:.. .. .,,,,,,,,,,,,..,OWMMMMMMMMMMMMMMMMMMMMMMMMMMMMWXXWMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMk..',,'''''''',,,,,,,,,,,,,,,,,..oO:......... .,,,,,,,,,,,,,. 'OWMMMMMMMMMMMMMMMMMMMMMMMMMWOc.'kMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMNc ...'''''''''.',,,,,,,,,,,,,,,,..cd;........ ..,,,,,,,,,,,;;'.;OMMMMMMMMMMMMMMMMMMMMMMMMXl. .dNWMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMK, .....'''..'''...',,,,,,,,,,,,'.......'''''''',,,,,,,,,;:;..,,:0MMMMMMMMMMMMMMMMMMMMMMXc..'...,cxXMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMO' .''...'''....'........',,,,,,,'.',,,,,,,,,,,,,,,,,,,,,,;:;.''..:XMMMMMMMMMMMMMMMMMMMMWd..',,''...,odddxO0XWMMMMWKKNMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMk..','''''...''''',,''......',,,''.....,,,,,,,,,,,,,,,,,;;:;;,. .oNMMMMMMMMMMMMMMMMMMMX; .,,,,,,,. ......';cooc;..oNMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMk..',,''''..'''',,,,,,,,'.............',,,,,,,,,,,,,,,;:;;;,. .. .kMMMMMMMMMMMMMMMMMMMK, .,,,,,,'..',,,,,''....... ,KMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMM0' ',,,,,,''',,,,,,,,,,,,,,,'''''',,,,,,,,,,,,,,,,,,,;:;..,. ;KMMMMMMMMMMMMMMMMMMNc .,,,,'. .',,,,,,,,,,,,...xWMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMX: .,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,;c:;'. ... :0WMMMMMMMMMMMMMMMMMK:..','. .',,,,,,,,,'...:OWMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMWk..',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,;;;;c;.. .... .xWMMMMMMMMMMMMMMMMMNx. ..... .,,,,,,,'...'lOWMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNl..,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,;:,.':' .:kXWMMMMMMMMMMMMMWNx. ... .'''.....,lkXWMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMK: .,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,'...,::,,. .. .;ldk0KKXXK0Oxoc'....'.. ....';cokKNMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMK;..,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,'...',;:;'.. .... ... . ......''........''''..c0KKXNWMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMKc..',,,,,,,,,,,,,,,,,,,,,,,,,,,,'... .,'.';,. . ... ...',,,'''''',,,,''.''..:KMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNd...,,,,,,,,,,,,,,,,,,,,,,,'... .;;'.',. .,,,,,,,,,,,,'..''..:KMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMW0:..',,,,,,,,,,,,,,,,'..... .',:;''.. ... .. ... .',,,,,,,,,,,''''..lXMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXl...',,,,,'''...... .',,:;. ... .... .... .',,,,,,,,,''''...dNMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWKol:,......... .,;..,,. . .,,,,,,,''''...;0WMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXxlddlc;. .... .... ....';c;,'..... . . .,,,,,,'.''..'dXMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXdccld0N0l'... ....,,..':;.. .... ... .... ... .,,,,,,''...lKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWKxlokXWMMMNkl,. ......,:;'''.. .. ... ... .',,,,,'...c0WMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMW0olllkNMMMMWXKkl'.,:,..;:;,,'. .. ... .....''''''''.... .',,,'...l0WMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXxldxokNMMW0doddl:,;:;,,'.... .... .,,..',,,,,,,,,,,,,,,,'. .'....;dKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXxlcld0X00koccddlc..';;,'.... .. .',,,,,,,,,,,,,,,,,,,,,,'. .':d0NMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWOolokxdddldxxkO0Kl..',,,,,,,'.. ','.. ...,,,,,,,,,,,,,,,,,,,,,'. .dKNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMKoldocldOkdkNWWMMMXc..',,,,,,,,,..cKNXK0Okkxd:..',,,,,,,,,,,,,,,,,,,,'...;,cKMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWOldkocllokKNMMMMWOoc. .',,,,,,,,. .l0WMMMMMMMNx'..',,,,,,,,,,,,,,,,,,,,.. .dNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMKocccd0KXWMMMMW0c.;d:. .',,,,,,. .:kXNWWWMMMWXd,....',,,,,,,,,,,,,'...'oKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMW0ocxXWMWMMMMNx. ;o, . .',,,'. ..',;;;lKMMMMNOo;'...............,ckXWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWOc;dXXxo0WMMO' ..... .. .... .... .xMMMMMMMWXOxolc:::::codkKNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMN0kd:cl;;:c:lKMMk'.'''.................... . .kXO0NMMMMMMMMMMMWWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMKo::,,cl'.:oc;oKWk'.''''''''''''''''''''''. ....ll;;oKMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMk:lo:..,,,,,',;c0k'.''''''''''''''''''''''. ...,cc;:xXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXd::;,:loo;.,ll:xk'.''''''''''''''''''''''. .'';coxKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWk:;clooool,',,,ll..'''''''''''''''''''''.. ..',cx0XWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMk:looooooool:;cll;..'''''''''''''''''''''.. .'',;::cokXWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMOcclllccloool:xNXd........................ ...:do:;,:kWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWKxxxxkkdllllxXMMNxollllllllllllcccccccccc::::l0WN0doOWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWXXXNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // // // // // // // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a "value" member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * * * _Available since v4.1 for address, bool, bytes32, and uint256._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an AddressSlot with member value located at slot. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an BooleanSlot with member value located at slot. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an Bytes32Slot with member value located at slot. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an Uint256Slot with member value located at slot. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if account is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, {isContract} will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's {transfer}: sends "amount" wei to * "recipient", forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by {transfer}, making them unable to receive funds via * {transfer}. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to "recipient", care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level "call". A * plain "call" is an unsafe replacement for a function call: use this * function instead. * * If "target" reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[abi.decode]. * * Requirements: * * - "target" must be a contract. * - calling "target" with "data" must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], but with * "errorMessage" as a fallback revert reason when "target" reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], * but also transferring "value" wei to "target". * * Requirements: * * - the calling contract must have an ETH balance of at least "value". * - the called Solidity function must be {payable}. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[functionCallWithValue], but * with "errorMessage" as a fallback revert reason when "target" reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[functionCall], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[functionCall], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction {delegatecall}. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to {implementation}. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by _implementation(). * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by _implementation(). Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by _implementation(). Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual {_fallback} * call, or as part of the Solidity {fallback} or {receive} functions. * * If overriden should call super._beforeFallback(). */ function _beforeFallback() internal virtual {} } contract NefariousNarwhals is Proxy { /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); constructor() { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = 0x7BBd504B73a45a80A198D0aCB39C524408c488e3; emit Upgraded(0x7BBd504B73a45a80A198D0aCB39C524408c488e3); Address.functionDelegateCall( 0x7BBd504B73a45a80A198D0aCB39C524408c488e3, abi.encodeWithSignature( "init(bool[2],address[4],uint256[8],string[3],bytes[2])", [false,false], [0x0000000000000000000000000000000000000000,0x0000000000000000000000000000000000000000,0x0000000000000000000000000000000000000000,0x1BAAd9BFa20Eb279d2E3f3e859e3ae9ddE666c52], [500,1000,0,0,0,10000,10,10], ["Nefarious Narwhals","NN","QmQdayEUh29UTnEbWrqrYQKg4TAwsGdavGgcxRRvpNqvv7"], ["",""] ) ); } /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation address. */ function implementation() public view returns (address) { return _implementation(); } function _implementation() internal override view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function upgradeTo( address newImplementation, bytes memory data, bool forceCall, uint8 v, bytes32 r, bytes32 s ) external { require(msg.sender == 0xC9Fc61ab66A611C8b62E083dc9F4645372965a37); bytes32 base = keccak256(abi.encode(address(this), newImplementation)); bytes32 hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", base)); require(ecrecover(hash, v, r, s) == 0x1BAAd9BFa20Eb279d2E3f3e859e3ae9ddE666c52); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } emit Upgraded(newImplementation); } }
Perform implementation upgrade Emits an {Upgraded} event./
function upgradeTo( address newImplementation, bytes memory data, bool forceCall, uint8 v, bytes32 r, bytes32 s ) external { require(msg.sender == 0xC9Fc61ab66A611C8b62E083dc9F4645372965a37); bytes32 base = keccak256(abi.encode(address(this), newImplementation)); bytes32 hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", base)); require(ecrecover(hash, v, r, s) == 0x1BAAd9BFa20Eb279d2E3f3e859e3ae9ddE666c52); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } emit Upgraded(newImplementation); }
247,862
/** *Submitted for verification at Etherscan.io on 2021-10-27 */ // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function getOwner() external view returns (address); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); } /* * @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() {} 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; } } 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); } } } } /** * @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; } function increment(uint256 a) internal pure returns (uint256) { uint256 b = a + 1; require(b >= a, "SafeMath: addition overflow"); return b; } function decrement(uint256 a) internal pure returns (uint256) { require(1 <= a, "SafeMath: subtraction overflow"); uint256 b = a - 1; return b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; address private _previousOwner; uint256 private _lockTime; 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() { _owner = msg.sender; } /** * @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() internal view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(_owner); _owner = address(0); } function getUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner function lock() public onlyOwner { _previousOwner = _owner; _owner = address(0); emit OwnershipRenounced(_owner); } function unlock() public { require( _previousOwner == msg.sender, "You don not have permission to unlock" ); require(block.timestamp > _lockTime, "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } /** * @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; } } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } interface ILP { function sync() external; } contract ReedBricks is Context, IERC20, Ownable, Pausable { using SafeMath for uint256; using Address for address; //address private router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address private router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isBlacklisted; uint256 private _totalSupply; uint8 private _decimals; string private _symbol; string private _name; // base controller of the token contract address payable private controller; address payable private feecollector; uint256 private _totalFee = 0; uint256 private _taxFee = 5; //5%// uint256 private immutable _mintcap; uint256 private immutable _burncap; event SwapEnabled(bool enabled); event SwapAndLiquify( uint256 threequarters, uint256 sharedETH, uint256 onequarter ); bool inSwapAndLiquify; bool private swapAndLiquifyEnabled = false; mapping(address => bool) private _isExcluded; IUniswapV2Router02 private uniswapV2Router; IUniswapV2Pair private uniswapV2Pair; address private uniswapV2PairAddress; address public deadAddress = 0x000000000000000000000000000000000000dEaD; address private deadBurn; // LP atomic sync address private lp; ILP private lpContract; bool private buyBackEnabled = false; uint256 private buybackLimit = 10**18; uint256 private buybackDivisor = 100; uint256 private numTokensSellDivisor = 10000; uint256 private maxAmount = 200; bool private privateSaleDropCompleted = true; bool private initialDistributionFinished; mapping(address => bool) allowTransfer; modifier initialDistributionLock() { require( initialDistributionFinished || isOwner() || allowTransfer[msg.sender] ); _; } modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } modifier onlyMaster() { require(msg.sender == controller); _; } modifier onlydeadBurn() { require(msg.sender == deadBurn); _; } constructor( address payable _controller, address payable _feecollector ) { _name = "ReedBricks.com v17"; _symbol = "REEDV17"; _decimals = 18; _totalSupply = 1000 * 10**6 * 10**_decimals; _balances[msg.sender] = _totalSupply; deadBurn = deadAddress; _mintcap = _totalSupply; _burncap = _totalSupply.div(2); controller = _controller; feecollector = _feecollector; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(router); uniswapV2PairAddress = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; setLP(uniswapV2PairAddress); IUniswapV2Pair _uniswapV2Pair = IUniswapV2Pair(uniswapV2PairAddress); uniswapV2Pair = _uniswapV2Pair; emit Transfer(address(0), msg.sender, _totalSupply); } /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address) { return owner(); } /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns the token name. */ function name() external view returns (string memory) { return _name; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() external view override returns (uint256) { return _totalSupply; } /** * @param account The address to query. * @return The balance of the specified address. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @notice Sets contract LP address */ function setLP(address _lp) public onlyOwner{ lp = _lp; lpContract = ILP(_lp); } /** * @dev Returns the mint cap on the token's total supply. */ function mintCap() internal view virtual returns (uint256) { return _mintcap; } /** * @dev Returns the burn cap on the token's total supply. */ function burnCap() internal view virtual returns (uint256) { return _burncap; } function pauseTransfer() public onlyOwner returns (bool) { _pause(); return true; } function blacklistAddress(address account, bool value) external onlyOwner { _isBlacklisted[account] = value; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapEnabled(_enabled); } /** * @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) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external 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 {IERC20}; * * 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 ) external override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "IERC20: 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, "IERC20: decreased allowance below zero" ) ); return true; } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. */ function burn(uint256 amount) public onlyOwner returns (bool) { _burn(_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 { require(sender != address(0), "IERC20: transfer from the zero address"); require( recipient != address(0), "IERC20: transfer to the zero address" ); require( !_isBlacklisted[sender] && !_isBlacklisted[recipient], "Blacklisted address" ); require(amount > 0, "Amount must be greater than Zero"); uint256 contractTokenBalance = balanceOf(address(this)); uint256 _maxTxAmount = _totalSupply.div(maxAmount); uint256 numTokensSell = _totalSupply.div(numTokensSellDivisor); if (sender != owner() && recipient != owner()) { require( amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount." ); } bool overMinimumTokenBalance = contractTokenBalance >= numTokensSell; if ( !inSwapAndLiquify && swapAndLiquifyEnabled && sender != uniswapV2PairAddress ) { if (overMinimumTokenBalance) { swapAndLiquify(numTokensSell); } } // uint256 balance = address(this).balance; // if (buyBackEnabled && balance > buybackLimit) { // buyBackTokens(buybackLimit.div(buybackDivisor)); // } _tokenTransfer(sender,recipient,amount); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into quarters uint256 threequarters = contractTokenBalance.mul(3).div(4); uint256 onequarter = contractTokenBalance.sub(threequarters); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(threequarters); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); uint256 sharedETH = newBalance.div(3); // add liquidity to uniswap addLiquidity(onequarter, sharedETH); // Transfer to marketing address transferToAddressETH(feecollector, sharedETH); emit SwapAndLiquify(threequarters, sharedETH, onequarter); } function buyBackTokens(uint256 amount) private lockTheSwap { if (amount > 0) { swapETHForTokens(amount); } } function transferToAddressETH(address payable recipient, uint256 amount) private { recipient.transfer(amount); } function swapETHForTokens(uint256 amount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); // make the swap uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens( amount, path, deadAddress, // Burn address block.timestamp.add(300) ); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function swapExactETHforTokens( address tokenOut, uint256 amountOut, uint256 deadline ) external payable { address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = tokenOut; uniswapV2Router.swapExactETHForTokens{value: msg.value}( amountOut, path, msg.sender, deadline ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } /** * @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), "IERC20: burn from the zero address"); // require( // _totalSupply - amount <= burnCap(), // "ERC20Capped: burnable cap exceeded" // ); _balances[account] = _balances[account].sub( amount, "IERC20: 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), "IERC20: approve from the zero address"); require(spender != address(0), "IERC20: 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, "IERC20: burn amount exceeds allowance" ) ); } function mint(address to, uint256 amount) external onlyOwner returns (bool) { _mint(to, amount); return true; } /** @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"); // require( // _totalSupply + amount >= mintCap(), // "ERC20Capped: cap exceeded" // ); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return IERC20(tokenAddress).transfer(address(this), tokens); } function _tokenTransfer(address sender, address recipient, uint256 amount) private { if (_isExcluded[sender] || _isExcluded[recipient]) { _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } else { uint256 taxtAmount = amount.mul(_taxFee).div(100); uint256 newAmount = amount.sub(taxtAmount); _balances[sender] = _balances[sender].sub(newAmount); _balances[recipient] = _balances[recipient].add(newAmount); emit Transfer(sender, recipient, amount); } } }
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./ require( _totalSupply + amount >= mintCap(), "ERC20Capped: cap exceeded" );
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); }
12,770,153
pragma solidity ^0.4.11; // Created for conduction of Zaber ICO - http://www.zabercoin.io/ // Copying in whole or in part is prohibited. // This code is the property of ICORating and ICOmachine - http://ICORating.com // Authors: Ivan Fedorov and Dmitry Borodin /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this does not hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @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)); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool _paused = false; function paused() public constant returns(bool) { return _paused; } /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused()); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner public { require(!_paused); _paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner public { require(_paused); _paused = false; Unpause(); } } // Contract interface for transferring current tokens to another contract MigrationAgent { function migrateFrom(address _from, uint256 _value) public; } // (A2) // Contract token contract Token is Pausable{ using SafeMath for uint256; string public constant name = "ZABERcoin"; string public constant symbol = "ZAB"; uint8 public constant decimals = 18; uint256 public totalSupply; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; mapping (address => bool) public unpausedWallet; bool public mintingFinished = false; uint256 public totalMigrated; address public migrationAgent; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Mint(address indexed to, uint256 amount); event MintFinished(); event Migrate(address indexed _from, address indexed _to, uint256 _value); modifier canMint() { require(!mintingFinished); _; } function Token(){ owner = 0x0; } function setOwner() public{ require(owner == 0x0); owner = msg.sender; } // Balance of the specified address function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } // Transfer of tokens from one account to another function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { require (_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } // Returns the number of tokens that _owner trusted to spend from his account _spender function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // Trust _sender and spend _value tokens from your account function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // Transfer of tokens from the trusted address _from to the address _to in the number _value function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); require (_value > 0); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } // Issue new tokens to the address _to in the amount _amount. Available to the owner of the contract (contract Crowdsale) function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } // Stop the release of tokens. This is not possible to cancel. Available to the owner of the contract. // function finishMinting() public onlyOwner returns (bool) { // mintingFinished = true; // MintFinished(); // return true; // } // Redefinition of the method of the returning status of the "Exchange pause". // Never for the owner of an unpaused wallet. function paused() public constant returns(bool) { return super.paused() && !unpausedWallet[msg.sender]; } // Add a wallet ignoring the "Exchange pause". Available to the owner of the contract. function addUnpausedWallet(address _wallet) public onlyOwner { unpausedWallet[_wallet] = true; } // Remove the wallet ignoring the "Exchange pause". Available to the owner of the contract. function delUnpausedWallet(address _wallet) public onlyOwner { unpausedWallet[_wallet] = false; } // Enable the transfer of current tokens to others. Only 1 time. Disabling this is not possible. // Available to the owner of the contract. function setMigrationAgent(address _migrationAgent) public onlyOwner { require(migrationAgent == 0x0); migrationAgent = _migrationAgent; } // Reissue your tokens. function migrate() public { uint256 value = balances[msg.sender]; require(value > 0); totalSupply = totalSupply.sub(value); totalMigrated = totalMigrated.add(value); MigrationAgent(migrationAgent).migrateFrom(msg.sender, value); Migrate(msg.sender,migrationAgent,value); balances[msg.sender] = 0; } } // (A3) // Contract for freezing of investors' funds. Hence, investors will be able to withdraw money if the // round does not attain the softcap. From here the wallet of the beneficiary will receive all the // money (namely, the beneficiary, not the manager's wallet). contract RefundVault is Ownable { using SafeMath for uint256; uint8 public round = 0; enum State { Active, Refunding, Closed } mapping (uint8 => mapping (address => uint256)) public deposited; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault() public { state = State.Active; } // Depositing funds on behalf of an ICO investor. Available to the owner of the contract (Crowdsale Contract). function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[round][investor] = deposited[round][investor].add(msg.value); } // Move the collected funds to a specified address. Available to the owner of the contract. function close(address _wallet) onlyOwner public { require(state == State.Active); require(_wallet != 0x0); state = State.Closed; Closed(); _wallet.transfer(this.balance); } // Allow refund to investors. Available to the owner of the contract. function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } // Return the funds to a specified investor. In case of failure of the round, the investor // should call this method of this contract (RefundVault) or call the method claimRefund of Crowdsale // contract. This function should be called either by the investor himself, or the company // (or anyone) can call this function in the loop to return funds to all investors en masse. function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[round][investor]; deposited[round][investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } function restart() onlyOwner public{ require(state == State.Closed); round += 1; state = State.Active; } // Destruction of the contract with return of funds to the specified address. Available to // the owner of the contract. function del(address _wallet) public onlyOwner { selfdestruct(_wallet); } } contract DistributorRefundVault is RefundVault{ address public taxCollector; uint256 public taxValue; function DistributorRefundVault(address _taxCollector, uint256 _taxValue) RefundVault() public{ taxCollector = _taxCollector; taxValue = _taxValue; } function close(address _wallet) onlyOwner public { require(state == State.Active); require(_wallet != 0x0); state = State.Closed; Closed(); uint256 allPay = this.balance; uint256 forTarget1; uint256 forTarget2; if(taxValue <= allPay){ forTarget1 = taxValue; forTarget2 = allPay.sub(taxValue); taxValue = 0; }else { taxValue = taxValue.sub(allPay); forTarget1 = allPay; forTarget2 = 0; } if(forTarget1 != 0){ taxCollector.transfer(forTarget1); } if(forTarget2 != 0){ _wallet.transfer(forTarget2); } } } // (A1) // The main contract for the sale and management of rounds. contract Crowdsale{ using SafeMath for uint256; enum ICOType {preSale, sale} enum Roles {beneficiary,accountant,manager,observer,team} Token public token; bool public isFinalized = false; bool public isInitialized = false; bool public isPausedCrowdsale = false; mapping (uint8 => address) public wallets; uint256 public maxProfit; // percent from 0 to 90 uint256 public minProfit; // percent from 0 to 90 uint256 public stepProfit; // percent step, from 1 to 50 (please, read doc!) uint256 public startTime; // unixtime uint256 public endDiscountTime; // unixtime uint256 public endTime; // unixtime // How many tokens (excluding the bonus) are transferred to the investor in exchange for 1 ETH // **THOUSANDS** 10^3 for human, 1**3 for Solidity, 1e3 for MyEtherWallet (MEW). // Example: if 1ETH = 40.5 Token ==> use 40500 uint256 public rate; // If the round does not attain this value before the closing date, the round is recognized as a // failure and investors take the money back (the founders will not interfere in any way). // **QUINTILLIONS** 10^18 / 1**18 / 1e18. Example: softcap=15ETH ==> use 15**18 (Solidity) or 15e18 (MEW) uint256 public softCap; // The maximum possible amount of income // **QUINTILLIONS** 10^18 / 1**18 / 1e18. Example: hardcap=123.45ETH ==> use 123450**15 (Solidity) or 12345e15 (MEW) uint256 public hardCap; // If the last payment is slightly higher than the hardcap, then the usual contracts do // not accept it, because it goes beyond the hardcap. However it is more reasonable to accept the // last payment, very slightly raising the hardcap. The value indicates by how many ETH the // last payment can exceed the hardcap to allow it to be paid. Immediately after this payment, the // round closes. The funders should write here a small number, not more than 1% of the CAP. // Can be equal to zero, to cancel. // **QUINTILLIONS** 10^18 / 1**18 / 1e18 uint256 public overLimit; // The minimum possible payment from an investor in ETH. Payments below this value will be rejected. // **QUINTILLIONS** 10^18 / 1**18 / 1e18. Example: minPay=0.1ETH ==> use 100**15 (Solidity) or 100e15 (MEW) uint256 public minPay; uint256 ethWeiRaised; uint256 nonEthWeiRaised; uint256 weiPreSale; uint256 public tokenReserved; DistributorRefundVault public vault; SVTAllocation public lockedAllocation; ICOType ICO = ICOType.preSale; uint256 allToken; bool public team = false; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event Finalized(); event Initialized(); function Crowdsale(Token _token) public { // Initially, all next 5-7 roles/wallets are given to the Manager. The Manager is an employee of the company // with knowledge of IT, who publishes the contract and sets it up. However, money and tokens require // a Beneficiary and other roles (Accountant, Team, etc.). The Manager will not have the right // to receive them. To enable this, the Manager must either enter specific wallets here, or perform // this via method changeWallet. In the finalization methods it is written which wallet and // what percentage of tokens are received. // Receives all the money (when finalizing pre-ICO & ICO) wallets[uint8(Roles.beneficiary)] = 0x8d6b447f443ce7cAA12399B60BC9E601D03111f9; // Receives all the tokens for non-ETH investors (when finalizing pre-ICO & ICO) wallets[uint8(Roles.accountant)] = 0x99a280Dc34A996474e5140f34434CE59b5e65879; // All rights except the rights to receive tokens or money. Has the right to change any other // wallets (Beneficiary, Accountant, ...), but only if the round has not started. Once the // round is initialized, the Manager has lost all rights to change the wallets. // If the ICO is conducted by one person, then nothing needs to be changed. Permit all 7 roles // point to a single wallet. wallets[uint8(Roles.manager)] = msg.sender; // Has only the right to call paymentsInOtherCurrency (please read the document) wallets[uint8(Roles.observer)] = 0x8baf8F18256952362E485fEF1D0909F21f9a886C; // When the round is finalized, all team tokens are transferred to a special freezing // contract. As soon as defrosting is over, only the Team wallet will be able to // collect all the tokens. It does not store the address of the freezing contract, // but the final wallet of the project team. wallets[uint8(Roles.team)] = 0x25365d4B293Ec34c39C00bBac3e5C5Ff2dC81F4F; // startTime, endDiscountTime, endTime (then you can change it in the setup) changePeriod(1510311600, 1511607600, 1511607600); // softCap & hardCap (then you can change it in the setup) changeTargets(0 ether, 51195 ether); // $15 000 000 / $293 // rate (10^3), overLimit (10^18), minPay (10^18) (then you can change it in the setup) changeRate(61250, 500 ether, 10 ether); // minProfit, maxProfit, stepProfit changeDiscount(0,0,0); token = _token; token.setOwner(); token.pause(); // block exchange tokens token.addUnpausedWallet(msg.sender); // The return of funds to investors & pay fee for partner vault = new DistributorRefundVault(0x793ADF4FB1E8a74Dfd548B5E2B5c55b6eeC9a3f8, 10 ether); } // Returns the name of the current round in plain text. Constant. function ICOSaleType() public constant returns(string){ return (ICO == ICOType.preSale)?'pre ICO':'ICO'; } // Transfers the funds of the investor to the contract of return of funds. Internal. function forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } // Check for the possibility of buying tokens. Inside. Constant. function validPurchase() internal constant returns (bool) { // The round started and did not end bool withinPeriod = (now > startTime && now < endTime); // Rate is greater than or equal to the minimum bool nonZeroPurchase = msg.value >= minPay; // hardCap is not reached, and in the event of a transaction, it will not be exceeded by more than OverLimit bool withinCap = msg.value <= hardCap.sub(weiRaised()).add(overLimit); // round is initialized and no "Pause of trading" is set return withinPeriod && nonZeroPurchase && withinCap && isInitialized && !isPausedCrowdsale; } // Check for the ability to finalize the round. Constant. function hasEnded() public constant returns (bool) { bool timeReached = now > endTime; bool capReached = weiRaised() >= hardCap; return (timeReached || capReached) && isInitialized; } // Finalize. Only available to the Manager and the Beneficiary. If the round failed, then // anyone can call the finalization to unlock the return of funds to investors // You must call a function to finalize each round (after the pre-ICO & after the ICO) function finalize() public { require(wallets[uint8(Roles.manager)] == msg.sender || wallets[uint8(Roles.beneficiary)] == msg.sender || !goalReached()); require(!isFinalized); require(hasEnded()); isFinalized = true; finalization(); Finalized(); } // The logic of finalization. Internal function finalization() internal { // If the goal of the achievement if (goalReached()) { // Send ether to Beneficiary vault.close(wallets[uint8(Roles.beneficiary)]); // if there is anything to give if (tokenReserved > 0) { // Issue tokens of non-eth investors to Accountant account token.mint(wallets[uint8(Roles.accountant)],tokenReserved); // Reset the counter tokenReserved = 0; } // If the finalization is Round 1 pre-ICO if (ICO == ICOType.preSale) { // Reset settings isInitialized = false; isFinalized = false; // Switch to the second round (to ICO) ICO = ICOType.sale; // Reset the collection counter weiPreSale = weiRaised(); ethWeiRaised = 0; nonEthWeiRaised = 0; // Re-start a refund contract vault.restart(); } else // If the second round is finalized { // Record how many tokens we have issued allToken = token.totalSupply(); // Permission to collect tokens to those who can pick them up team = true; } } else // If they failed round { // Allow investors to withdraw their funds vault.enableRefunds(); } } // The Manager freezes the tokens for the Team. // You must call a function to finalize Round 2 (only after the ICO) function finalize1() public { require(wallets[uint8(Roles.manager)] == msg.sender); require(team); team = false; lockedAllocation = new SVTAllocation(token, wallets[uint8(Roles.team)]); token.addUnpausedWallet(lockedAllocation); // 20% - tokens to Team wallet after freeze (80% for investors) // *** CHECK THESE NUMBERS *** token.mint(lockedAllocation,allToken.mul(20).div(80)); } // Initializing the round. Available to the manager. After calling the function, // the Manager loses all rights: Manager can not change the settings (setup), change // wallets, prevent the beginning of the round, etc. You must call a function after setup // for the initial round (before the Pre-ICO and before the ICO) function initialize() public{ // Only the Manager require(wallets[uint8(Roles.manager)] == msg.sender); // If not yet initialized require(!isInitialized); // And the specified start time has not yet come // If initialization return an error, check the start date! require(now <= startTime); initialization(); Initialized(); isInitialized = true; } function initialization() internal { // no code } // At the request of the investor, we raise the funds (if the round has failed because of the hardcap) function claimRefund() public{ vault.refund(msg.sender); } // We check whether we collected the necessary minimum funds. Constant. function goalReached() public constant returns (bool) { return weiRaised() >= softCap; } // Customize. The arguments are described in the constructor above. function setup(uint256 _startTime, uint256 _endDiscountTime, uint256 _endTime, uint256 _softCap, uint256 _hardCap, uint256 _rate, uint256 _overLimit, uint256 _minPay, uint256 _minProfit, uint256 _maxProfit, uint256 _stepProfit) public{ changePeriod(_startTime, _endDiscountTime, _endTime); changeTargets(_softCap, _hardCap); changeRate(_rate, _overLimit, _minPay); changeDiscount(_minProfit, _maxProfit, _stepProfit); } // Change the date and time: the beginning of the round, the end of the bonus, the end of the round. Available to Manager // Description in the Crowdsale constructor function changePeriod(uint256 _startTime, uint256 _endDiscountTime, uint256 _endTime) public{ require(wallets[uint8(Roles.manager)] == msg.sender); require(!isInitialized); // Date and time are correct require(now <= _startTime); require(_endDiscountTime > _startTime && _endDiscountTime <= _endTime); startTime = _startTime; endTime = _endTime; endDiscountTime = _endDiscountTime; } // We change the purpose of raising funds. Available to the manager. // Description in the Crowdsale constructor. function changeTargets(uint256 _softCap, uint256 _hardCap) public { require(wallets[uint8(Roles.manager)] == msg.sender); require(!isInitialized); // The parameters are correct require(_softCap <= _hardCap); softCap = _softCap; hardCap = _hardCap; } // Change the price (the number of tokens per 1 eth), the maximum hardCap for the last bet, // the minimum bet. Available to the Manager. // Description in the Crowdsale constructor function changeRate(uint256 _rate, uint256 _overLimit, uint256 _minPay) public { require(wallets[uint8(Roles.manager)] == msg.sender); require(!isInitialized); require(_rate > 0); rate = _rate; overLimit = _overLimit; minPay = _minPay; } // We change the parameters of the discount:% min bonus,% max bonus, number of steps. // Available to the manager. Description in the Crowdsale constructor function changeDiscount(uint256 _minProfit, uint256 _maxProfit, uint256 _stepProfit) public { require(wallets[uint8(Roles.manager)] == msg.sender); require(!isInitialized); // The parameters are correct require(_stepProfit <= _maxProfit.sub(_minProfit)); // If not zero steps if(_stepProfit > 0){ // We will specify the maximum percentage at which it is possible to provide // the specified number of steps without fractional parts maxProfit = _maxProfit.sub(_minProfit).div(_stepProfit).mul(_stepProfit).add(_minProfit); }else{ // to avoid a divide to zero error, set the bonus as static maxProfit = _minProfit; } minProfit = _minProfit; stepProfit = _stepProfit; } // Collected funds for the current round. Constant. function weiRaised() public constant returns(uint256){ return ethWeiRaised.add(nonEthWeiRaised); } // Returns the amount of fees for both phases. Constant. function weiTotalRaised() public constant returns(uint256){ return weiPreSale.add(weiRaised()); } // Returns the percentage of the bonus on the current date. Constant. function getProfitPercent() public constant returns (uint256){ return getProfitPercentForData(now); } // Returns the percentage of the bonus on the given date. Constant. function getProfitPercentForData(uint256 timeNow) public constant returns (uint256) { // if the discount is 0 or zero steps, or the round does not start, we return the minimum discount if(maxProfit == 0 || stepProfit == 0 || timeNow > endDiscountTime) { return minProfit.add(100); } // if the round is over - the maximum if(timeNow<=startTime) { return maxProfit.add(100); } // bonus period uint256 range = endDiscountTime.sub(startTime); // delta bonus percentage uint256 profitRange = maxProfit.sub(minProfit); // Time left uint256 timeRest = endDiscountTime.sub(timeNow); // Divide the delta of time into uint256 profitProcent = profitRange.div(stepProfit).mul(timeRest.mul(stepProfit.add(1)).div(range)); return profitProcent.add(minProfit).add(100); } // The ability to quickly check pre-ICO (only for Round 1, only 1 time). Completes the pre-ICO by // transferring the specified number of tokens to the Accountant's wallet. Available to the Manager. // Use only if this is provided by the script and white paper. In the normal scenario, it // does not call and the funds are raised normally. We recommend that you delete this // function entirely, so as not to confuse the auditors. Initialize & Finalize not needed. // ** QUINTILIONS ** 10^18 / 1**18 / 1e18 function fastICO(uint256 _totalSupply) public { require(wallets[uint8(Roles.manager)] == msg.sender); require(ICO == ICOType.preSale && !isInitialized); token.mint(wallets[uint8(Roles.accountant)], _totalSupply); ICO = ICOType.sale; } // Remove the "Pause of exchange". Available to the manager at any time. If the // manager refuses to remove the pause, then 120 days after the successful // completion of the ICO, anyone can remove a pause and allow the exchange to continue. // The manager does not interfere and will not be able to delay the term. // He can only cancel the pause before the appointed time. function tokenUnpause() public { require(wallets[uint8(Roles.manager)] == msg.sender || (now > endTime + 120 days && ICO == ICOType.sale && isFinalized && goalReached())); token.unpause(); } // Enable the "Pause of exchange". Available to the manager until the ICO is completed. // The manager cannot turn on the pause, for example, 3 years after the end of the ICO. function tokenPause() public { require(wallets[uint8(Roles.manager)] == msg.sender && !isFinalized); token.pause(); } // Pause of sale. Available to the manager. function crowdsalePause() public { require(wallets[uint8(Roles.manager)] == msg.sender); require(isPausedCrowdsale == false); isPausedCrowdsale = true; } // Withdrawal from the pause of sale. Available to the manager. function crowdsaleUnpause() public { require(wallets[uint8(Roles.manager)] == msg.sender); require(isPausedCrowdsale == true); isPausedCrowdsale = false; } // Checking whether the rights to address ignore the "Pause of exchange". If the // wallet is included in this list, it can translate tokens, ignoring the pause. By default, // only the following wallets are included: // - Accountant wallet (he should immediately transfer tokens, but not to non-ETH investors) // - Contract for freezing the tokens for the Team (but Team wallet not included) // Inside. Constant. function unpausedWallet(address _wallet) internal constant returns(bool) { bool _accountant = wallets[uint8(Roles.accountant)] == _wallet; return _accountant; } // For example - After 5 years of the project's existence, all of us suddenly decided collectively // (company + investors) that it would be more profitable for everyone to switch to another smart // contract responsible for tokens. The company then prepares a new token, investors // disassemble, study, discuss, etc. After a general agreement, the manager allows any investor: // - to burn the tokens of the previous contract // - generate new tokens for a new contract // It is understood that after a general solution through this function all investors // will collectively (and voluntarily) move to a new token. function moveTokens(address _migrationAgent) public { require(wallets[uint8(Roles.manager)] == msg.sender); token.setMigrationAgent(_migrationAgent); } // Change the address for the specified role. // Available to any wallet owner except the observer. // Available to the manager until the round is initialized. // The Observer's wallet or his own manager can change at any time. function changeWallet(Roles _role, address _wallet) public { require( (msg.sender == wallets[uint8(_role)] && _role != Roles.observer) || (msg.sender == wallets[uint8(Roles.manager)] && (!isInitialized || _role == Roles.observer)) ); address oldWallet = wallets[uint8(_role)]; wallets[uint8(_role)] = _wallet; if(!unpausedWallet(oldWallet)) token.delUnpausedWallet(oldWallet); if(unpausedWallet(_wallet)) token.addUnpausedWallet(_wallet); } // If a little more than a year has elapsed (ICO start date + 460 days), a smart contract // will allow you to send all the money to the Beneficiary, if any money is present. This is // possible if you mistakenly launch the ICO for 30 years (not 30 days), investors will transfer // money there and you will not be able to pick them up within a reasonable time. It is also // possible that in our checked script someone will make unforeseen mistakes, spoiling the // finalization. Without finalization, money cannot be returned. This is a rescue option to // get around this problem, but available only after a year (460 days). // Another reason - the ICO was a failure, but not all ETH investors took their money during the year after. // Some investors may have lost a wallet key, for example. // The method works equally with the pre-ICO and ICO. When the pre-ICO starts, the time for unlocking // the distructVault begins. If the ICO is then started, then the term starts anew from the first day of the ICO. // Next, act independently, in accordance with obligations to investors. // Within 400 days of the start of the Round, if it fails only investors can take money. After // the deadline this can also include the company as well as investors, depending on who is the first to use the method. function distructVault() public { require(wallets[uint8(Roles.beneficiary)] == msg.sender); require(now > startTime + 400 days); vault.del(wallets[uint8(Roles.beneficiary)]); } // We accept payments other than Ethereum (ETH) and other currencies, for example, Bitcoin (BTC). // Perhaps other types of cryptocurrency - see the original terms in the white paper and on the ICO website. // We release tokens on Ethereum. During the pre-ICO and ICO with a smart contract, you directly transfer // the tokens there and immediately, with the same transaction, receive tokens in your wallet. // When paying in any other currency, for example in BTC, we accept your money via one common wallet. // Our manager fixes the amount received for the bitcoin wallet and calls the method of the smart // contract paymentsInOtherCurrency to inform him how much foreign currency has been received - on a daily basis. // The smart contract pins the number of accepted ETH directly and the number of BTC. Smart contract // monitors softcap and hardcap, so as not to go beyond this framework. // In theory, it is possible that when approaching hardcap, we will receive a transfer (one or several // transfers) to the wallet of BTC, that together with previously received money will exceed the hardcap in total. // In this case, we will refund all the amounts above, in order not to exceed the hardcap. // Collection of money in BTC will be carried out via one common wallet. The wallet's address will be published // everywhere (in a white paper, on the ICO website, on Telegram, on Bitcointalk, in this code, etc.) // Anyone interested can check that the administrator of the smart contract writes down exactly the amount // in ETH (in equivalent for BTC) there. In theory, the ability to bypass a smart contract to accept money in // BTC and not register them in ETH creates a possibility for manipulation by the company. Thanks to // paymentsInOtherCurrency however, this threat is leveled. // Any user can check the amounts in BTC and the variable of the smart contract that accounts for this // (paymentsInOtherCurrency method). Any user can easily check the incoming transactions in a smart contract // on a daily basis. Any hypothetical tricks on the part of the company can be exposed and panic during the ICO, // simply pointing out the incompatibility of paymentsInOtherCurrency (ie, the amount of ETH + BTC collection) // and the actual transactions in BTC. The company strictly adheres to the described principles of openness. // The company administrator is required to synchronize paymentsInOtherCurrency every working day (but you // cannot synchronize if there are no new BTC payments). In the case of unforeseen problems, such as // brakes on the Ethereum network, this operation may be difficult. You should only worry if the // administrator does not synchronize the amount for more than 96 hours in a row, and the BTC wallet // receives significant amounts. // This scenario ensures that for the sum of all fees in all currencies this value does not exceed hardcap. // Our BTC wallet for audit in this function: 1CAyLcES1tNuatRhnL1ooPViZ32vF5KQ4A // ** QUINTILLIONS ** 10^18 / 1**18 / 1e18 function paymentsInOtherCurrency(uint256 _token, uint256 _value) public { require(wallets[uint8(Roles.observer)] == msg.sender); bool withinPeriod = (now >= startTime && now <= endTime); bool withinCap = _value.add(ethWeiRaised) <= hardCap.add(overLimit); require(withinPeriod && withinCap && isInitialized); nonEthWeiRaised = _value; tokenReserved = _token; } // The function for obtaining smart contract funds in ETH. If all the checks are true, the token is // transferred to the buyer, taking into account the current bonus. function buyTokens(address beneficiary) public payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; uint256 ProfitProcent = getProfitPercent(); // calculate token amount to be created uint256 tokens = weiAmount.mul(rate).mul(ProfitProcent).div(100000); // update state ethWeiRaised = ethWeiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // buyTokens alias function () public payable { buyTokens(msg.sender); } } // (B) // The contract for freezing tokens for the team.. contract SVTAllocation { using SafeMath for uint256; Token public token; address public owner; uint256 public unlockedAt; uint256 tokensCreated = 0; // The contract takes the ERC20 coin address from which this contract will work and from the // owner (Team wallet) who owns the funds. function SVTAllocation(Token _token, address _owner) public{ // How many days to freeze from the moment of finalizing ICO unlockedAt = now + 365 days; // freeze TEAM tokens for 1 year token = _token; owner = _owner; } // If the time of freezing expired will return the funds to the owner. function unlock() public{ require(now >= unlockedAt); require(token.transfer(owner,token.balanceOf(this))); } }
Remove the "Pause of exchange". Available to the manager at any time. If the manager refuses to remove the pause, then 120 days after the successful completion of the ICO, anyone can remove a pause and allow the exchange to continue. The manager does not interfere and will not be able to delay the term. He can only cancel the pause before the appointed time.
function tokenUnpause() public { require(wallets[uint8(Roles.manager)] == msg.sender || (now > endTime + 120 days && ICO == ICOType.sale && isFinalized && goalReached())); token.unpause(); }
2,524,446
./full_match/44787/0xBCba425b9Dd7D56B49d2Af59DA15E284A49dbEc5/sources/contracts/pools/BaseCarbonTonne.sol
Generic function to switch attributes mappings into either acceptance or rejection criteria _mappingName attribute mapping of project-vintage data accepted determines if mapping works as black or whitelist
function switchMapping(string memory _mappingName, bool accepted) external virtual onlyOwner { if (strcmp(_mappingName, 'regions')) { accepted ? regionsIsAcceptedMapping = true : regionsIsAcceptedMapping = false; accepted ? standardsIsAcceptedMapping = true : standardsIsAcceptedMapping = false; accepted ? methodologiesIsAcceptedMapping = true : methodologiesIsAcceptedMapping = false; } emit MappingSwitched(_mappingName, accepted); }
13,272,187
./full_match/1/0x9c086c8d464829Cd6E1dAE8e40B2C7C34c2a0890/sources/browser/CWTSwap.sol
Convert Tokens to Tokens. User specifies exact input && minium output. input_token Address of Tokens sold. output_token Address of Tokens bought. tokens_sold Amount of Tokens sold. min_tokens_bought Minium amount of Tokens bought. deadline Time after which this transaction can no longer be executed. return Amount of Tokens bought./
function tokenToTokenSwapInput( address input_token, address output_token, uint256 tokens_sold, uint256 min_tokens_bought, uint256 deadline) onlyAdmin nonReentrant external returns (uint256) { return tokenToTokenInput(input_token, output_token, tokens_sold, min_tokens_bought, deadline, msg.sender, msg.sender); }
9,655,218
./partial_match/5/0x1C8dad3dc796d795903c86f827bee5393D29e70A/sources/DividendPool.sol
claim dividend amount amount of erc20 token nonce nonce (prevent replay attacks) deadline deadline (unix timestamp) signature signed by signer/
function dividend( uint256 amount, uint32 nonce, uint64 deadline, bytes memory signature ) external withdrawAmountCheck(amount) { require(block.timestamp <= deadline, "DividendPool: expired"); address sender = msg.sender; bytes32 _hash = keccak256( abi.encodePacked(nonce, sender, amount, deadline) ); require(!_claimedSignature[_hash], "DividendPool: nonce already used"); require( _hash.toEthSignedMessageHash().recover(signature) == getsigner(), "invalid signature" ); try ERC20().transfer(sender, amount) returns (bool success) { require(success, "DividendPool: transfer failed"); unchecked { _currentBalance -= amount; } _claimedSignature[_hash] = true; emit Dividend(sender, amount); revert("DividendPool: transfer failed"); } }
16,875,702
./full_match/11155111/0x76DBBBB2f1C10EF6aF36730b3104D2992FD9Ea26/sources/contracts/GameFactory.sol
uint256 _entryPrice = games[_gameId].entryPrice;require(msg.value >= _entryPrice, "Please send funds for the correct entry price");require(games[_gameId].status == Status.Open, "Game is not currently open");
function buyEntries(uint256 _gameId, uint256 _numEntries) public payable { require(!factoryPaused, "Game Factory is currently paused. Come back later"); require(msg.sender != games[_gameId].owner, "You own the Game. You can not enter"); bool matchingTierFlag = false; for(uint i = 0; i < 5; i++) { if((prices[_gameId][i].number == _numEntries) && (prices[_gameId][i].price == msg.value)) { matchingTierFlag = true; } } require(matchingTierFlag, "That is not a valid purchase"); Purchase memory purchase = Purchase({ id: nextPurchaseId, upperBound: nextEntryId + (_numEntries - 1), owner: msg.sender, parentGameId: _gameId, amountSpent: msg.value, numEntries: _numEntries }); User memory user = users[msg.sender]; if(!user.hasValue) { user.wallet = msg.sender; user.hasValue = true; users[msg.sender].purchaseList.push(purchase.id); users[msg.sender].purchaseList.push(purchase.id); } if(!hasEnteredGame[msg.sender][_gameId]) { hasEnteredGame[msg.sender][_gameId] = true; games[_gameId].uniqueEntrants++; } purchases[purchase.id] = purchase; games[_gameId].purchaseList.push(purchase.id); games[_gameId].nextEntryId += _numEntries; nextPurchaseId += 1; emit UserUpdated(users[msg.sender]); emit GameUpdated(games[_gameId]); }
3,793,894
./full_match/5/0x393f13d4A7A82c71d0926751CF897E1a1c588C35/sources/contracts/data/DataStore.sol
get the int array for the given key key the key of the int array return the int array for the key
function getIntArray(bytes32 key) external view returns (int256[] memory) { return intArrayValues[key]; }
11,589,376
./partial_match/42/0xe529489f6F238689A4BD861305C106dd457B0743/sources/CompoundNoFoldStrategyUSDTMainnet.sol
Salvages a token./ To make sure that governance cannot come in and take away the coins
function salvage(address recipient, address token, uint256 amount) external onlyGovernance { require(!unsalvagableTokens[token], "token is defined as not salvagable"); IERC20(token).safeTransfer(recipient, amount); }
3,339,120
pragma solidity ^0.4.13; library Strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string self) internal returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-termintaed utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal returns (slice ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice self) internal returns (slice) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice&#39;s text. */ function toString(slice self) internal returns (string) { var ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice self) internal returns (uint) { // Starting at ptr-31 means the LSB will be the byte we care about var ptr = self._ptr - 31; var end = ptr + self._len; for (uint len = 0; ptr < end; len++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } return len; } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice self) internal returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice self, slice other) internal returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; var selfptr = self._ptr; var otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); var diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice self, slice other) internal returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice self, slice rune) internal returns (slice) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint len; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { len = 1; } else if(b < 0xE0) { len = 2; } else if(b < 0xF0) { len = 3; } else { len = 4; } // Check for truncated codepoints if (len > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += len; self._len -= len; rune._len = len; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice self) internal returns (slice ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice self) internal returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint len; uint div = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } var b = word / div; if (b < 0x80) { ret = b; len = 1; } else if(b < 0xE0) { ret = b & 0x1F; len = 2; } else if(b < 0xF0) { ret = b & 0x0F; len = 3; } else { ret = b & 0x07; len = 4; } // Check for truncated codepoints if (len > self._len) { return 0; } for (uint i = 1; i < len; i++) { div = div / 256; b = (word / div) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice self) internal returns (bytes32 ret) { assembly { ret := sha3(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice self, slice needle) internal returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let len := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let len := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice self, slice needle) internal returns (bool) { if (self._len < needle._len) { return false; } var selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let len := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } var selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let len := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 68 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) let end := add(selfptr, sub(selflen, needlelen)) ptr := selfptr loop: jumpi(exit, eq(and(mload(ptr), mask), needledata)) ptr := add(ptr, 1) jumpi(loop, lt(sub(ptr, 1), end)) ptr := add(selfptr, selflen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr; for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 69 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) ptr := add(selfptr, sub(selflen, needlelen)) loop: jumpi(ret, eq(and(mload(ptr), mask), needledata)) ptr := sub(ptr, 1) jumpi(loop, gt(add(ptr, 1), selfptr)) ptr := selfptr jump(exit) ret: ptr := add(ptr, needlelen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice self, slice needle) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice self, slice needle) internal returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice self, slice needle, slice token) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice self, slice needle) internal returns (slice token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice self, slice needle, slice token) internal returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice self, slice needle) internal returns (slice token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice self, slice needle) internal returns (uint count) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { count++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice self, slice needle) internal returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice self, slice other) internal returns (string) { var ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice self, slice[] parts) internal returns (string) { if (parts.length == 0) return ""; uint len = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) len += parts[i]._len; var ret = new string(len); uint retptr; assembly { retptr := add(ret, 32) } for(i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } library ConvertStringByte { function bytes32ToString(bytes32 x) constant returns (string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } function stringToBytes32(string memory source) returns (bytes32 result) { assembly { result := mload(add(source, 32)) } } } /** * @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; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract Platinum is Ownable { using SafeMath for uint256; using Strings for *; // ========= 宣告 ========= string public version = "0.0.1"; // 基本單位 string public unit = "oz"; // 總供給量 uint256 public total; // 存貨 struct Bullion { string index; string unit; uint256 amount; string ipfs; } bytes32[] public storehouseIndex; mapping (bytes32 => Bullion) public storehouse; // 掛勾貨幣 address public token; // 匯率 1白金:白金幣 uint256 public rate = 10; // PlatinumToken 實例 PlatinumToken coin; // ========= 初始化 ========= function Platinum() { } // ========= event ========= event Stock ( string index, string unit, uint256 amount, string ipfs, uint256 total ); event Ship ( string index, uint256 total ); event Mint ( uint256 amount, uint256 total ); event Alchemy ( uint256 amount, uint256 total ); event Buy ( string index, address from, uint256 fee, uint256 price ); // ========= 擁有者方法 ========= /** * 操作存貨-進貨 * * 此方法執行: * - 紀錄新增的白金,紀錄資訊: * - index: 白金編號 * - unit: 白金單位 * - amount: 數量 * - ipfs: 白金證明URL * - 增加白金總庫存數量,量為amount * * Requires: * - 執行者須為owner * - 白金編號index不能重複 * - 單位須等於目前合約所設定的單位 * - 量amount需大於0 * * Returns: * - bool: 執行成功時,回傳true * * Events: * - Stock: 執行成功時觸發 */ function stock(string _index, string _unit, uint256 _amount, string _ipfs) onlyOwner returns (bool) { bytes32 _bindex = ConvertStringByte.stringToBytes32(_index); require(_amount > 0); require(_unit.toSlice().equals(unit.toSlice())); require(!(storehouse[_bindex].amount > 0)); Bullion bullion = storehouse[_bindex]; bullion.index = _index; bullion.unit = _unit; bullion.amount = _amount; bullion.ipfs = _ipfs; // 加入倉儲目錄 storehouseIndex.push(_bindex); // 加入倉儲 storehouse[_bindex] = bullion; // 增加總庫存 total = total.add(_amount); Stock(bullion.index, bullion.unit, bullion.amount, bullion.ipfs, total); return true; } /** * 操作存貨-出貨 * * 此方法執行: * - 移除白金庫存 * - 減少白金總庫存量,量為白金庫存的數量 * * Requires: * - 執行者為owner * - 白金編號index需存在於紀錄(已使用stock方法新增該庫存) * - 白金總庫存需足夠,大於指定白金庫存的數量 * * Returns: * - bool: 執行成功時,回傳true * * Events: * - Ship: 執行成功時觸發 */ function ship(string _index) onlyOwner returns (bool) { bytes32 _bindex = ConvertStringByte.stringToBytes32(_index); require(storehouse[_bindex].amount > 0); Bullion bullion = storehouse[_bindex]; require(total.sub(bullion.amount) >= 0); uint256 tmpAmount = bullion.amount; for (uint256 index = 0; index < storehouseIndex.length; index++) { Bullion _bullion = storehouse[storehouseIndex[index]]; if (_bullion.index.toSlice().equals(_index.toSlice())) { // 從倉儲目錄移除 delete storehouseIndex[index]; } } // 從倉儲移除 delete storehouse[_bindex]; // 減少總庫存 total = total.sub(tmpAmount); Ship(bullion.index, total); return true; } /** * 鑄幣 * * 此方法執行: * - 增加白金代幣數量 * - 減少總白金庫存 * * Requires: * - 執行者為owner * - 白金總庫存需足夠,即大於等於ptAmount * - 白金代幣合約需已設定(setTokenAddress方法) * * Returns: * - bool: 執行成功時,回傳true * * Events: * - Mint: 執行成功時觸發 */ function mint(uint256 _ptAmount) onlyOwner returns (bool) { require(token != 0x0); uint256 amount = convert2PlatinumToken(_ptAmount); // 發送token的增加涵式 bool produced = coin.produce(amount); require(produced); total = total.sub(_ptAmount); Mint(_ptAmount, total); return true; } /** * 煉金 * * 此方法執行: * - 減少白金代幣 * - 增加總白金庫存 * * Requires: * - 執行者為owner * - 需已設定白金代幣合約(setTokenAddress方法) * - 白金代幣owner所擁有的代幣足夠,即tokenAmount小於等於代幣owner的白金代幣數量 * * Returns: * - bool: 執行成功,回傳true * * Events: * - Alchemy: 執行成功時觸發 */ function alchemy(uint256 _tokenAmount) onlyOwner returns (bool) { require(token != 0x0); uint256 amount = convert2Platinum(_tokenAmount); bool reduced = coin.reduce(_tokenAmount); require(reduced); total = total.add(amount); Alchemy(amount, total); return true; } /** * 設定-匯率 * * 匯率規則: * - 白金數量 * 匯率 = 白金代幣數量 * - 白金代幣數量 / 匯率 = 白金數量 * * Requires: * - 執行者為owner * - 匯率rate需大於0 * * Returns: * - bool: 執行成功,回傳true */ function setRate(uint256 _rate) onlyOwner returns (bool) { require(_rate > 0); rate = _rate; return true; } /** * 設定-Token地址 * * 設定白金合約地址 * * Requires: * - 執行者為owner * - 合約地址address不為0 * * Returns: * - bool: 執行成功,回傳true */ function setTokenAddress(address _address) onlyOwner returns (bool) { require(_address != 0x0); coin = PlatinumToken(_address); token = _address; return true; } /** * 購買金條 * * 此方法執行: * - 扣除buyer的白金代幣 * - 移除白金庫存,代表buyer已從庫存買走白金 * * Requires: * - 執行者為owner * - 白金編號index需存在於紀錄(已使用stock方法新增該庫存) * * Returns: * - bool: 執行成功,回傳true * * Events: * - Buy: 執行成功時觸發 */ function buy(string _index, address buyer) onlyOwner returns (bool) { require(token != 0x0); bytes32 _bindex = ConvertStringByte.stringToBytes32(_index); uint256 fee = coin.fee(); require(storehouse[_bindex].amount > 0); Bullion bullion = storehouse[_bindex]; uint256 tokenPrice = convert2PlatinumToken(bullion.amount); uint256 tokenPriceFee = tokenPrice.add(fee); // 轉帳 bool transfered = coin.transferFrom(buyer, coin.owner(), tokenPriceFee); require(transfered); // 直接把剛剛賣出的價格煉金 bool reduced = coin.reduce(tokenPrice); require(reduced); // 減少庫存 for (uint256 index = 0; index < storehouseIndex.length; index++) { Bullion _bullion = storehouse[storehouseIndex[index]]; if (_bullion.index.toSlice().equals(_index.toSlice())) { // 從倉儲目錄移除 delete storehouseIndex[index]; } } // 從倉儲移除 delete storehouse[_bindex]; Buy(_index, buyer, fee, tokenPrice); return true; } // ========= 公共方法 ========= // 比率轉換-白金幣換白金 function convert2Platinum(uint256 _amount) constant returns (uint256) { return _amount.div(rate); } // 比率轉換-白金換白金幣 function convert2PlatinumToken(uint256 _amount) constant returns (uint256) { return _amount.mul(rate); } // 金條資訊 function info(string _index) constant returns (string, string, uint256, string) { bytes32 _bindex = ConvertStringByte.stringToBytes32(_index); require(storehouse[_bindex].amount > 0); Bullion bullion = storehouse[_bindex]; return (bullion.index, bullion.unit, bullion.amount, bullion.ipfs); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract PlatinumToken is Ownable, ERC20 { using SafeMath for uint256; // ========= 宣告 ========= // 版本 string public version = "0.0.1"; // 名稱 string public name; // 標記 string public symbol; // 小數點位數 uint256 public decimals; // 白金合約地址 address public platinum; mapping (address => mapping (address => uint256)) allowed; mapping(address => uint256) balances; // 總供給量 uint256 public totalSupply; // 手續費 uint256 public fee = 10; // ========= 初始化 ========= function PlatinumToken( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol ) { balances[msg.sender] = initialSupply; totalSupply = initialSupply; name = tokenName; symbol = tokenSymbol; decimals = decimalUnits; } // ========= 權限控管 ========= modifier isPlatinumContract() { require(platinum != 0x0); require(msg.sender == platinum); _; } modifier isOwnerOrPlatinumContract() { require(msg.sender != address(0) && (msg.sender == platinum || msg.sender == owner)); _; } /** * 增產 * * 此方法執行: * - 增加owner的balance,量為指定的amount * - 增加totalSupply,量為指定的amount * * Requires: * - 執行者為白金合約(可透過setPlatinumAddress方法設定) * - amount須設定為0以上 * * Return: * - bool: 執行成功回傳true */ function produce(uint256 amount) isPlatinumContract returns (bool) { balances[owner] = balances[owner].add(amount); totalSupply = totalSupply.add(amount); return true; } /** 減產 * * 此方法執行: * - 減少owner的balance,量為指定的amount * - 減少totalSupply,量為指定的amount * * Requires: * - 執行者為白金合約(可透過setPlatinumAddress方法設定) * - amount須設定為0以上 * - owner的balance需大於等於指定的amount * - totalSupply需大於等於指定的amount * * Return: * - bool: 執行成功回傳true */ function reduce(uint256 amount) isPlatinumContract returns (bool) { require(balances[owner].sub(amount) >= 0); require(totalSupply.sub(amount) >= 0); balances[owner] = balances[owner].sub(amount); totalSupply = totalSupply.sub(amount); return true; } /** * 設定-白金合約地址 * * 此方法執行: * - 修改此合約所認識的白金合約地址,此地址決定能執行produce和reduce方法的合約 * * Requires: * - 執行者須為owner * - 地址不能設為0 * * Returns: * - bool: 設定成功時回傳true */ function setPlatinumAddress(address _address) onlyOwner returns (bool) { require(_address != 0x0); platinum = _address; return true; } /** * 設定-手續費 * * 手續費規則: * - 購買金條時,代幣量總量增加手續費為總扣除代幣總量 * * Requires: * - 執行者為owner * * Returns: * - bool: 執行成功,回傳true */ function setFee(uint256 _fee) onlyOwner returns (bool) { require(_fee >= 0); fee = _fee; return true; } /** * 交易,轉移白金代幣 * * 此方法執行: * - 減少from的白金代幣,量為value * - 增加to的白金代幣,量為value * * Requires: * - 執行者為owner * * Returns: * - bool: 執行成功回傳true * * Events: * - Transfer: 執行成功時,觸發此事件 */ function transfer(address _to, uint256 _value) onlyOwner returns (bool) { balances[owner] = balances[owner].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(owner, _to, _value); return true; } /** * 查詢白金代幣餘額 * * Returns: * - balance: 指定address的白金代幣餘額 */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } /** * 轉帳 * * 實際將approve過的token數量進行交易 * * 此方法執行: * - 交易指定數量的代幣 * * Requires: * - 交易的代幣數量value需大於0 * - allowed的代幣數量需大於value(allowed的代幣先由呼叫approve方法設定) * * Returns: * - bool: 執行成功,回傳true */ function transferFrom(address _from, address _to, uint256 _value) isOwnerOrPlatinumContract returns (bool) { var _allowance = allowed[_from][owner]; uint256 valueSubFee = _value.sub(fee); balances[_to] = balances[_to].add(valueSubFee); balances[_from] = balances[_from].sub(_value); balances[owner] = balances[owner].add(fee); allowed[_from][owner] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * 轉帳 - 允許 * * 允許一定數量的代幣可以轉帳至owner * * 欲修改允許值,需先執行此方法將value設為0,再執行一次此方法將value設為指定值 * * 此方法操作: * - 修改allowed值,紀錄sender允許轉帳value數量代幣給owner * - allowed值有設定時,value須為0 * - allowed值未設定時,value不為0 * * Returns: * - bool: 執行成功,回傳true */ function approve(address _dummy, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][owner] == 0)); allowed[msg.sender][owner] = _value; Approval(msg.sender, owner, _value); return true; } /** * 轉帳 - 查詢允許值 * * Returns: * - unit256: 允許值 */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * 刪除合約 * * 此方法呼叫合約內建的selfdestruct方法 */ function suicide() onlyOwner returns (bool) { selfdestruct(owner); return true; } }
設定-Token地址 設定白金合約地址 Requires: - 執行者為owner - 合約地址address不為0 Returns: - bool: 執行成功,回傳true/
function setTokenAddress(address _address) onlyOwner returns (bool) { require(_address != 0x0); coin = PlatinumToken(_address); token = _address; return true; }
2,236,296
pragma solidity >=0.5.0 <0.6.0; import '../libs/collections/AddressMap.sol'; import '../libs/lifecycle/LockableDestroyable.sol'; import '../libs/ownership/Ownable.sol'; import "../libs/strings/AddressToASCII.sol"; import "./IRegistry.sol"; /** * @title Registry */ contract Registry is IRegistry, Ownable, LockableDestroyable { using AddressMap for AddressMap.Data; using AddressToASCII for address; struct Account { address addr; uint8 kind; bool frozen; address parent; bytes32 hash; } // ------------------------------- Variables ------------------------------- // Number of data slots available per account uint8 constant MAX_DATA = 100; // Account variables // - indices: Mapping of address to index // - items: Mapping of index to account // - accounts: Count of items/accounts mapping(address => int256) private indices; mapping(int256 => Account) private items; int256 public accounts; // Account data // - mapping of: // MAX_DATA // (address => (index => data)) mapping(address => mapping(uint8 => bytes32)) public data; // Account hash mappings mapping(bytes32 => AddressMap.Data) public hashes; // Address write permissions // (kind => address) mapping(uint8 => AddressMap.Data) public permissions; // ------------------------------- Modifiers ------------------------------- /** * Ensures the `msg.sender` has permission for the given kind/type of account. * * - The `owner` account is always allowed * - Addresses/Contracts must have a corresponding entry, for the given kind */ modifier isAllowed(uint8 kind) { // Verify permission require(kind > 0, "Invalid, or missing permission"); if (msg.sender != owner) { require(permissions[kind].exists(msg.sender), "Missing permission"); } _; } // ------------------------------------------------------------------------- /** * Adds an account to storage * THROWS when `msg.sender` doesn't have permission * THROWS when the account already exists * @param addr The address of the account * @param kind The kind of account * @param isFrozen The frozen status of the account * @param parent The account parent/owner * @param hash The hash that uniquely identifies the account */ function addAccount(address addr, uint8 kind, bool isFrozen, address parent, bytes32 hash) isUnlocked isAllowed(kind) external { // Check if the account already exists int256 oneBasedIndex = indices[addr]; require(oneBasedIndex < 1 || oneBasedIndex > accounts, "Account already exists"); // Prevent cyclical lineage Account memory a = Account(addr, kind, isFrozen, parent, hash); (bool cyclical, address at) = hasCyclicalLineage(a); require(!cyclical, string(abi.encodePacked("Cyclical lineage at address: ", at.toString()))); // Append the account/index and update the count accounts++; indices[addr] = accounts; items[accounts] = a; hashes[hash].append(addr); } /** * Sets an account's frozen status * THROWS when the account doesn't exist * @param addr The address of the account * @param frozen The frozen status of the account */ function setAccountFrozen(address addr, bool frozen) isUnlocked isAllowed(get(addr).kind) external { // NOTE: Not bounds checking `index` here, as `isAllowed` ensures the address exists. // Indices are one-based internally, so we need to add one to compensate. int256 oneBasedIndex = indices[addr]; items[oneBasedIndex].frozen = frozen; } /** * Sets the account's parent * THROWS when the account doesn't exist or when the new parent would cause a cyclical lineage * @param addr The address of the account * @param parent The new parent of the account */ function setAccountParent(address addr, address parent) isUnlocked isAllowed(get(addr).kind) external { // NOTE: Not bounds checking `index` here, as `isAllowed` ensures the address exists. // Indices are one-based internally, so we need to add one to compensate. Account storage a = items[indices[addr]]; a.parent = parent; (bool cyclical, address at) = hasCyclicalLineage(a); require(!cyclical, string(abi.encodePacked("Cyclical lineage at address: ", at.toString()))); } /** * Sets the account's hash * THROWS when the account doesn't exist * @dev Removes the current hash from `hashes` and adds a new entry, using the new hash, to `hashes` * @param addr The address of the account * @param hash The new hash of the account */ function setAccountHash(address addr, bytes32 hash) isUnlocked isAllowed(get(addr).kind) external { // NOTE: Not bounds checking `index` here, as `isAllowed` ensures the address exists. // Indices are one-based internally, so we need to add one to compensate. Account storage a = items[indices[addr]]; hashes[a.hash].remove(addr); hashes[hash].append(addr); a.hash = hash; } /** * Removes an account from storage * THROWS when the account doesn't exist * @param addr The address of the account */ function removeAccount(address addr) isUnlocked isAllowed(get(addr).kind) external { // Remove data bytes32 ZERO_BYTES = bytes32(0); mapping(uint8 => bytes32) storage accountData = data[addr]; for (uint8 i = 0; i < MAX_DATA; i++) { if (accountData[i] != ZERO_BYTES) { delete accountData[i]; } } // Remove hash int256 oneBasedIndex = indices[addr]; bytes32 h = items[oneBasedIndex].hash; hashes[h].remove(addr); // Remove account // When the item being removed is not the last item in the collection, // replace that item with the last one, otherwise zero it out. // // If {2} is the item to be removed // [0, 1, 2, 3, 4] // The result would be: // [0, 1, 4, 3] // if (oneBasedIndex < accounts) { // Replace with last item Account storage last = items[accounts]; // Get the last item indices[last.addr] = oneBasedIndex; // Update last items index to current index items[oneBasedIndex] = last; // Update current index to last item delete items[accounts]; // Delete the last item, since it's moved } else { // Delete the account delete items[oneBasedIndex]; } delete indices[addr]; accounts--; } /** * Sets data for an address/caller * THROWS when the account doesn't exist * @param addr The address * @param index The index of the data * @param customData The data store set */ function setAccountData(address addr, uint8 index, bytes32 customData) isUnlocked isAllowed(get(addr).kind) external { require(index < MAX_DATA, "index outside of bounds"); data[addr][index] = customData; } /** * Adds/Removes permissions for the given address * THROWS when the permissions can't be granted/revoked * @param kind The kind of the permissions to grant * @param addr The address to add/remove permissions for * @param grant If permissions are being granted or revoked */ function setPermission(uint8 kind, address addr, bool grant) isUnlocked isAllowed(kind) external { if (grant) { require(permissions[kind].append(addr), "Address already has permission"); } else { require(permissions[kind].remove(addr), "Address permission don't exist"); } } // ---------------------------- Address Getters ---------------------------- /** * Gets the account at the given index * THROWS when the index is out-of-bounds * @param index The index of the item to retrieve * @return The address, kind, frozen status, and parent of the account at the given index */ function accountAt(int256 index) external view returns(address, uint8, bool, address, bytes32) { require(index >= 0 && index < accounts, "Index outside of bounds"); Account memory a = items[index + 1]; return (a.addr, a.kind, a.frozen, a.parent, a.hash); } /** * Gets the account of the hash at the given index * THROWS when the index is out-of-bounds * @param hash The hash of the item to retrieve * @param index The index of the item to retrieve * @return The address, kind, frozen status, and parent of the account at the given index */ function accountAtHash(bytes32 hash, int256 index) external view returns(address, uint8, bool, address, bytes32) { Account memory a = get(hashes[hash].at(index)); return (a.addr, a.kind, a.frozen, a.parent, a.hash); } /** * Gets the address of the hash at the given index * THROWS when the index is out-of-bounds * @param hash The hash of the item to retrieve * @param index The index of the item to retrieve * @return The address of the hash at the given index */ function addressAtHash(bytes32 hash, int256 index) external view returns(address) { return hashes[hash].at(index); } /** * Gets the account for the given address * THROWS when the account doesn't exist * @param addr The address of the item to retrieve * @return The address, kind, frozen status, parent, and hash of the account at the given index */ function accountGet(address addr) external view returns(uint8, bool, address, bytes32) { Account memory a = get(addr); return (a.kind, a.frozen, a.parent, a.hash); } /** * Gets the hash for the given account address * THROWS when the account doesn't exist * @param addr The address of the account * @return The hash * @return The hash of the address */ function accountHash(address addr) external view returns(bytes32) { return get(addr).hash; } /** * Gets the parent address for the given account address * THROWS when the account doesn't exist * @param addr The address of the account * @return The parent address */ function accountParent(address addr) external view returns(address) { return get(addr).parent; } /** * Gets the account kind, for the given account address * THROWS when the account doesn't exist * @param addr The address of the account * @return The kind of account */ function accountKind(address addr) external view returns(uint8) { return get(addr).kind; } /** * Gets the frozen status of the account * THROWS when the account doesn't exist * @param addr The address of the account * @return The frozen status of the account */ function accountFrozen(address addr) external view returns(bool) { return get(addr).frozen; } /** * Gets the kind and frozen status of the account * THROWS when the account doesn't exist * @param addr The address of the account * @return The kind and frozen status of the account */ function accountKindAndFrozen(address addr) external view returns(uint8, bool) { Account memory a = get(addr); return (a.kind, a.frozen); } /** * Returns the kind of the addr and the first lineage address that's frozen, or itself when frozen. * THROWS when the account doesn't exist * @dev It IS required to check ancestral existence, as this function doesn't use `lineageCount(address)` * @param addr The address of the account * @return The kind of the addr and whether any account in its lineage is frozen, or blocked by the callback */ function accountKindAndFrozenAddress(address addr) external view returns(uint8, address) { int256 oneBasedIndex = indices[addr]; require(oneBasedIndex > 0 && oneBasedIndex <= accounts, "Account doesn't exist"); Account memory a = items[oneBasedIndex]; if (a.frozen) { return (a.kind, a.addr); } uint8 kind = a.kind; address frozen; while(a.parent != ZERO_ADDRESS) { oneBasedIndex = indices[a.parent]; if (oneBasedIndex < 1 || oneBasedIndex > accounts) { break; // Parent doesn't exist } a = items[oneBasedIndex]; if (a.frozen) { frozen = a.addr; break; } } return (kind, frozen); } /** * Returns the kind of the addr, the first frozen address within the lineage, or the addr when it's frozen, and * an array of lineage addresses. * THROWS when the account doesn't exist * @dev It IS NOT required to check ancestral existence, as this is taken care of within `lineageCount(address)` * @param addr The address to get the kind, frozen address, and lineage for * @return The kind of the addr, frozen address, lineage addresses */ function accountKindAndFrozenAddressLineage(address addr) external view returns(uint8, address, address[] memory) { uint256 count = lineageCount(addr); address[] memory lineage = new address[](count); Account memory a = items[indices[addr]]; uint8 kind = a.kind; address frozen; if (a.frozen) { frozen = a.addr; } for (uint256 i = 0; i < count; i++) { a = items[indices[a.parent]]; lineage[i] = a.addr; // Set to the first frozen address if (a.frozen && frozen == ZERO_ADDRESS) { frozen = a.addr; } } return (kind, frozen, lineage); } /** * Returns the lineage addresses of the addr * THROWS when the account doesn't exist * @dev It IS NOT required to check ancestral existence, as this is taken care of within `lineageCount(address)` * @param addr The address to retrieve the lineage for * @return The lineage of the given addr */ function accountLineage(address addr) external view returns(address[] memory) { uint256 count = lineageCount(addr); address[] memory lineage = new address[](count); Account memory a = items[indices[addr]]; for (uint256 i = 0; i < count; i++) { a = items[indices[a.parent]]; lineage[i] = a.addr; } return lineage; } /** * Gets the index of the account * Returns -1 for missing accounts * @param addr The address of the account to get the index for * @return The index of the given account address */ function accountIndexOf(address addr) external view returns(int256) { if (addr == ZERO_ADDRESS) { return -1; } int256 index = indices[addr] - 1; if (index < 0 || index >= accounts) { return -1; } return index; } /** * Returns whether or not the given address exists * @param addr The account address * @return If the given address exists */ function accountExists(address addr) external view returns(bool) { int256 oneBasedIndex = indices[addr]; return oneBasedIndex > 0 && oneBasedIndex <= accounts; } /** * Returns whether or not the given address exists for the given kind * @param addr The account address * @param kind The kind of address * @return If the given address exists with the given kind */ function accountKindExists(address addr, uint8 kind) external view returns(bool) { int256 oneBasedIndex = indices[addr]; if (oneBasedIndex < 1 || oneBasedIndex > accounts) { return false; } return items[oneBasedIndex].kind == kind; } // -------------------------- Permission Getters --------------------------- /** * Retrieves the permission address at the index for the given type * THROWS when the index is out-of-bounds * @param kind The kind of permission * @param index The index of the item to retrieve * @return The permission address of the item at the given index */ function permissionAt(uint8 kind, int256 index) external view returns(address) { return permissions[kind].at(index); } /** * Gets the index of the permission address for the given type * Returns -1 for missing permission * @param kind The kind of permission * @param addr The address of the permission to get the index for * @return The index of the given permission address */ function permissionIndexOf(uint8 kind, address addr) external view returns(int256) { return permissions[kind].indexOf(addr); } /** * Returns whether or not the given permission address exists for the given type * @param kind The kind of permission * @param addr The address to check for permission * @return If the given address has permission or not */ function permissionExists(uint8 kind, address addr) external view returns(bool) { return permissions[kind].exists(addr); } // ------------------------------------------------------------------------- /** * Returns the lineage addresses of all the addresses * THROWS when any account doesn't exist * @dev Only contains existant ancestors, stopping at the first non-existent account * @param addresses The addresses to retrieve the lineage for * @return The lineage of the given addresses */ function accountLineage(address[] memory addresses) public view returns(address[] memory) { // Get the total lineage count for all addresses uint256 count; for (uint256 i = 0; i < addresses.length; i++) { count += lineageCount(addresses[i]); } // Get each lineage address for all addresses address[] memory lineage = new address[](count); uint256 i = 0; for (uint256 j = 0; j < addresses.length; j++) { Account memory a = items[indices[addresses[j]]]; int256 oneBasedIndex = indices[a.parent]; while (oneBasedIndex > 0 && oneBasedIndex <= accounts) { a = items[oneBasedIndex]; lineage[i++] = a.addr; oneBasedIndex = indices[a.parent]; } } return lineage; } /** * Gets the number of ancestors of the given addr * THROWS when the account doesn't exist * @dev Only counts existant ancestors, stopping at the first non-existent account * @param addr The address to retrieve ancestry count for * @return The number of ancestry addresses */ function lineageCount(address addr) public view returns(uint256) { int256 oneBasedIndex = indices[addr]; require(oneBasedIndex > 0 && oneBasedIndex <= accounts, "Account doesn't exist"); uint256 count; Account memory a = items[oneBasedIndex]; while(a.parent != ZERO_ADDRESS) { oneBasedIndex = indices[a.parent]; if (oneBasedIndex < 1 || oneBasedIndex > accounts) { break; // Parent doesn't exist } a = items[oneBasedIndex]; count++; } return count; } /** * Gets the account for the given address * THROWS when the account doesn't exist * @param addr The address of the item to retrieve * @return The address, kind, frozen status, and parent of the account at the given index */ function get(address addr) internal view returns(Account memory) { int256 oneBasedIndex = indices[addr]; require(oneBasedIndex > 0 && oneBasedIndex <= accounts, "Account doesn't exist"); return items[oneBasedIndex]; } /** * Checks if the given account has a cyclical kind lineage * @param account The account to check lineage for * @return If the lineage is non-cyclical */ function hasCyclicalLineage(Account memory account) internal view returns (bool, address) { // Account can't be its parent if (account.addr == account.parent) { return (true, account.parent); } // Ensure lineage kind uniqueness uint256 lineage; Account memory a = account; while(a.parent != ZERO_ADDRESS) { int256 oneBasedIndex = indices[a.parent]; if (oneBasedIndex < 1 || oneBasedIndex > accounts) { break; } uint256 l = lineage | (1 << uint256(a.kind)); if (lineage == l) { return (true, a.parent); } lineage = l; a = items[oneBasedIndex]; } return (false, ZERO_ADDRESS); } }
Returns whether or not the given address exists addr The account address return If the given address exists/
function accountExists(address addr) external view returns(bool) { int256 oneBasedIndex = indices[addr]; return oneBasedIndex > 0 && oneBasedIndex <= accounts; }
12,591,966
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "hardhat/console.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; import "./interface/IDebtor.sol"; import "./interface/ICreditor.sol"; import "./interface/ISwap.sol"; import "./interface/ISelfCompoundingYield.sol"; import "./interface/ITimelockRegistryUpgradeable.sol"; import "./reward/interfaces/IStakingMultiRewards.sol"; import "./inheritance/StorageV1ConsumerUpgradeable.sol"; /** Vault is a baseAsset lender. Vehicles are borrowers that put money to work. The design logic of the system: Each vault and vehicle is treated as an independent entity. Vault is willing to lend money, but with limited trust on the vehicles Vehicles is willing to borrow money, but only when it is beneficial to how it is using. Vehicle can potentially borrow from multiple vaults. Its sole purpose being making money to repay debt and share profits to all stakeholders. The vault focuses on: 1) Deciding where the money should be lended to. 2) Liquidating the returned baseAsset to longAsset. */ contract VaultUpgradeable is StorageV1ConsumerUpgradeable, ERC20Upgradeable, ICreditor { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; using MathUpgradeable for uint256; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; event Deposit(address indexed _who, uint256 _amount); event Withdraw(address indexed _who, uint256 _amount); event Longed(uint256 totalDeposit, uint256 baseProfit, uint256 longedProfit); event WithdrawFeeUpdated(uint256 _withdrawFeeRatio, uint256 _withdrawalFeeHalfDecayPeriod, uint256 _withdrawalFeeWaivedPeriod); // Vault lends, vehicle borrows // governance/admin to decide the maximum funds that could be invested // in an IV. // Operator push and pull the funds arbitrarily within these boundaries. // That makes it easier to decentralize Operator. struct VehicleInfo { // Debt related uint256 baseAssetDebt; // the amount of baseAsset that was borrowed by the vehicle // how much the vault is willing to lend bool disableBorrow; // if the vehicle can continue to borrow assets uint256 lendMaxBps; // the vault is willing to lend `min(lendRatioNum * totalBaseAsset, borrowCap)` uint256 lendCap; // the maximum amount that the vault is willing to lend to the vehicle } // users deposit baseAsset // the accrued interest is returned with longAsset address public baseAsset; address public longAsset; // if `selfCompoundingLongAsset` is address(0), // then it is not self compounding, we distribute long asset to the pool as it is address public selfCompoundingLongAsset; // vehicle mapping (address => VehicleInfo) public vInfo; // We disable deposit and withdraw in the same block by default to prevent attacks // However, we could allow it after the external protocol behaviour has been verified mapping(address => bool) public flashDepositAndWithdrawAllowed; mapping(address => uint256) public lastActivityBlock; // By default, there is a withdrawal fee applied on users // This flag allows us to exempt withdrawal fees on certain addresses // This is useful for protocol collaboration mapping(address => bool) public noWithdrawalFee; mapping(address => uint256) public lastFeeTime; // An artificial cap for experimental vaults uint256 public depositCap; // flag that determines if there's withdrawal fee mapping(address => uint256) public withdrawalFeeOccured; uint256 public withdrawFeeRatio; // Disable withdrawFee for newly deposted asset if it is set to 0. uint256 public withdrawalFeeHalfDecayPeriod; // Disable withdrawFee while withdrawing if it is set to 0. uint256 public withdrawalFeeWaivedPeriod; // Unit of the withdrawl fee ratio and the lending cap. uint256 constant BPS_UNIT = 10000; // Our withdrawal fee will decay 1/2 for every decay period // e.g. if decay period is 2 weeks, the maximum wtihdrawal fee after two weeks is 0.5% // after 4 weeks: 0.25%. // Maximum cap of allowed withdrawl fee. [Unit: BPS_UNIT] uint256 constant WITHDRAWAL_FEE_RATIO_CAP = 100; // 1% max // Investment vehicles that generates the interest EnumerableSetUpgradeable.AddressSet investmentVehicles; /// True if deposit is enabled. bool public vaultDepositEnabled; // Address of the reward pool (StakingMultiRewardsUpgradable) address rewardPool; modifier ifVaultDepositEnabled() { require(vaultDepositEnabled, "Vault: Deposit not enabled"); require(totalSupply() <= depositCap, "Vault: Deposit cap reached"); _; } modifier onlyDebtor() { require(isDebtor(msg.sender), "Vault: caller is not a debtor"); _; } modifier flashDepositAndWithdrawDefence() { if(!flashDepositAndWithdrawAllowed[msg.sender]){ require(lastActivityBlock[msg.sender] != block.number, "Vault: flash forbidden"); } lastActivityBlock[msg.sender] = block.number; _; } modifier timelockPassed(address iv) { // if timelock registry is not set, then timelock is not yet activated. if(registry() != address(0)) { // Check the timelock if it has been enabled. // This is present to ease initial vault deployment and setup, once a vault has been setup and linked properly // with the IVs, then we could proceed and enable the timelock. if(ITimelockRegistryUpgradeable(registry()).vaultTimelockEnabled(address(this))) { require(ITimelockRegistryUpgradeable(registry()).isIVActiveForVault(address(this), iv), "Vault: IV not available yet"); } } _; } /// Checks if the target address is debtor /// @param _target target address /// @return true if target address is debtor, false if not function isDebtor(address _target) public view returns(bool) { return investmentVehicles.contains(_target); } /// Initializes the contract function initialize( address _store, address _baseAsset, address _longAsset, uint256 _depositCap ) public virtual initializer { require(_baseAsset != _longAsset, "Base asset cannot be the same as long asset"); super.initialize(_store); baseAsset = _baseAsset; longAsset = _longAsset; depositCap = _depositCap; vaultDepositEnabled = true; // All vaults have 0 withdraw fee in the beginning. // to facilitate kickstarting the vault _setWihdrawFeeParameter(0, 2 weeks, 6 weeks); __ERC20_init( string(abi.encodePacked("lVault: ", ERC20Upgradeable(_baseAsset).name(), "=>", ERC20Upgradeable(_longAsset).name())), string(abi.encodePacked("long_", ERC20Upgradeable(_baseAsset).symbol(), "_", ERC20Upgradeable(_longAsset).symbol())) ); } /// Set the reward pool for distributing the longAsset. /// /// See Also: StakingMultiRewardsUpgradable /// @param _rewardPool Address of the reward pool. function setRewardPool(address _rewardPool) public adminPriviledged { rewardPool = _rewardPool; } // Deposit triggers investment when the investment ratio is under some threshold /// Deposit baseAsset into the vault /// @param amount The amount of baseAsset deposited from the user function deposit(uint256 amount) public virtual { _deposit(msg.sender, msg.sender, amount); } /// Deposit baseAsset into the vault for targetAccount. /// @param targetAccount Target account to deposit for /// @param amount The amount of baseAsset deposited from the user function depositFor(address targetAccount, uint256 amount) public virtual { _deposit(msg.sender, targetAccount, amount); } function _deposit(address assetFrom, address shareTo, uint256 amount) internal virtual ifVaultDepositEnabled flashDepositAndWithdrawDefence { emit Deposit(shareTo, amount); IERC20Upgradeable(baseAsset).safeTransferFrom( assetFrom, address(this), amount ); // Any deposits would reset the deposit time to the newest _mint(shareTo, amount); _accountWithdrawFeeAtDeposit(shareTo, amount); } function _accountWithdrawFeeAtDeposit(address _who, uint256 _amount) internal { if(!noWithdrawalFee[_who] && withdrawFeeRatio > 0) { uint256 withdrawFeeNewlyOccured = _amount.mul(withdrawFeeRatio).div(BPS_UNIT); withdrawalFeeOccured[_who] = withdrawlFeePending(_who).add(withdrawFeeNewlyOccured); lastFeeTime[msg.sender] = block.timestamp; } } /// Withdraw the baseAsset from the vault. /// Always withdraws 1:1, then distributes withdrawal fee /// because the interest has already been paid in other forms. /// The actual amount of the baseAsset user received is subjet to the pending withdraw fee. /// @param amount Amount of the baseAsset to be withdrawed from the vault. function withdraw(uint256 amount) public virtual flashDepositAndWithdrawDefence { // The withdrawal starts from the first investmentVehicle // This implies that we have the concept of investment depth: // The more profitable ones are the ones with higher priority // and would keep them deeper in the stack (`i` larger means deeper) // There MUST be at least one investmentVehicle, thus it is ok not to use SafeMath here uint256 balance = IERC20Upgradeable(address(this)).balanceOf(msg.sender); require(balance >= amount, "msg.sender doesn't have that much balance."); uint256 baseAssetBalanceInVault = IERC20Upgradeable(baseAsset).balanceOf(address(this)); if (investmentVehicles.length() > 0) { for ( uint256 i = 0; // withdraw starts from the first vehicle i < investmentVehicles.length() && baseAssetBalanceInVault < amount; // until it reaches the end, or if we got enough i++ ) { _withdrawFromIV(investmentVehicles.at(i), amount - baseAssetBalanceInVault); // Update `baseAssetBalanceInVault` baseAssetBalanceInVault = IERC20Upgradeable(baseAsset).balanceOf(address(this)); } } uint256 sendAmount = MathUpgradeable.min(amount, baseAssetBalanceInVault); _withdrawSendwithFee(msg.sender, sendAmount); emit Withdraw(msg.sender, sendAmount); _burn(msg.sender, sendAmount); } function _withdrawSendwithFee(address _who, uint256 _sendAmount) internal { uint256 _balance = IERC20Upgradeable(address(this)).balanceOf(msg.sender); uint256 _withdrawalFeePending = withdrawlFeePending(_who); uint256 sendAmountActual = _sendAmount; if(_withdrawalFeePending > 0) { uint256 withdrawFee = _withdrawalFeePending.mul(_sendAmount).div(_balance); withdrawalFeeOccured[_who] = _withdrawalFeePending.sub(withdrawFee); lastFeeTime[msg.sender] = block.timestamp; sendAmountActual = _sendAmount.sub(withdrawFee); IERC20Upgradeable(address(baseAsset)).safeTransfer(treasury(), withdrawFee); } IERC20Upgradeable(address(baseAsset)).safeTransfer(_who, sendAmountActual); } /// Withdral all the baseAsset from an IV. /// @param _iv Address of the IV. function withdrawAllFromIV(address _iv) public opsPriviledged { _withdrawFromIV(_iv, baseAssetDebtOf(_iv)); } /// Withdral ceterain amount of the baseAsset from an IV. /// @param _iv Address of the IV. /// @param _amount Amount of the baseAsset to be withdrawed. function withdrawFromIV(address _iv, uint256 _amount) public opsPriviledged { _withdrawFromIV(_iv, _amount); } /// Withdral ceterain amount of the baseAsset from multiple IVs. /// See withdrawFromIV for details. function withdrawFromIVs(address[] memory _ivs, uint256[] memory _amounts) public opsPriviledged { for(uint256 i = 0; i < _ivs.length; i++) { _withdrawFromIV(_ivs[i], _amounts[i]); } } /// Withdral all the baseAsset from multiple IVs. /// See withdrawAllFromIV for details. function withdrawAllFromIVs(address[] memory _ivs) public opsPriviledged { for(uint256 i = 0; i < _ivs.length; i++) { _withdrawFromIV(_ivs[i], baseAssetDebtOf(_ivs[i])); } } function _withdrawFromIV(address iv, uint256 amount) internal { uint256 beforeWithdraw = IERC20Upgradeable(baseAsset).balanceOf(address(this)); // request amount IDebtor(iv).withdrawAsCreditor( amount ); // refresh balance In Vault uint256 afterWithdraw = IERC20Upgradeable(baseAsset).balanceOf(address(this)); uint256 actuallyWithdrawn = afterWithdraw.sub(beforeWithdraw); _accountingDebtRepayment(iv, actuallyWithdrawn); } function _accountingDebtRepayment(address _debtor, uint256 repaymentAmountInBase) internal { if(repaymentAmountInBase <= vInfo[_debtor].baseAssetDebt){ vInfo[_debtor].baseAssetDebt = (vInfo[_debtor].baseAssetDebt).sub(repaymentAmountInBase); } else { // this handles the anomaly case where we got more repayment than the debt. vInfo[_debtor].baseAssetDebt = 0; } } function _accountingFundsLendingOut(address _debtor, uint256 _fundsSentOutInBase) internal { vInfo[_debtor].baseAssetDebt = (vInfo[_debtor].baseAssetDebt).add(_fundsSentOutInBase); } /// Invest all the available baseAsset in the vault. function investAll() public opsPriviledged { // V1 only invests into the default vehicle `investmentVehicles[0]` // Vault only pushes funds into the vehicle // but the money is not really at work, real investment has to // happen under the hood uint256 allAmount = IERC20Upgradeable(address(baseAsset)).balanceOf(address(this)); _investTo(investmentVehicles.at(0), allAmount); } /// Invest certain amount of the baseAsset in the vault to an IV. /// @param _target Address of the IV. /// @param _amount Amount of the baseAsset to be invested. function investTo(address _target, uint256 _amount) public opsPriviledged { _investTo(_target, _amount); } /// Invest certain amount of the baseAsset in the vault to multiple IVs. function investToIVs(address[] memory _targets, uint256[] memory _amounts) public opsPriviledged { for(uint256 i = 0 ; i < _targets.length; i++) { _investTo(_targets[i], _amounts[i]); } } /// Migrate certain amount of the baseAsset from one IV to another. /// @param _fromIv Address of the source IV. /// @param _toIv Address of the destination IV. /// @param _pullAmount Amount of the baseAsset to be pulled out from old IV. /// @param _pushAmount Amount of the baseAsset to be pushed into the new IV. function migrateFunds(address _fromIv, address _toIv, uint256 _pullAmount, uint256 _pushAmount) public opsPriviledged { _withdrawFromIV(_fromIv, _pullAmount); _investTo(_toIv, _pushAmount); } /// Calculate the lending capacity of an IV. /// This vault cannot lend baseAsset with amount more than the lending capacity. /// @param _target Address of the IV. /// @return Return the lending capacity. (Unit: BPS_UNIT) function effectiveLendCapacity(address _target) public view returns (uint256) { // totalSupply is the amount of baseAsset the vault holds uint256 capByRatio = totalSupply().mul(vInfo[_target].lendMaxBps).div(BPS_UNIT); return MathUpgradeable.min( vInfo[_target].lendCap, // hard cap capByRatio ); } function _investTo(address _target, uint256 _maxAmountBase) internal virtual returns(uint256){ require(isDebtor(_target), "Vault: investment vehicle not registered"); // The maximum amount that we will attempt to lend out will be the min of // the provided argument and the effective lend cap _maxAmountBase = MathUpgradeable.min(effectiveLendCapacity(_target), _maxAmountBase); IERC20Upgradeable(address(baseAsset)).safeApprove(_target, 0); IERC20Upgradeable(address(baseAsset)).safeApprove(_target, _maxAmountBase); uint256 baseBefore = IERC20Upgradeable(address(baseAsset)).balanceOf(address(this)); uint256 reportInvested = IDebtor(address(_target)).askToInvestAsCreditor( _maxAmountBase ); uint256 baseAfter = IERC20Upgradeable(address(baseAsset)).balanceOf(address(this)); uint256 actualInvested = baseBefore.sub(baseAfter); require(actualInvested == reportInvested, "Vault: report invested != actual invested"); IERC20Upgradeable(address(baseAsset)).safeApprove(_target, 0); _accountingFundsLendingOut(_target, actualInvested); return actualInvested; } /// Add an investment vehicle. /// @param newVehicle Address of the new IV. /// @param _lendMaxBps Lending capacity of the IV in ratio. /// @param _lendCap Lending capacity of the IV. function addInvestmentVehicle( address newVehicle, uint256 _lendMaxBps, uint256 _lendCap ) public adminPriviledged timelockPassed(newVehicle) returns(uint256) { require(!isDebtor(newVehicle), "vehicle already registered"); vInfo[newVehicle] = VehicleInfo({ baseAssetDebt: 0, disableBorrow: false, // borrow is enabled by default lendMaxBps: _lendMaxBps, lendCap: _lendCap }); investmentVehicles.add(newVehicle); } /// This moves an IV to the lowest withdraw priority. /// @param iv Address of the IV. function moveInvestmentVehicleToLowestPriority( address iv ) external adminPriviledged { require(isDebtor(iv)); // This is done by removing iv from the list and re-adding it back. // After that, the iv will be at the end of the list. investmentVehicles.remove(iv); investmentVehicles.add(iv); } /// Remove an IV from the vault. /// @param _target Address of the IV. function removeInvestmentVehicle(address _target) public adminPriviledged { require(vInfo[_target].baseAssetDebt == 0, "cannot remove vehicle with nonZero debt"); investmentVehicles.remove(_target); } /// @return Return the number of the IVs added to this vault. function investmentVehiclesLength() public view returns(uint256) { return investmentVehicles.length(); } /// @param idx Index of the IV. /// @return Return the address of an IV. function getInvestmentVehicle(uint256 idx) public view returns(address) { return investmentVehicles.at(idx); } /// @param _iv Address of the IV. /// @return Return the debt (in baseAsset) of an IV function baseAssetDebtOf(address _iv) public view returns(uint256) { return vInfo[_iv].baseAssetDebt; } /// Collect the interest from IVs and convert them into longAsset. /// The converted longAsset would be distribute to user through the reward pool. /// /// See also: StakingMultiRewardsUpgradeable /// @param ivs List of IVs to collect interest from. /// @param minimumLongProfit The minimum LongProfit collected. function collectAndLong(address[] memory ivs, uint256 minimumLongProfit) public opsPriviledged virtual { uint256 beforeBaseBalance = IERC20Upgradeable(baseAsset).balanceOf(address(this)); for(uint256 i = 0; i < ivs.length; i++){ address iv = ivs[i]; IDebtor(iv).withdrawAsCreditor( interestPendingInIV(iv) ); } uint256 afterBaseBalance = IERC20Upgradeable(baseAsset).balanceOf(address(this)); uint256 baseProfit = afterBaseBalance.sub(beforeBaseBalance); IERC20Upgradeable(baseAsset).safeApprove(swapCenter(), 0); IERC20Upgradeable(baseAsset).safeApprove(swapCenter(), baseProfit); uint256 longedProfit = ISwap(swapCenter()).swapExactTokenIn(baseAsset, longAsset, baseProfit, minimumLongProfit); emit Longed(totalSupply(), baseProfit, longedProfit); _distributeProfit(longedProfit); } function _distributeProfit(uint256 longedProfit) internal { if(selfCompoundingLongAsset == address(0)){ // not wrapping, directly notify the reward pool IERC20Upgradeable(longAsset).safeTransfer(rewardPool, longedProfit); IStakingMultiRewards(rewardPool).notifyTargetRewardAmount(longAsset, longedProfit); } else { // we should wrap long asset to self compounding IERC20Upgradeable(longAsset).safeApprove(selfCompoundingLongAsset, 0); IERC20Upgradeable(longAsset).safeApprove(selfCompoundingLongAsset, longedProfit); ISelfCompoundingYield(selfCompoundingLongAsset).deposit(longedProfit); uint256 wrappedLongBalance = ERC20Upgradeable(selfCompoundingLongAsset).balanceOf(address(this)); // notify the wrapped long to the pool IERC20Upgradeable(selfCompoundingLongAsset).safeTransfer(rewardPool, wrappedLongBalance); IStakingMultiRewards(rewardPool).notifyTargetRewardAmount(selfCompoundingLongAsset, wrappedLongBalance); } } /// Return the intest (profit) of the vault in an IV. /// The interest is defined as the baseAsset balance of the vault /// in IV minus the debt that the IV owed the vault. /// @param iv The address of the IV. /// @return The interest of the vault in the IV. function interestPendingInIV(address iv) public view returns(uint256) { uint256 balance = IDebtor(iv).baseAssetBalanceOf(address(this)); uint256 debt = vInfo[iv].baseAssetDebt; if(balance > debt) { return balance - debt; // No overflow problem. } else { return 0; } } function _updateRewards(address targetAddr) internal { require(rewardPool != address(0), "Reward pool needs to be set."); IStakingMultiRewards(rewardPool).updateAllRewards(targetAddr); } function _transfer(address sender, address recipient, uint256 amount) internal virtual override { _updateRewards(sender); _updateRewards(recipient); super._transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual override { _updateRewards(account); super._mint(account, amount); } function _burn(address account, uint256 amount) internal virtual override { _updateRewards(account); super._burn(account, amount); } /// Set the deposit cap. /// @param _depositCap Deposit cap (in baseAsset) of the vault. function setDepositCap(uint256 _depositCap) public adminPriviledged { depositCap = _depositCap; } /// Set the deposit enabled flag. /// @param _flag True if the deposit is enabled. function setDepositEnabled(bool _flag) public adminPriviledged { vaultDepositEnabled = _flag; } function setFlashDepositAndWithdrawAllowed(address[] memory _targets, bool _flag) public adminPriviledged { for(uint256 i = 0 ; i < _targets.length; i++){ flashDepositAndWithdrawAllowed[_targets[i]] = _flag; } } /// Add accounts to the no-withdrawl fee white list. function setNoWithdrawalFee(address[] memory _targets, bool _flag) public adminPriviledged { for(uint256 i = 0 ; i < _targets.length ; i++) { noWithdrawalFee[_targets[i]] = _flag; } } /// Set the withdraw fee parametrs. /// See the withdraw fee documentation for more details /// @param _withdrawFeeRatio The withdraw fee ratio. Unit: BPS_UNIT /// @param _withdrawalFeeHalfDecayPeriod The half-decay period of the withdraw fee. [second] /// @param _withdrawalFeeWaivedPeriod The withdraw fee waived period. [second] function setWihdrawFeeParameter( uint256 _withdrawFeeRatio, uint256 _withdrawalFeeHalfDecayPeriod, uint256 _withdrawalFeeWaivedPeriod ) external adminPriviledged { _setWihdrawFeeParameter(_withdrawFeeRatio, _withdrawalFeeHalfDecayPeriod, _withdrawalFeeWaivedPeriod); } function _setWihdrawFeeParameter( uint256 _withdrawFeeRatio, uint256 _withdrawalFeeHalfDecayPeriod, uint256 _withdrawalFeeWaivedPeriod ) internal { require(_withdrawFeeRatio <= WITHDRAWAL_FEE_RATIO_CAP, "withdrawFeeRatio too large"); withdrawFeeRatio = _withdrawFeeRatio; withdrawalFeeHalfDecayPeriod = _withdrawalFeeHalfDecayPeriod; withdrawalFeeWaivedPeriod = _withdrawalFeeWaivedPeriod; emit WithdrawFeeUpdated(_withdrawFeeRatio, _withdrawalFeeHalfDecayPeriod, _withdrawalFeeWaivedPeriod); } /// Calculate the current unsettled withdraw fee. /// @param _who The address to calculate the fee. /// @return fee Return the amount of the withdraw fee (as baseAsset). function withdrawlFeePending(address _who) public view returns (uint256 fee) { if(noWithdrawalFee[_who] || withdrawalFeeHalfDecayPeriod == 0){ return 0; } else { uint256 timePassed = block.timestamp.sub(lastFeeTime[_who]); if(timePassed > withdrawalFeeWaivedPeriod) { return 0; } else { // No need for safe math here. return withdrawalFeeOccured[_who] >> (timePassed/withdrawalFeeHalfDecayPeriod); } } } /// Set the self-compounding vault for the long asset. /// /// See also: SelfCompoundingYieldUpgradable /// @param _selfCompoundingLong Address of the self-compounding vault. function setLongSelfCompounding(address _selfCompoundingLong) public adminPriviledged { selfCompoundingLongAsset = _selfCompoundingLong; } } // 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; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../GSN/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view 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 { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../GSN/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 returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IDebtor { // Debtor should implement accounting at `withdrawAsCreditor()` and `askToInvestAsCreditor()` function withdrawAsCreditor(uint256 _amount) external returns (uint256); function askToInvestAsCreditor(uint256 _amount) external returns (uint256); function baseAssetBalanceOf( address _address ) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface ICreditor { } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface ISwap { function swapExactTokenIn(address tokenIn, address tokenOut, uint256 amountIn, uint256 minAmountOut) external payable returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface ISelfCompoundingYield { function baseAsset() external view returns (address); function deposit(uint256 baseAmount) external; function withdraw(uint256 shareAmount) external; function shareToBaseAsset(uint256 share) external view returns (uint256); function baseAssetToShare(uint256 baseAmount) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface ITimelockRegistryUpgradeable { function effectiveTimelock() external view returns (uint256); function isIVActiveGlobal(address iv) external view returns (bool); function isIVActiveForVault(address vault, address iv) external view returns (bool); function isIVInsuredByInsuranceVault(address vault, address iv) external view returns (bool); function vaultTimelockEnabled(address vault) external view returns(bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/istakingrewards interface IStakingMultiRewards { function totalSupply() external view returns(uint256); function lastTimeRewardApplicable(address targetYield) external view returns (uint256) ; function rewardPerToken(address targetYield) external view returns (uint256); function earned(address targetYield, address account) external view returns(uint256); function setRewardDistribution(address[] calldata _rewardDistributions, bool _flag) external; function notifyTargetRewardAmount(address targetYield, uint256 reward) external; function updateAllRewards(address targetAccount) external; function updateReward(address targetYield, address targetAccount) external; function getAllRewards() external; function getAllRewardsFor(address user) external; function getReward(address targetYield) external; function getRewardFor(address user, address targetYield) external; function addReward(address targetYield, uint256 duration, bool isSelfCompoundingYield) external; function removeReward(address targetYield) external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "../utilities/UnstructuredStorageWithTimelock.sol"; import "../StorageV1Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; contract StorageV1ConsumerUpgradeable is Initializable { using UnstructuredStorageWithTimelock for bytes32; // bytes32(uint256(keccak256("eip1967.proxy.storage")) - 1 bytes32 private constant _STORAGE_SLOT = 0x23bdfa8033717db08b14621917cfe422b93b161b8e3ef1c873d2197616ec0bb2; modifier onlyGovernance() { require( msg.sender == governance(), "StorageV1ConsumerUpgradeable: Only governance" ); _; } modifier adminPriviledged() { require(msg.sender == governance() || isAdmin(msg.sender), "StorageV1ConsumerUpgradeable: not governance or admin"); _; } modifier opsPriviledged() { require(msg.sender == governance() || isAdmin(msg.sender) || isOperator(msg.sender), "StorageV1ConsumerUpgradeable: not governance or admin or operator"); _; } function initialize(address _store) public virtual initializer { address curStorage = (_STORAGE_SLOT).fetchAddress(); require( curStorage == address(0), "StorageV1ConsumerUpgradeable: Initialized" ); (_STORAGE_SLOT).setAddress(_store); } function store() public view returns (address) { return (_STORAGE_SLOT).fetchAddress(); } function governance() public view returns (address) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.governance(); } function treasury() public view returns (address) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.treasury(); } function swapCenter() public view returns (address) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.swapCenter(); } function registry() public view returns (address) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.registry(); } function storageFetchAddress(bytes32 key) public view returns (address) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.addressStorage(key); } function storageFetchAddressInArray(bytes32 key, uint256 index) public view returns (address) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.addressArrayStorage(key, index); } function storageFetchUint256(bytes32 key) public view returns (uint256) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.uint256Storage(key); } function storageFetchUint256InArray(bytes32 key, uint256 index) public view returns (uint256) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.uint256ArrayStorage(key, index); } function storageFetchBool(bytes32 key) public view returns (bool) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.boolStorage(key); } function storageFetchBoolInArray(bytes32 key, uint256 index) public view returns (bool) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.boolArrayStorage(key, index); } function isAdmin(address _who) public view returns (bool) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.isAdmin(_who); } function isOperator(address _who) public view returns (bool) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.isOperator(_who); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <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 {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /** UnstructuredStorageWithTimelock is a set of functions that facilitates setting/fetching unstructured storage along with information of future updates and its timelock information. For every content storage, there are two other slots that could be calculated automatically: * Slot (The current value) * Scheduled Slot (The future value) * Scheduled Time (The future time) Note that the library does NOT enforce timelock and does NOT store the timelock information. */ library UnstructuredStorageWithTimelock { // This is used to calculate the time slot and scheduled content for different variables uint256 private constant SCHEDULED_SIGNATURE = 0x111; uint256 private constant TIMESLOT_SIGNATURE = 0xAAA; function updateAddressWithTimelock(bytes32 _slot) internal { require( scheduledTime(_slot) > block.timestamp, "Timelock has not passed" ); setAddress(_slot, scheduledAddress(_slot)); } function updateUint256WithTimelock(bytes32 _slot) internal { require( scheduledTime(_slot) > block.timestamp, "Timelock has not passed" ); setUint256(_slot, scheduledUint256(_slot)); } function setAddress(bytes32 _slot, address _target) internal { // solhint-disable-next-line no-inline-assembly assembly { sstore(_slot, _target) } } function fetchAddress(bytes32 _slot) internal view returns (address result) { assembly { result := sload(_slot) } } function scheduledAddress(bytes32 _slot) internal view returns (address result) { result = fetchAddress(scheduledContentSlot(_slot)); } function scheduledUint256(bytes32 _slot) internal view returns (uint256 result) { result = fetchUint256(scheduledContentSlot(_slot)); } function setUint256(bytes32 _slot, uint256 _target) internal { // solhint-disable-next-line no-inline-assembly assembly { sstore(_slot, _target) } } function fetchUint256(bytes32 _slot) internal view returns (uint256 result) { assembly { result := sload(_slot) } } function scheduledContentSlot(bytes32 _slot) internal pure returns (bytes32) { return bytes32( uint256(keccak256(abi.encodePacked(_slot, SCHEDULED_SIGNATURE))) ); } function scheduledTime(bytes32 _slot) internal view returns (uint256) { return fetchUint256(scheduledTimeSlot(_slot)); } function scheduledTimeSlot(bytes32 _slot) internal pure returns (bytes32) { return bytes32( uint256(keccak256(abi.encodePacked(_slot, TIMESLOT_SIGNATURE))) ); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "hardhat/console.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; contract StorageV1Upgradeable is Initializable { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; address public proxyAdmin; address public governance; address public _treasury; EnumerableSetUpgradeable.AddressSet admin; EnumerableSetUpgradeable.AddressSet operator; address public swapCenter; address public registry; bool public registryLocked; mapping(bytes32 => address) public addressStorage; mapping(bytes32 => address[]) public addressArrayStorage; mapping(bytes32 => uint256) public uint256Storage; mapping(bytes32 => uint256[]) public uint256ArrayStorage; mapping(bytes32 => bool) public boolStorage; mapping(bytes32 => bool[]) public boolArrayStorage; event GovernanceChanged(address oldGov, address newGov); event TreasuryChanged(address oldTreasury, address newTreasury); event AdminAdded(address newAdmin); event AdminRetired(address retiredAdmin); event OperatorAdded(address newOperator); event OperatorRetired(address oldOperator); event RegistryChanged(address oldRegistry, address newRegistry); event SwapCenterChanged(address oldSwapCenter, address newSwapCenter); event RegistryLocked(); modifier onlyGovernance() { require(msg.sender == governance, "StorageV1: not governance"); _; } modifier adminPriviledged() { require(msg.sender == governance || isAdmin(msg.sender), "StorageV1: not governance or admin"); _; } modifier registryNotLocked() { require(!registryLocked, "StorageV1: registry locked"); _; } constructor() { governance = msg.sender; } function initialize(address _governance, address _proxyAdmin) external initializer { require(_governance != address(0), "!empty"); require(_proxyAdmin != address(0), "!empty"); governance = _governance; proxyAdmin = _proxyAdmin; } function setGovernance(address _governance) external onlyGovernance { require(_governance != address(0), "!empty"); emit GovernanceChanged(governance, _governance); governance = _governance; } function treasury() external view returns (address) { if(_treasury == address(0)) { return governance; } else { return _treasury; } } function setTreasury(address _newTreasury) external onlyGovernance { require(_newTreasury != address(0)); emit TreasuryChanged(_treasury, _newTreasury); _treasury = _newTreasury; } function setRegistry(address _registry) external onlyGovernance registryNotLocked { require(_registry != address(0), "!empty"); emit RegistryChanged(registry, _registry); registry = _registry; } function lockRegistry() external onlyGovernance { emit RegistryLocked(); registryLocked = true; // While the contract doesn't provide an unlock method // It is still possible to unlock this via Timelock, by upgrading the // implementation of the Timelock proxy. } function setSwapCenter(address _swapCenter) external onlyGovernance { emit SwapCenterChanged(swapCenter, _swapCenter); swapCenter = _swapCenter; } function setAddress(bytes32 index, address _newAddr) external onlyGovernance { addressStorage[index] = _newAddr; } function setAddressArray(bytes32 index, address[] memory _newAddrs) external onlyGovernance { addressArrayStorage[index] = _newAddrs; } function setUint256(bytes32 index, uint256 _newUint256) external onlyGovernance { uint256Storage[index] = _newUint256; } function setUint256Array(bytes32 index, uint256[] memory _newAddrs) external onlyGovernance { uint256ArrayStorage[index] = _newAddrs; } function setUint256(bytes32 index, bool _newBool) external onlyGovernance { boolStorage[index] = _newBool; } function setBoolArray(bytes32 index, bool[] memory _newBools) external onlyGovernance { boolArrayStorage[index] = _newBools; } function numOfAdmin() public view returns (uint256) { return admin.length(); } function numOfOperator() public view returns (uint256) { return operator.length(); } function getAdmin(uint256 idx) public view returns (address){ return admin.at(idx); } function getOperator(uint256 idx) public view returns (address){ return operator.at(idx); } function addAdmin(address _who) public onlyGovernance returns (bool) { emit AdminAdded(_who); return admin.add(_who); } function addOperator(address _who) public adminPriviledged returns (bool) { emit OperatorAdded(_who); return operator.add(_who); } function removeAdmin(address _who) public onlyGovernance returns (bool) { emit AdminRetired(_who); return admin.remove(_who); } function removeOperator(address _who) public adminPriviledged returns (bool) { emit OperatorRetired(_who); return operator.remove(_who); } function isAdmin(address _who) public view returns (bool) { return admin.contains(_who); } function isOperator(address _who) public view returns (bool) { return operator.contains(_who); } }
https:docs.synthetix.io/contracts/source/interfaces/istakingrewards
interface IStakingMultiRewards { function totalSupply() external view returns(uint256); function lastTimeRewardApplicable(address targetYield) external view returns (uint256) ; function rewardPerToken(address targetYield) external view returns (uint256); function earned(address targetYield, address account) external view returns(uint256); function setRewardDistribution(address[] calldata _rewardDistributions, bool _flag) external; function notifyTargetRewardAmount(address targetYield, uint256 reward) external; function updateAllRewards(address targetAccount) external; function updateReward(address targetYield, address targetAccount) external; function getAllRewards() external; function getAllRewardsFor(address user) external; function getReward(address targetYield) external; function getRewardFor(address user, address targetYield) external; function addReward(address targetYield, uint256 duration, bool isSelfCompoundingYield) external; function removeReward(address targetYield) external; pragma solidity >=0.4.24; }
276,986
/** *Submitted for verification at Etherscan.io on 2022-03-17 */ // SPDX-License-Identifier: UNLICENSED // File: contracts/abstract/OwnableDelegateProxy.sol pragma solidity 0.8.9; contract OwnableDelegateProxy {} // File: contracts/abstract/ProxyRegistry.sol pragma solidity 0.8.9; // Part: ProxyRegistry contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // File: contracts/abstract/IERC1155TokenReceiver.sol pragma solidity 0.8.9; /** * @dev ERC-1155 interface for accepting safe transfers. */ interface IERC1155TokenReceiver { /** * @notice Handle the receipt of a single ERC1155 token type * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value MUST result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _amount The amount of tokens being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received( address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data ) external returns ( bytes4 ) ; /** * @notice Handle the receipt of multiple ERC1155 token types * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value WILL result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeBatchTransferFrom` function * @param _from The address which previously owned the token * @param _ids An array containing ids of each token being transferred * @param _amounts An array containing amounts of each token being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived( address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data ) external returns ( bytes4 ) ; /** * @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types. * @param interfaceID The ERC-165 interface ID that is queried for support.s * @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface. * This function MUST NOT consume more than 5,000 gas. * @return Wheter ERC-165 or ERC1155TokenReceiver interfaces are supported. */ function supportsInterface(bytes4 interfaceID) external view returns (bool); } // File: contracts/abstract/ERC1155Metadata.sol pragma solidity 0.8.9; /** * @notice Contract that handles metadata related methods. * @dev Methods assume a deterministic generation of URI based on token IDs. * Methods also assume that URI uses hex representation of token IDs. */ abstract contract ERC1155Metadata { /***********************************| * | Metadata Public Function s | |__________________________________*/ /** * @notice A distinct Uniform Resource Identifier (URI) for a given token. * @dev URIs are defined in RFC 3986. * URIs are assumed to be deterministically generated based on token ID * Token IDs are assumed to be represented in their hex format in URIs * @return URI string */ function uri(uint256 _id) external view virtual returns (string memory); } // File: contracts/abstract/IERC1155.sol pragma solidity 0.8.9; interface IERC1155 { // Events /** * @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning * Operator MUST be msg.sender * When minting/creating tokens, the `_from` field MUST be set to `0x0` * When burning/destroying tokens, the `_to` field MUST be set to `0x0` * The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID * To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0 */ event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount); /** * @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning * Operator MUST be msg.sender * When minting/creating tokens, the `_from` field MUST be set to `0x0` * When burning/destroying tokens, the `_to` field MUST be set to `0x0` * The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID * To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0 */ event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts); /** * @dev MUST emit when an approval is updated */ event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /** * @dev MUST emit when the URI is updated for a token ID * URIs are defined in RFC 3986 * The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema" */ event URI(string _uri, uint256 indexed _id); /** * @notice Transfers amount of an _id from the _from address to the _to address specified * @dev MUST emit TransferSingle event on success * Caller must be approved to manage the _from account's tokens (see isApprovedForAll) * MUST throw if `_to` is the zero address * MUST throw if balance of sender for token `_id` is lower than the `_amount` sent * MUST throw on any other error * When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data ) external; /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @dev MUST emit TransferBatch event on success * Caller must be approved to manage the _from account's tokens (see isApprovedForAll) * MUST throw if `_to` is the zero address * MUST throw if length of `_ids` is not the same as length of `_amounts` * MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sent * MUST throw on any other error * When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom( address _from, address _to, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data ) external; /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) external view returns (uint256); /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders * @param _ids ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch( address[] calldata _owners, uint256[] calldata _ids ) external view returns ( uint256[] memory ) ; /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @dev MUST emit the ApprovalForAll event on success * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external; /** * @notice Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return isOperator True if the operator is approved, false if not */ function isApprovedForAll( address _owner, address _operator ) external view returns ( bool isOperator ) ; } // File: contracts/abstract/IERC165.sol pragma solidity 0.8.9; /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas * @param _interfaceId The interface identifier, as specified in ERC-165 */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } // File: contracts/abstract/Address.sol pragma solidity 0.8.9; /** * @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.3._ */ 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.3._ */ 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/abstract/Roles.sol pragma solidity 0.8.9; /** * @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: contracts/abstract/Context.sol pragma solidity 0.8.9; /* * @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) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: contracts/abstract/Ownable.sol pragma solidity 0.8.9; // Part: OpenZeppelin/[email protected]/Ownable /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * 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 returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/abstract/MinterRole.sol pragma solidity 0.8.9; /** * @title MinterRole * @dev Owner is responsible to add/remove minter */ contract MinterRole is Context, Ownable { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; modifier onlyMinter() { require( isMinter(_msgSender()), "MinterRole: caller does not have the Minter role" ); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyOwner { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } // File: contracts/abstract/SafeMath.sol pragma solidity 0.8.9; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/abstract/ERC1155.sol pragma solidity 0.8.9; /** * @dev Implementation of Multi-Token Standard contract */ abstract contract ERC1155 is IERC1155, IERC165, ERC1155Metadata { using SafeMath for uint256; using Address for address; /***********************************| * | Variables and Events | |__________________________________*/ // onReceive function signatures bytes4 internal constant ERC1155_RECEIVED_VALUE = 0xf23a6e61; bytes4 internal constant ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81; // Objects balances mapping(address => mapping(uint256 => uint256)) internal balances; // Operator Functions mapping(address => mapping(address => bool)) internal operators; /***********************************| * | Public Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data ) public override virtual { require(( msg.sender == _from ) || _isApprovedForAll(_from, msg.sender), "ERC1155#safeTransferFrom: INVALID_OPERATOR"); require(_to != address(0), "ERC1155#safeTransferFrom: INVALID_RECIPIENT"); // require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations _safeTransferFrom(_from, _to, _id, _amount); _callonERC1155Received(_from, _to, _id, _amount, _data); } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom( address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) public override virtual { // Requirements require(( msg.sender == _from ) || _isApprovedForAll(_from, msg.sender), "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR"); require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT"); _safeBatchTransferFrom(_from, _to, _ids, _amounts); _callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data); } /***********************************| * | Internal Transfer Functions | |__________________________________*/ /** * @dev Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount */ function _safeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount ) internal { // Update balances balances[_from][_id] = balances[_from][_id].sub ( _amount ) ; // Subtract amount balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount // Emit event emit TransferSingle(msg.sender, _from, _to, _id, _amount); } /** * @dev Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...) */ function _callonERC1155Received( address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data ) internal { if (_to.isContract()) { try IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data) returns (bytes4 response) { if (response != ERC1155_RECEIVED_VALUE) { revert("ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155#_callonERC1155Received: transfer to non ERC1155Receiver implementer"); } } } /** * @dev Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type */ function _safeBatchTransferFrom( address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts ) internal { require ( _ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH" ) ; // Number of transfer to execute uint256 nTransfer = _ids.length; // Executing all transfers for (uint256 i = 0; i < nTransfer;i++) { // Update storage balance of previous bin balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit event emit TransferBatch(msg.sender, _from, _to, _ids, _amounts); } /** * @dev Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...) */ function _callonERC1155BatchReceived( address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) internal { // Check if recipient is contract if (_to.isContract() ) { try IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data) returns (bytes4 response) { if (response != ERC1155_BATCH_RECEIVED_VALUE) { revert("ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155#_callonERC1155BatchReceived: transfer to non ERC1155Receiver implementer"); } } } /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external override { // Update operator status operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @dev Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return isOperator true if the operator is approved, false if not */ function _isApprovedForAll( address _owner, address _operator ) internal view returns (bool isOperator) { return operators[_owner][_operator]; } /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) override public view returns (uint256) { return balances[_owner][_id]; } /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders * @param _ids ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] memory _owners, uint256[] memory _ids) override public view returns (uint256[] memory) { require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH"); // Variables uint256[] memory batchBalances = new uint256[](_owners.length); // Iterate over each owner and token ID for (uint256 i = 0; i < _owners.length;i++) { batchBalances[i] = balances[_owners[i]][_ids[i]]; } return batchBalances; } /* * INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); */ bytes4 private constant INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7; /* * INTERFACE_SIGNATURE_ERC1155 = * bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^ * bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^ * bytes4(keccak256("balanceOf(address,uint256)")) ^ * bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^ * bytes4(keccak256("setApprovalForAll(address,bool)")) ^ * bytes4(keccak256("isApprovedForAll(address,address)")); */ bytes4 private constant INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26; /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` and */ function supportsInterface(bytes4 _interfaceID) override external pure returns (bool) { if (_interfaceID == INTERFACE_SIGNATURE_ERC165 || _interfaceID == INTERFACE_SIGNATURE_ERC1155) { return true; } return false; } } // File: contracts/abstract/ERC1155MintBurn.sol pragma solidity 0.8.9; /** * @dev Multi-Fungible Tokens with minting and burning methods. These methods assume * a parent contract to be executed as they are `internal` functions */ abstract contract ERC1155MintBurn is ERC1155 { using SafeMath for uint256; /****************************************| * | Minting Functions | |_______________________________________*/ /** * @dev Mint _amount of tokens of a given id * @param _to The address to mint tokens to * @param _id Token id to mint * @param _amount The amount to be minted * @param _data Data to pass if receiver is contract */ function _mint(address _to, uint256 _id, uint256 _amount, bytes memory _data) internal { // Add _amount balances[_to][_id] = balances[_to][_id].add(_amount); // Emit event emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount); // Calling onReceive method if recipient is contract _callonERC1155Received(address(0x0), _to, _id, _amount, _data); } /** * @dev Mint tokens for each ids in _ids * @param _to The address to mint tokens to * @param _ids Array of ids to mint * @param _amounts Array of amount of tokens to mint per id * @param _data Data to pass if receiver is contract */ function _batchMint( address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) internal { require ( _ids.length == _amounts.length, "ERC1155MintBurn#batchMint: INVALID_ARRAYS_LENGTH" ) ; // Number of mints to execute uint256 nMint = _ids.length; // Executing all minting for (uint256 i = 0; i < nMint;i++) { // Update storage balance balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, address(0x0), _to, _ids, _amounts); // Calling onReceive method if recipient is contract _callonERC1155BatchReceived(address(0x0), _to, _ids, _amounts, _data); } /****************************************| * | Burning Functions | |_______________________________________*/ /** * @dev Burn _amount of tokens of a given token id * @param _from The address to burn tokens from * @param _id Token id to burn * @param _amount The amount to be burned */ function _burn(address _from, uint256 _id, uint256 _amount) internal { // Substract _amount balances[_from][_id] = balances[_from][_id].sub(_amount); // Emit event emit TransferSingle(msg.sender, _from, address(0x0), _id, _amount); } /** * @dev Burn tokens of given token id for each (_ids[i], _amounts[i]) pair * @param _from The address to burn tokens from * @param _ids Array of token ids to burn * @param _amounts Array of the amount to be burned */ function _batchBurn( address _from, uint256[] memory _ids, uint256[] memory _amounts ) internal { require ( _ids.length == _amounts.length, "ERC1155MintBurn#batchBurn: INVALID_ARRAYS_LENGTH" ) ; // Number of mints to execute uint256 nBurn = _ids.length; // Executing all minting for (uint256 i = 0; i < nBurn;i++) { // Update storage balance balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, _from, address(0x0), _ids, _amounts); } } // File: contracts/abstract/ERC1155Tradable.sol pragma solidity 0.8.9; /** * @title ERC1155Tradable * ERC1155Tradable - ERC1155 contract that whitelists an operator address, * has create and mint functionality, and supports useful standards from OpenZeppelin, * like _exists(), name(), symbol(), and totalSupply() */ abstract contract ERC1155Tradable is ERC1155MintBurn, Ownable, MinterRole { using SafeMath for uint256; using Address for address; // OpenSea proxy registry to ease selling NFTs on OpenSea address public proxyRegistryAddress; mapping(uint256 => address) public creators; mapping(uint256 => uint256) public tokenSupply; mapping(uint256 => uint256) public tokenMaxSupply; mapping(uint256 => uint8) public tokenCityIndex; mapping(uint256 => uint8) public tokenType; // Contract name string public name; // Contract symbol string public symbol; // URI's default URI prefix string internal baseMetadataURI; uint256 internal _currentTokenID = 0; constructor (string memory _name, string memory _symbol, address _proxyRegistryAddress, string memory _baseMetadataURI) { name = _name; symbol = _symbol; proxyRegistryAddress = _proxyRegistryAddress; baseMetadataURI = _baseMetadataURI; } function contractURI() public view returns (string memory) { return string(abi.encodePacked(baseMetadataURI)); } /** * @dev Returns URIs are defined in RFC 3986. * URIs are assumed to be deterministically generated based on token ID * Token IDs are assumed to be represented in their hex format in URIs * @return URI string */ function uri(uint256 _id) override external view returns (string memory) { require(_exists(_id), "Deed NFT doesn't exists"); return string(abi.encodePacked(baseMetadataURI, _uint2str(_id))); } /** * @dev Returns the total quantity for a token ID * @param _id uint256 ID of the token to query * @return amount of token in existence */ function totalSupply(uint256 _id) public view returns (uint256) { return tokenSupply[_id]; } /** * @dev Returns the max quantity for a token ID * @param _id uint256 ID of the token to query * @return amount of token in existence */ function maxSupply(uint256 _id) public view returns (uint256) { return tokenMaxSupply[_id]; } /** * @dev return city index of designated NFT with its identifier */ function cityIndex(uint256 _id) public view returns (uint256) { require(_exists(_id), "Deed NFT doesn't exists"); return tokenCityIndex[_id]; } /** * @dev return card type of designated NFT with its identifier */ function cardType(uint256 _id) public view returns (uint256) { require(_exists(_id), "Deed NFT doesn't exists"); return tokenType[_id]; } /** * @dev Creates a new token type and assigns _initialSupply to an address * @param _initialOwner the first owner of the Token * @param _initialSupply Optional amount to supply the first owner (1 for NFT) * @param _maxSupply max supply allowed (1 for NFT) * @param _cityIndex city index of NFT * (0 = Tanit, 1 = Reshef, 2 = Ashtarte, 3 = Melqart, 4 = Eshmun, 5 = Kushor, 6 = Hammon) * @param _type card type of NFT * (0 = Common, 1 = Uncommon, 2 = Rare, 3 = Legendary) * @param _data Optional data to pass if receiver is contract * @return The newly created token ID */ function create( address _initialOwner, uint256 _initialSupply, uint256 _maxSupply, uint8 _cityIndex, uint8 _type, bytes memory _data ) public onlyMinter returns (uint256) { require(_initialSupply <= _maxSupply, "_initialSupply > _maxSupply"); uint256 _id = _getNextTokenID(); _incrementTokenTypeId(); creators[_id] = _initialOwner; if (_initialSupply != 0) { _mint(_initialOwner, _id, _initialSupply, _data); } tokenSupply[_id] = _initialSupply; tokenMaxSupply[_id] = _maxSupply; tokenCityIndex[_id] = _cityIndex; tokenType[_id] = _type; return _id; } /** * @dev Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings. * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return isOperator true if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) override public view returns (bool isOperator) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return _isApprovedForAll(_owner, _operator); } /** * @dev Returns whether the specified token exists by checking to see if it has a creator * @param _id uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 _id) internal view returns (bool) { return creators[_id] != address(0); } /** * @dev calculates the next token ID based on value of _currentTokenID * @return uint256 for the next token ID */ function _getNextTokenID() private view returns (uint256) { return _currentTokenID.add(1); } /** * @dev increments the value of _currentTokenID */ function _incrementTokenTypeId() private { _currentTokenID++; } /** * @dev Convert uint256 to string * @param _i Unsigned integer to convert to string */ function _uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k] = bytes1(uint8(48 + _i % 10)); _i /= 10; if (k > 0) { k--; } } return string(bstr); } } // File: contracts/abstract/ManagerRole.sol pragma solidity 0.8.9; /** * @title ManagerRole * @dev Owner is responsible to add/remove manager */ contract ManagerRole is Context, Ownable { using Roles for Roles.Role; event ManagerAdded(address indexed account); event ManagerRemoved(address indexed account); Roles.Role private _managers; modifier onlyManager() { require(isManager(_msgSender()), "ManagerRole: caller does not have the Manager role"); _; } function isManager(address account) public view returns (bool) { return _managers.has(account); } function addManager(address account) public onlyOwner { _addManager(account); } function removeManager(address account) public onlyOwner { _removeManager(account); } function _addManager(address account) internal { _managers.add(account); emit ManagerAdded(account); } function _removeManager(address account) internal { _managers.remove(account); emit ManagerRemoved(account); } } // File: contracts/abstract/StrategyRole.sol pragma solidity 0.8.9; /** * @title StrategyRole * @dev Owner is responsible to add/remove strategy */ contract StrategyRole is Context, ManagerRole { using Roles for Roles.Role; event StrategyAdded(address indexed account); event StrategyRemoved(address indexed account); Roles.Role private _strategies; modifier onlyStrategy() { require(isStrategy(_msgSender()), "StrategyRole: caller does not have the Strategy role"); _; } function isStrategy(address account) public view returns (bool) { return _strategies.has(account); } function addStrategy(address account) public onlyManager { _addStrategy(account); } function removeStrategy(address account) public onlyManager { _removeStrategy(account); } function _addStrategy(address account) internal { _strategies.add(account); emit StrategyAdded(account); } function _removeStrategy(address account) internal { _strategies.remove(account); emit StrategyRemoved(account); } } // File: contracts/abstract/StrategyHandler.sol pragma solidity 0.8.9; /** * @title NFT Contract for Meeds DAO */ interface StrategyHandler is IERC1155 { /** * @dev return the total use count of an NFT by a wallet */ function getTotalUseCount(address _account, uint256 _id) external view returns (uint256); /** * @dev return the use count of an NFT by wallet inside a strategy */ function getStrategyUseCount(address _account, uint256 _id, address _strategy) external view returns (uint256); /** * @notice Mark NFT as being used. Only callable by registered strategies * @param _account User account address * @param _id ID of the token type */ function startUsingNFT(address _account, uint256 _id) external returns (bool); /** * @notice Unmark NFT as being used. Only callable by registered strategies * @param _account User account address * @param _id ID of the token type */ function endUsingNFT(address _account, uint256 _id) external returns (bool); } // File: contracts/Deed.sol pragma solidity 0.8.9; /** * @title NFT Contract for Meeds DAO */ contract Deed is ERC1155Tradable, StrategyHandler, StrategyRole { using SafeMath for uint256; event StartedUsingNFT(address indexed account, uint256 indexed id, address indexed strategy); event EndedUsingNFT(address indexed account, uint256 indexed id, address indexed strategy); // mapping account => nftId => useCount // this is used to restrict transfers if nft is being used in any strategy mapping(address => mapping(uint256 => uint256)) internal totalUseCount; // mapping account => nftId => strategyAddress => useCount // this is used to make sure a strategy can only end using nft that it started using before mapping(address => mapping(uint256 => mapping(address => uint256))) internal stratUseCount; constructor (address _proxyRegistryAddress, string memory _baseMetadataURI) ERC1155Tradable("Meeds Deed Token", "DEED", _proxyRegistryAddress, _baseMetadataURI) { } /** * @dev Will update the base URL of token's URI * @param _newBaseMetadataURI New base URL of token's URI */ function setBaseMetadataURI(string memory _newBaseMetadataURI) public onlyManager { baseMetadataURI = _newBaseMetadataURI; } /** * @dev return the list of NFTs owned by an address */ function nftsOf(address _account) public view returns (uint256[] memory) { uint256 len = 0; for (uint256 i = 1; i <= _currentTokenID; i++) { if (balances[_account][i] > 0) { len++; } } uint256 index = 0; uint256[] memory nfts = new uint256[](len); for (uint256 i = 1; i <= _currentTokenID; i++) { if (balances[_account][i] > 0) { nfts[index++] = i; } } return nfts; } /** * @dev return the total supply of NFTs (Token Types) */ function totalSupply() public view returns (uint256) { return _currentTokenID; } /** * @dev return the total use count of an NFT by owner */ function getTotalUseCount(address _account, uint256 _id) external view returns (uint256) { return totalUseCount[_account][_id]; } /** * @dev return the use count of an NFT by wallet inside a strategy */ function getStrategyUseCount(address _account, uint256 _id, address _strategy) external view returns (uint256) { return stratUseCount[_account][_id][_strategy]; } /** * @notice Mark NFT as being used. Only callable by registered strategies * @param _account User account address * @param _id ID of the token type */ function startUsingNFT(address _account, uint256 _id) external onlyStrategy returns (bool) { require(balances[_account][_id] > 0, "Deed#startUsingNFT: user account doesn't own the NFT"); stratUseCount[_account][_id][msg.sender] = stratUseCount[_account][_id][msg.sender].add(1); totalUseCount[_account][_id] = totalUseCount[_account][_id].add(1); emit StartedUsingNFT(_account, _id, msg.sender); return true; } /** * @notice Unmark NFT as being used. Only callable by registered strategies * @param _account User account address * @param _id ID of the token type */ function endUsingNFT(address _account, uint256 _id) external onlyStrategy returns (bool) { require(stratUseCount[_account][_id][msg.sender] > 0, "Deed#endUsingNFT: NFT is not currently in use by strategy"); stratUseCount[_account][_id][msg.sender] = stratUseCount[_account][_id][msg.sender].sub(1); totalUseCount[_account][_id] = totalUseCount[_account][_id].sub(1); emit EndedUsingNFT(_account, _id, msg.sender); return true; } /** * @dev Overrides safeTransferFrom function of ERC1155 to introduce totalUseCount check */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) public override (ERC1155, IERC1155) { require(totalUseCount[_from][_id] == 0, "Deed#safeTransferFrom: NFT being used in strategy"); ERC1155.safeTransferFrom(_from, _to, _id, _amount, _data); } /** * @dev Overrides safeBatchTransferFrom function of ERC1155 to introduce totalUseCount check */ function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) public override (ERC1155, IERC1155) { // Number of transfer to execute uint256 nTransfer = _ids.length; // check if any nft is being used for (uint256 i = 0; i < nTransfer; i++) { require(totalUseCount[_from][_ids[i]] == 0, "Deed#safeBatchTransferFrom: NFT being used in strategy"); } ERC1155.safeBatchTransferFrom(_from, _to, _ids, _amounts, _data); } }
Get the balance of an account's Tokens _owner The address of the token holder _id ID of the Token return The _owner's balance of the Token type requested/
function balanceOf(address _owner, uint256 _id) override public view returns (uint256) { return balances[_owner][_id]; }
7,635,439
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "../interfaces/IN.sol"; import "../interfaces/INilPass.sol"; import "../interfaces/IPricingStrategy.sol"; /** * @title NilPassCore contract * @author Tony Snark * @notice This contract provides basic functionalities to allow minting using the NilPass * @dev This contract should be used only for testing or testnet deployments */ abstract contract NilPassCore is ERC721Enumerable, ReentrancyGuard, AccessControl, INilPass, IPricingStrategy { uint128 public constant MAX_MULTI_MINT_AMOUNT = 32; uint128 public constant MAX_N_TOKEN_ID = 8888; bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); bytes32 public constant DAO_ROLE = keccak256("DAO"); IN public immutable n; uint16 public reserveMinted; uint256 public mintedOutsideNRange; address public masterMint; DerivativeParameters public derivativeParams; uint128 maxTokenId; struct DerivativeParameters { bool onlyNHolders; bool supportsTokenId; uint16 reservedAllowance; uint128 maxTotalSupply; uint128 maxMintAllowance; } event Minted(address to, uint256 tokenId); /** * @notice Construct an NilPassCore instance * @param name Name of the token * @param symbol Symbol of the token * @param n_ Address of your n instance (only for testing) * @param derivativeParams_ Parameters describing the derivative settings * @param masterMint_ Address of the master mint contract * @param dao_ Address of the NIL DAO */ constructor( string memory name, string memory symbol, IN n_, DerivativeParameters memory derivativeParams_, address masterMint_, address dao_ ) ERC721(name, symbol) { derivativeParams = derivativeParams_; require(derivativeParams.maxTotalSupply > 0, "NilPass:INVALID_SUPPLY"); require( !derivativeParams.onlyNHolders || (derivativeParams.onlyNHolders && derivativeParams.maxTotalSupply <= MAX_N_TOKEN_ID), "NilPass:INVALID_SUPPLY" ); require(derivativeParams.maxTotalSupply >= derivativeParams.reservedAllowance, "NilPass:INVALID_ALLOWANCE"); require(masterMint_ != address(0), "NilPass:INVALID_MASTERMINT"); require(dao_ != address(0), "NilPass:INVALID_DAO"); n = n_; masterMint = masterMint_; derivativeParams.maxMintAllowance = derivativeParams.maxMintAllowance < MAX_MULTI_MINT_AMOUNT ? derivativeParams.maxMintAllowance : MAX_MULTI_MINT_AMOUNT; maxTokenId = derivativeParams.maxTotalSupply > MAX_N_TOKEN_ID ? derivativeParams.maxTotalSupply : MAX_N_TOKEN_ID; _setupRole(ADMIN_ROLE, msg.sender); _setupRole(DAO_ROLE, dao_); _setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE); _setRoleAdmin(DAO_ROLE, DAO_ROLE); } modifier onlyAdmin() { require(hasRole(ADMIN_ROLE, msg.sender), "Nil:ACCESS_DENIED"); _; } modifier onlyDAO() { require(hasRole(DAO_ROLE, msg.sender), "Nil:ACCESS_DENIED"); _; } /** * @notice Allow anyone to mint a token with the supply id if this pass is unrestricted. * n token holders can use this function without using the n token holders allowance, * this is useful when the allowance is fully utilized. * @param recipient Recipient of the mint * @param amount Amount of tokens to mint * @param paid Amount paid for the mint */ function mint( address recipient, uint8 amount, uint256 paid, bytes calldata data ) public virtual override; /** * @notice Allow anyone to mint multiple tokens with the provided IDs if this pass is unrestricted. * n token holders can use this function without using the n token holders allowance, * this is useful when the allowance is fully utilized. */ function mintTokenId( address, uint256[] calldata, uint256 ) public view override { require(derivativeParams.supportsTokenId, "NilPass: TOKENID_MINTING_DISABLED"); } /** * @dev Safely mints `tokenId` and transfers it to `to` */ function _safeMint(address to, uint256 tokenId) internal virtual override { require(msg.sender == masterMint, "NilPass:INVALID_MINTER"); super._safeMint(to, tokenId); emit Minted(to, tokenId); } /** * @notice Set the exclusivity flag to only allow N holders to mint * @param status Boolean to enable or disable N holder exclusivity */ function setOnlyNHolders(bool status) public onlyAdmin { derivativeParams.onlyNHolders = status; } /** * @notice Calculate the currently available number of reserved tokens for n token holders * @return Reserved mint available */ function nHoldersMintsAvailable() public view virtual returns (uint256); /** * @notice Calculate the currently available number of open mints * @return Open mint available */ function openMintsAvailable() public view virtual returns (uint256); /** * @notice Calculate the total available number of mints * @return total mint available */ function totalMintsAvailable() public view virtual override returns (uint256); function mintParameters() external view override returns (INilPass.MintParams memory) { return INilPass.MintParams({ reservedAllowance: derivativeParams.reservedAllowance, maxTotalSupply: derivativeParams.maxTotalSupply, openMintsAvailable: openMintsAvailable(), totalMintsAvailable: totalMintsAvailable(), nHoldersMintsAvailable: nHoldersMintsAvailable(), nHolderPriceInWei: getNextPriceForNHoldersInWei(1), openPriceInWei: getNextPriceForOpenMintInWei(1), totalSupply: totalSupply(), onlyNHolders: derivativeParams.onlyNHolders, maxMintAllowance: derivativeParams.maxMintAllowance, supportsTokenId: derivativeParams.supportsTokenId }); } /** * @notice Check if a token with an Id exists * @param tokenId The token Id to check for */ function tokenExists(uint256 tokenId) external view override returns (bool) { return _exists(tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable, IERC165, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } function maxTotalSupply() external view override returns (uint256) { return derivativeParams.maxTotalSupply; } function reservedAllowance() public view returns (uint16) { return derivativeParams.reservedAllowance; } function getNextPriceForNHoldersInWei(uint256) public view virtual override returns (uint256); function getNextPriceForOpenMintInWei(uint256) public view virtual override returns (uint256); function canMint(address account, bytes calldata data) public view virtual override returns (bool); } //SPDX-License-Identifier: MIT /** @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( (@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@( @@( @@( @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@ @@ @@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ @ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@( @@@ @@@ @@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */ pragma solidity 0.8.6; interface IKarmaScore { function verify( address account, uint256 score, bytes32[] calldata merkleProof ) external view returns (bool); function setMerkleRoot(bytes32 _merkleRoot) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; interface IN is IERC721Enumerable, IERC721Metadata { function getFirst(uint256 tokenId) external view returns (uint256); function getSecond(uint256 tokenId) external view returns (uint256); function getThird(uint256 tokenId) external view returns (uint256); function getFourth(uint256 tokenId) external view returns (uint256); function getFifth(uint256 tokenId) external view returns (uint256); function getSixth(uint256 tokenId) external view returns (uint256); function getSeventh(uint256 tokenId) external view returns (uint256); function getEight(uint256 tokenId) external view returns (uint256); } // SPDX-License-Identifier: MIT /** @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( (@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@( @@( @@( @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@ @@ @@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ @ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@( @@@ @@@ @@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */ pragma solidity 0.8.6; interface INOwnerResolver { function ownerOf(uint256 nid) external view returns (address); function balanceOf(address account) external view returns (uint256); function nOwned(address owner) external view returns (uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; interface INilPass is IERC721Enumerable { struct MintParams { uint256 reservedAllowance; uint256 maxTotalSupply; uint256 nHoldersMintsAvailable; uint256 openMintsAvailable; uint256 totalMintsAvailable; uint256 nHolderPriceInWei; uint256 openPriceInWei; uint256 totalSupply; uint256 maxMintAllowance; bool onlyNHolders; bool supportsTokenId; } function mint( address recipient, uint8 amount, uint256 paid, bytes calldata data ) external; function mintTokenId( address recipient, uint256[] calldata tokenIds, uint256 paid ) external; function mintWithN( address recipient, uint256[] calldata tokenIds, uint256 paid, bytes calldata data ) external; function totalMintsAvailable() external view returns (uint256); function maxTotalSupply() external view returns (uint256); function mintParameters() external view returns (MintParams memory); function tokenExists(uint256 tokenId) external view returns (bool); function nUsed(uint256 nid) external view returns (bool); function canMint(address account, bytes calldata data) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface IPricingStrategy { /** * @notice Returns the next price for an N mint */ function getNextPriceForNHoldersInWei(uint256 numberOfMints) external view returns (uint256); /** * @notice Returns the next price for an open mint */ function getNextPriceForOpenMintInWei(uint256 numberOfMints) external view returns (uint256); } //SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "../interfaces/IN.sol"; import "../interfaces/INOwnerResolver.sol"; import "../interfaces/IKarmaScore.sol"; import "./VisionsPricing.sol"; /** * @title Visio(n)s */ contract Visions is VisionsPricing { using Strings for uint256; using Counters for Counters.Counter; string public baseTokenURI; string public metadataExtension; bool public karmaSaleActive; bool public nHolderSaleActive; bool public publicSaleActive; bool public isSaleHalted; bool public airdropClaimed; uint256 public constant KARMASALE_AMOUNT = 160; uint256 public constant NHOLDERSALE_AMOUNT = 60; uint256 public constant AIRDROP_RESERVE = 50; // Nov 17 18:00 UTC uint32 karmaSaleLaunchTime = 1637172000; // Nov 17 19:00 UTC (1 hour later) uint32 nHolderSaleLaunchTime = karmaSaleLaunchTime + 3600; // Nov 17 20:00 UTC (1 hour later) uint32 publicSaleLaunchTime = nHolderSaleLaunchTime + 3600; DerivativeParameters params = DerivativeParameters(false, false, 0, 383, 4); mapping(uint256 => bool) public override nUsed; INOwnerResolver public immutable nOwnerResolver; IKarmaScore public immutable karmaScoreResolver; constructor( address _n, address masterMint, address dao, address nOwnersRegistry, address karmaScore ) VisionsPricing("Visio(n)s", "VISIONS", IN(_n), params, 77000000000000000, masterMint, dao) { // Start token IDs at 1 baseTokenURI = "https://arweave.net/hDGOAc0ku7--6GRnTfPKsM3bkvjIXLi-0MIkOFEMSJw/"; metadataExtension = ".json"; nOwnerResolver = INOwnerResolver(nOwnersRegistry); karmaScoreResolver = IKarmaScore(karmaScore); } function claimAirdrop(address[] memory recipients) public onlyAdmin { require(!airdropClaimed, "Visions: AIRDROP_ALREADY_CLAIMED"); uint256 recipientsLength = recipients.length; for (uint256 i = 0; i < 50; i++) { _mint(recipients[i % recipientsLength], i + 1); } airdropClaimed = true; } /** Updates the karma sale state for n holders */ function setKarmaSaleState(bool _preSaleActiveState) public onlyAdmin { karmaSaleActive = _preSaleActiveState; } /** Updates the n holder sale state for n holders */ function setnHolderSaleState(bool _nHolderSaleState) public onlyAdmin { nHolderSaleActive = _nHolderSaleState; } /** Updates the public sale state for non-n holders */ function setPublicSaleState(bool _publicSaleActiveState) public onlyAdmin { publicSaleActive = _publicSaleActiveState; } /** Give the ability to halt the sale if necessary due to automatic sale enablement based on time */ function setSaleHaltedState(bool _saleHaltedState) public onlyAdmin { isSaleHalted = _saleHaltedState; } /** Return true if the high karma sale is active */ function _isKarmaSaleActive() internal view returns (bool) { return ((block.timestamp >= karmaSaleLaunchTime || karmaSaleActive) && !isSaleHalted); } /** Return true if the regular karma sale is active */ function _isnHolderSaleActive() internal view returns (bool) { return ((block.timestamp >= nHolderSaleLaunchTime || nHolderSaleActive) && !isSaleHalted); } /** Return true if the public sale is active */ function _isPublicSaleActive() internal view returns (bool) { return ((block.timestamp >= publicSaleLaunchTime || publicSaleActive) && !isSaleHalted); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(super.tokenURI(tokenId), metadataExtension)); } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } function setBaseTokenURIAndExtension(string calldata baseTokenUri_, string calldata metadataExtension_) external onlyDAO { baseTokenURI = baseTokenUri_; metadataExtension = metadataExtension_; } /** Return the max number of mints per wallet (2 when presale, 4 when public) */ function _maxMintsPerWallet() internal view returns (uint256) { return _isPublicSaleActive() ? 4 : 2; } function getKarma(bytes calldata data) internal view returns (uint256) { if (data.length > 0) { (address account, uint256 karmaScore, bytes32[] memory merkleProof) = abi.decode( data, (address, uint256, bytes32[]) ); if (karmaScoreResolver.verify(account, karmaScore, merkleProof)) { return account == address(0) ? 1000 : karmaScore; } } return 1000; } /** * @notice Allow a n token holder to bulk mint tokens with id of their n tokens' id * @param recipient Recipient of the mint * @param tokenIds Ids to be minted * @param paid Amount paid for the mint * @param data data to verify Merkle proof */ function mintWithN( address recipient, uint256[] calldata tokenIds, uint256 paid, bytes calldata data ) public virtual override nonReentrant { uint256 maxTokensToMint = tokenIds.length; uint256 karma = getKarma(data); require( (_isPublicSaleActive()) || (karmaSaleActive && karma >= 1020) || (nHolderSaleActive && karma >= 1000), "Visions:SALE_NOT_OPEN_FOR_YOU" ); require(maxTokensToMint <= totalMintsAvailable(), "NilPass:MAX_ALLOCATION_REACHED"); require(balanceOf(recipient) + maxTokensToMint <= _maxMintsPerWallet(), "Visions:MINT_ABOVE_ALLOWANCE"); require(paid == getNextPriceForNHoldersInWei(maxTokensToMint), "NilPass:INVALID_PRICE"); for (uint256 i = 0; i < maxTokensToMint; i++) { require(!nUsed[tokenIds[i]], "Visions:N_ALREADY_USED"); uint256 tokenId = totalSupply() + 1; _safeMint(recipient, tokenId); nUsed[tokenIds[i]] = true; } } /** * @notice Allow anyone to mint a token with the supply id if this pass is unrestricted. * n token holders can use this function without using the n token holders allowance, * this is useful when the allowance is fully utilized. * @param recipient Recipient of the mint * @param amount Amount of tokens to mint * @param paid Amount paid for the mint */ function mint( address recipient, uint8 amount, uint256 paid, bytes calldata ) public virtual override nonReentrant { require(_isPublicSaleActive(), "Visions:USER_NOT_ALLOWED_TO_MINT"); require(amount <= totalMintsAvailable(), "NilPass:MAX_ALLOCATION_REACHED"); require(balanceOf(recipient) + amount <= _maxMintsPerWallet(), "NilPass:MINT_ABOVE_MAX_MINT_ALLOWANCE"); require(paid == getNextPriceForOpenMintInWei(amount), "NilPass:INVALID_PRICE"); for (uint256 i = 0; i < amount; i++) { uint256 tokenId = totalSupply() + 1; _safeMint(recipient, tokenId); } } /** * @notice Calculate the currently available number of reserved tokens for n token holders * @return Reserved mint available */ function nHoldersMintsAvailable() public view override returns (uint256) { return totalMintsAvailable(); } /** * @notice Calculate the currently available number of open mints * @return Open mint available */ function openMintsAvailable() public view override returns (uint256) { if (_isPublicSaleActive()) { return params.maxTotalSupply + 1 - totalSupply() + 1; } else if (_isnHolderSaleActive()) { return 0; } else { return 0; } } /** * @notice Calculate the total available number of mints * @return total mint available */ function totalMintsAvailable() public view override returns (uint256) { if (_isPublicSaleActive()) { return params.maxTotalSupply - totalSupply(); } else if (_isnHolderSaleActive()) { return KARMASALE_AMOUNT + NHOLDERSALE_AMOUNT + AIRDROP_RESERVE - totalSupply(); } else { return KARMASALE_AMOUNT + AIRDROP_RESERVE - totalSupply(); } } function canMint(address account, bytes calldata data) public view virtual override returns (bool) { bool mintsAvailable = totalMintsAvailable() > 0; bool balanceBelow = balanceOf(account) < _maxMintsPerWallet(); bool hasN = nOwnerResolver.balanceOf(account) > 0; /** * Karma Pre-sale * Karma >= 1020 * 160 pieces * 2 per wallet */ if ( _isKarmaSaleActive() && mintsAvailable && balanceBelow && hasN && getKarma(data) >= 1020 ) { return true; } /** * Karma Pre-sale * Karma >= 1000 * 60 pieces * 2 per wallet */ if ( _isnHolderSaleActive() && mintsAvailable && balanceBelow && hasN && getKarma(data) >= 1000 ) { return true; } // Public if (_isPublicSaleActive() && mintsAvailable && balanceBelow) { return true; } return false; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "../core/NilPassCore.sol"; abstract contract VisionsPricing is NilPassCore { uint256 price; constructor( string memory name, string memory symbol, IN n, DerivativeParameters memory derivativeParams, uint256 price_, address masterMint, address dao ) NilPassCore( name, symbol, n, derivativeParams, masterMint, dao ) { price = price_; } /** * @notice Returns the next price for an N mint */ function getNextPriceForNHoldersInWei(uint256 numberOfMints) public virtual override view returns (uint256) { return numberOfMints*price; } /** * @notice Returns the next price for an open mint */ function getNextPriceForOpenMintInWei(uint256 numberOfMints) public virtual override view returns (uint256) { return numberOfMints*price; } }
Calculate the currently available number of reserved tokens for n token holders return Reserved mint available/ Calculate the currently available number of open mints return Open mint available/ Calculate the total available number of mints return total mint available/
function nHoldersMintsAvailable() public view virtual returns (uint256); function openMintsAvailable() public view virtual returns (uint256); function totalMintsAvailable() public view virtual override returns (uint256); function mintParameters() external view override returns (INilPass.MintParams memory) { return INilPass.MintParams({ reservedAllowance: derivativeParams.reservedAllowance, maxTotalSupply: derivativeParams.maxTotalSupply, openMintsAvailable: openMintsAvailable(), totalMintsAvailable: totalMintsAvailable(), nHoldersMintsAvailable: nHoldersMintsAvailable(), nHolderPriceInWei: getNextPriceForNHoldersInWei(1), openPriceInWei: getNextPriceForOpenMintInWei(1), totalSupply: totalSupply(), onlyNHolders: derivativeParams.onlyNHolders, maxMintAllowance: derivativeParams.maxMintAllowance, supportsTokenId: derivativeParams.supportsTokenId }); }
5,785,004
// SPDX-License-Identifier: AGPL-3.0-only //Code from: https://github.com/m1guelpf/lil-web3/blob/main/src/LilFlashloan.sol pragma solidity ^0.8.13; import { ERC20 } from "@rari-capital/solmate/src/tokens/ERC20.sol"; /// @title Flash Borrower Interface /// @author Miguel Piedrafita /// @notice Contracts must implement this interface in order to receive flash loans from LilFlashloan interface FlashBorrower { /// @notice Flash loan callback /// @param token The ERC20 token you're receiving your flash loan on /// @param amount The amount of tokens received /// @param data Forwarded data from the flash loan request /// @dev Called after receiving the requested flash loan, should return tokens + any fees before the end of the transaction function onFlashLoan( ERC20 token, uint256 amount, bytes calldata data ) external; } /// @title lil flashloan /// @author Miguel Piedrafita /// @notice A (Proof of Concept)-level flash loan implementation /// @dev In order to keep things simple, this implementation is not compliant with EIP-3156 (the flash loan standard) contract LilFlashloan { /// ERRORS /// /// @notice Thrown when trying to update token fees or withdraw token balance without being the manager error Unauthorized(); /// @notice Thrown when trying to update token fees to an invalid percentage error InvalidPercentage(); /// @notice Thrown when the loaned tokens (and any additional fees) are not returned before the end of the transaction error TokensNotReturned(); /// EVENTS /// /// @notice Emitted when the fees for flash loaning a token have been updated /// @param token The ERC20 token to apply the specified fee to /// @param fee The new fee for this token as a percentage and multiplied by 100 to avoid decimals (for example, 10% is 10_00) event FeeUpdated(ERC20 indexed token, uint256 fee); /// @notice Emitted when the manager withdraws part of the contract's liquidity /// @param token The ERC20 token that was withdrawn /// @param amount The amount of tokens that were withdrawn event Withdrawn(ERC20 indexed token, uint256 amount); /// @notice Emitted when a flash loan is completed /// @param receiver The contract that received the funds /// @param token The ERC20 token that was loaned /// @param amount The amount of tokens that were loaned event Flashloaned( FlashBorrower indexed receiver, ERC20 indexed token, uint256 amount ); /// @notice The manager of this contract address public immutable manager; /// @notice A list of the fee percentages (multiplied by 100 to avoid decimals, for example 10% is 10_00) for each token mapping(ERC20 => uint256) public fees; /// @notice Deploys a LilFlashloan instance and sets the deployer as manager constructor() payable { manager = msg.sender; } /// @notice Request a flash loan /// @param receiver The contract that will receive the flash loan /// @param token The ERC20 token you want to borrow /// @param amount The amount of tokens you want to borrow /// @param data Data to forward to the receiver contract along with your flash loan /// @dev Make sure your contract implements the FlashBorrower interface! function execute( FlashBorrower receiver, ERC20 token, uint256 amount, bytes calldata data ) public payable { uint256 currentBalance = token.balanceOf(address(this)); emit Flashloaned(receiver, token, amount); token.transfer(address(receiver), amount); receiver.onFlashLoan(token, amount, data); if (currentBalance + getFee(token, amount) > token.balanceOf(address(this))) revert TokensNotReturned(); } /// @notice Calculate the fee owed for the loaned tokens /// @param token The ERC20 token you're receiving your loan on /// @param amount The amount of tokens you're receiving /// @return The amount of tokens you need to pay as a fee function getFee(ERC20 token, uint256 amount) public view returns (uint256) { if (fees[token] == 0) return 0; return (amount * fees[token]) / 10_000; } /// @notice Update the fee percentage for a specified ERC20 token, only available to the manager of the contract /// @param token The ERC20 token you're updating the fee percentage for /// @param fee The fee percentage for this token, multiplied by 100 (for example, 10% is 10_00) function setFees(ERC20 token, uint256 fee) public payable { if (msg.sender != manager) revert Unauthorized(); if (fee > 100_00) revert InvalidPercentage(); emit FeeUpdated(token, fee); fees[token] = fee; } /// @notice Withdraw part of the contract's liquidity, only available to the manager of the contract /// @param token The ERC20 token you want to withdraw /// @param amount The amount of tokens to withdraw function withdraw(ERC20 token, uint256 amount) public payable { if (msg.sender != manager) revert Unauthorized(); emit Withdrawn(token, amount); token.transfer(msg.sender, amount); } }
Flash Borrower Interface Miguel Piedrafita Contracts must implement this interface in order to receive flash loans from LilFlashloan
interface FlashBorrower { function onFlashLoan( ERC20 token, uint256 amount, bytes calldata data ) external; import { ERC20 } from "@rari-capital/solmate/src/tokens/ERC20.sol"; }
5,516,874
pragma solidity ^0.4.25; /** * @title SafeMath * @dev Math operations with safety checks that throw on error. */ library SafeMath { // Multiplies two numbers, throws on overflow./ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) return 0; c = a * b; assert(c / a == b); return c; } // Integer division of two numbers, truncating the quotient. function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } // Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } // Adds two numbers, throws on overflow. function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Smart-Mining 'mining-pool & token-distribution'-contract - https://smart-mining.io - mail@smart-mining.io */ contract SmartMining { using SafeMath for uint256; // ------------------------------------------------------------------------- // Variables // ------------------------------------------------------------------------- string constant public name = "smart-mining.io"; // EIP-20 string constant public symbol = "SMT"; // EIP-20 uint8 constant public decimals = 18; // EIP-20 uint256 public totalSupply = 10000; // EIP-20 struct Member { // 'Member'-struct bool crowdsalePrivateSale; // If 'true', member can participate in crowdsale before crowdsaleOpen == true uint256 crowdsaleMinPurchase; // Approved minimum crowdsale purchase in Wei uint256 balance; // Token balance in Ici, represents the percent of mining profits uint256 unpaid; // Available Wei for withdrawal, + 1 in storage for gas optimization and indicator if address is member of SmartMining contract } mapping (address => Member) public members; // All Crowdsale members as 'Member'-struct uint16 public memberCount; // Count of all SmartMining members inclusive the team-contract address[] public memberIndex; // Lookuptable of all member addresses to iterate on deposit over and assign unpaid Ether to members address public owner; // Owner of this contract address public withdrawer; // Allowed executor of automatic processed member whitdrawals (SmartMining-API) address public depositor; // Allowed depositor of mining profits bool public crowdsaleOpen; // 'true' if crowdsale is open for investors bool public crowdsaleFinished; // 'true' after crowdsaleCap was reached address public crowdsaleWallet; // Address where crowdsale funds are collected uint256 public crowdsaleCap; // Wei after crowdsale is finished uint256 public crowdsaleRaised; // Amount of wei raised in crowdsale // ------------------------------------------------------------------------- // Constructor // ------------------------------------------------------------------------- constructor (uint256 _crowdsaleCapEth, address _crowdsaleWallet, address _teamContract, uint256 _teamShare, address _owner) public { require(_crowdsaleCapEth != 0 && _crowdsaleWallet != 0x0 && _teamContract != 0x0 && _teamShare != 0 && _owner != 0x0); // Initialize contract owner and trigger 'SetOwner'-event owner = _owner; emit SetOwner(owner); // Update totalSupply with the decimal amount totalSupply = totalSupply.mul(10 ** uint256(decimals)); // Convert '_crowdsaleCapEth' from Ether to Wei crowdsaleCap = _crowdsaleCapEth.mul(10 ** 18); // Initialize withdrawer and crowdsaleWallet withdrawer = msg.sender; crowdsaleWallet = _crowdsaleWallet; // Assign totalSupply to contract address and trigger 'from 0x0'-'Transfer'-event for token creation members[address(this)].balance = totalSupply; emit Transfer(0x0, address(this), totalSupply); // Initialize team-contract members[_teamContract].unpaid = 1; memberIndex.push(_teamContract); // memberIndex[0] will become team-contract address memberCount++; // Transfer team tokens uint256 teamTokens = totalSupply.mul(_teamShare).div(100); members[address(this)].balance = members[address(this)].balance.sub(teamTokens); members[_teamContract].balance = teamTokens; emit Transfer(address(this), _teamContract, teamTokens); } // ------------------------------------------------------------------------- // Events // ------------------------------------------------------------------------- event SetOwner(address indexed owner); event SetDepositor(address indexed depositor); event SetWithdrawer(address indexed withdrawer); event SetTeamContract(address indexed teamContract); event Approve(address indexed member, uint256 crowdsaleMinPurchase, bool privateSale); event Participate(address indexed member, uint256 value, uint256 tokens); event Transfer(address indexed from, address indexed to, uint256 value); event ForwardCrowdsaleFunds(address indexed to, uint256 value); event CrowdsaleStarted(bool value); event CrowdsaleFinished(bool value); event Withdraw(address indexed member, uint256 value); event Deposit(address indexed from, uint256 value); // ------------------------------------------------------------------------- // WITHDRAWER (SmartMining-API) & OWNER ONLY external maintenance interface // ------------------------------------------------------------------------- function approve (address _beneficiary, uint256 _ethMinPurchase, bool _privateSale) external { require(msg.sender == owner || msg.sender == withdrawer, "Only SmartMining-API and contract owner allowed to approve."); require(crowdsaleFinished == false, "No new approvals after crowdsale finished."); require(_beneficiary != 0x0); if( members[_beneficiary].unpaid == 1 ) { members[_beneficiary].crowdsaleMinPurchase = _ethMinPurchase.mul(10 ** 18); members[_beneficiary].crowdsalePrivateSale = _privateSale; } else { members[_beneficiary].unpaid = 1; members[_beneficiary].crowdsaleMinPurchase = _ethMinPurchase.mul(10 ** 18); members[_beneficiary].crowdsalePrivateSale = _privateSale; memberIndex.push(_beneficiary); memberCount++; } emit Approve(_beneficiary, members[_beneficiary].crowdsaleMinPurchase, _privateSale); } // ------------------------------------------------------------------------- // OWNER ONLY external maintenance interface // ------------------------------------------------------------------------- modifier onlyOwner () { require(msg.sender == owner); _; } function setTeamContract (address _newTeamContract) external onlyOwner { require(_newTeamContract != 0x0 && _newTeamContract != memberIndex[0]); // Move team-contract member to new addresss members[_newTeamContract] = members[memberIndex[0]]; delete members[memberIndex[0]]; // Trigger 'SetTeamContract' & 'Transfer'-event for token movement emit SetTeamContract(_newTeamContract); emit Transfer(memberIndex[0], _newTeamContract, members[_newTeamContract].balance); // Update memberIndex[0] to new team-contract address memberIndex[0] = _newTeamContract; } function setOwner (address _newOwner) external onlyOwner { if( _newOwner != 0x0 ) { owner = _newOwner; } else { owner = msg.sender; } emit SetOwner(owner); } function setDepositor (address _newDepositor) external onlyOwner { depositor = _newDepositor; emit SetDepositor(_newDepositor); } function setWithdrawer (address _newWithdrawer) external onlyOwner { withdrawer = _newWithdrawer; emit SetWithdrawer(_newWithdrawer); } function startCrowdsale () external onlyOwner { require(crowdsaleFinished == false, "Crowdsale can only be started once."); crowdsaleOpen = true; emit CrowdsaleStarted(true); } function cleanupMember (uint256 _memberIndex) external onlyOwner { require(members[memberIndex[_memberIndex]].unpaid == 1, "Not a member."); require(members[memberIndex[_memberIndex]].balance == 0, "Only members without participation can be deleted."); // Delete whitelisted member which not participated in crowdsale delete members[memberIndex[_memberIndex]]; memberIndex[_memberIndex] = memberIndex[memberIndex.length-1]; memberIndex.length--; memberCount--; } // ------------------------------------------------------------------------- // Public external interface // ------------------------------------------------------------------------- function () external payable { require(crowdsaleOpen || members[msg.sender].crowdsalePrivateSale || crowdsaleFinished, "smart-mining.io crowdsale not started yet."); if(crowdsaleFinished) deposit(); if(crowdsaleOpen || members[msg.sender].crowdsalePrivateSale) participate(); } function deposit () public payable { // Pre validate deposit require(crowdsaleFinished, "Deposits only possible after crowdsale finished."); require(msg.sender == depositor, "Only 'depositor' allowed to deposit."); require(msg.value >= 10**9, "Minimum deposit 1 gwei."); // Distribute deposited Ether to all SmartMining members related to their profit-share which is representat by their ICE token balance for (uint i=0; i<memberIndex.length; i++) { members[memberIndex[i]].unpaid = // Adding current deposit to members unpaid Wei amount members[memberIndex[i]].unpaid.add( // MemberTokenBalance * DepositedWei / totalSupply = WeiAmount of member-share to be added to members unpaid holdings members[memberIndex[i]].balance.mul(msg.value).div(totalSupply) ); } // Trigger 'Deposit'-event emit Deposit(msg.sender, msg.value); } function participate () public payable { // Pre validate purchase require(members[msg.sender].unpaid == 1, "Only whitelisted members are allowed to participate!"); require(crowdsaleOpen || members[msg.sender].crowdsalePrivateSale, "Crowdsale is not open."); require(msg.value != 0, "No Ether attached to this buy order."); require(members[msg.sender].crowdsaleMinPurchase == 0 || msg.value >= members[msg.sender].crowdsaleMinPurchase, "Send at least your whitelisted crowdsaleMinPurchase Ether amount!"); // Get token count and validate that enaugh tokens are available uint256 tokens = crowdsaleCalcTokenAmount(msg.value); require(members[address(this)].balance >= tokens, "There are not enaugh Tokens left for this order."); emit Participate(msg.sender, msg.value, tokens); // Remove members crowdsaleMinPurchase for further orders members[msg.sender].crowdsaleMinPurchase = 0; // Subtract tokens from contract and add tokens to members current holdings (Transfer) members[address(this)].balance = members[address(this)].balance.sub(tokens); members[msg.sender].balance = members[msg.sender].balance.add(tokens); emit Transfer(address(this), msg.sender, tokens); // Update crowdsale states crowdsaleRaised = crowdsaleRaised.add(msg.value); if(members[address(this)].balance == 0) { // Close crowdsale if all tokens are sold out crowdsaleOpen = false; crowdsaleFinished = true; emit CrowdsaleFinished(true); } // Forward msg.value (attached Ether) to crowdsaleWallet and trigger 'ForwardCrowdsaleFunds'-event emit ForwardCrowdsaleFunds(crowdsaleWallet, msg.value); crowdsaleWallet.transfer(msg.value); } function crowdsaleCalcTokenAmount (uint256 _weiAmount) public view returns (uint256) { // Multiplied by totalSupply to avoid floats in calculation return // _weiAmount * totalSupply / crowdsaleCap * crowdsaleSupply / totalSupply _weiAmount .mul(totalSupply) .div(crowdsaleCap) .mul( totalSupply.sub(members[memberIndex[0]].balance) ) .div(totalSupply); } function withdrawOf (address _beneficiary) external { _withdraw(_beneficiary); } function withdraw () external { _withdraw(msg.sender); } function balanceOf (address _beneficiary) public view returns (uint256) { return members[_beneficiary].balance; } function unpaidOf (address _beneficiary) public view returns (uint256) { return members[_beneficiary].unpaid.sub(1); } function crowdsaleIsMemberOf (address _beneficiary) public view returns (bool) { return members[_beneficiary].unpaid >= 1; } function crowdsaleRemainingWei () public view returns (uint256) { return crowdsaleCap.sub(crowdsaleRaised); } function crowdsaleRemainingToken () public view returns (uint256) { return members[address(this)].balance; } function crowdsalePercentOfTotalSupply () public view returns (uint256) { return totalSupply.sub(members[memberIndex[0]].balance).mul(100).div(totalSupply); } // ------------------------------------------------------------------------- // Private functions, can only be called by this contract // ------------------------------------------------------------------------- function _withdraw (address _beneficiary) private { // Pre-validate withdrawal if(msg.sender != _beneficiary) { require(msg.sender == owner || msg.sender == withdrawer, "Only 'owner' and 'withdrawer' can withdraw for other members."); } require(members[_beneficiary].unpaid >= 1, "Not a member account."); require(members[_beneficiary].unpaid > 1, "No unpaid balance on account."); // Remember members unpaid amount but remove it from his contract holdings before initiating the withdrawal for security reasons uint256 unpaid = members[_beneficiary].unpaid.sub(1); members[_beneficiary].unpaid = 1; // Trigger 'Withdraw'-event emit Withdraw(_beneficiary, unpaid); // Transfer the unpaid Wei amount to member address if(_beneficiary != memberIndex[0]) { // Client withdrawals rely on the 'gas stipend' (2300 gas) which has been checked during KYC _beneficiary.transfer(unpaid); } else { // Team-contract withdrawals obtain up to 100 times more gas for further automatic processing require( _beneficiary.call.gas(230000).value(unpaid)() ); } } }
Move team-contract member to new addresss Trigger 'SetTeamContract' & 'Transfer'-event for token movement Update memberIndex[0] to new team-contract address
function setTeamContract (address _newTeamContract) external onlyOwner { require(_newTeamContract != 0x0 && _newTeamContract != memberIndex[0]); members[_newTeamContract] = members[memberIndex[0]]; delete members[memberIndex[0]]; emit SetTeamContract(_newTeamContract); emit Transfer(memberIndex[0], _newTeamContract, members[_newTeamContract].balance); memberIndex[0] = _newTeamContract; }
6,400,776
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.1.0/contracts/access/Ownable.sol"; import "github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.1.0/contracts/token/ERC20/SafeERC20.sol"; import "github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.1.0/contracts/utils/Pausable.sol"; import "github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.1.0/contracts/utils/ReentrancyGuard.sol"; import "../interfaces/ITranqToken.sol"; import "../interfaces/ITranqComptroller.sol"; import "../interfaces/IStrategyBurnVault.sol"; import "../interfaces/IUniPair.sol"; import "../interfaces/IUniRouter02.sol"; import "../interfaces/IWETH.sol"; contract StrategyTranquil is Ownable, ReentrancyGuard, Pausable { using SafeMath for uint256; using SafeERC20 for IERC20; address public constant comptrollerAddress = 0x6a82A17B48EF6be278BBC56138F35d04594587E3; address public controllerFeeAddress = 0xB989B490F9899a5AD56a4255A3C84457040B59dc; //0x54EfdaE67807cf4394020e48c7262bdbbdEbd9F2; address public withdrawFeeAddress = 0xB989B490F9899a5AD56a4255A3C84457040B59dc; address public wantAddress; address public tqTokenAddress; address public earnedAddress; address public uniRouterAddress; address public woneAddress; address public rewardAddress; address public vaultChefAddress; address public govAddress; uint256 public lastEarnBlock = block.number; uint256 public sharesTotal = 0; uint256 public controllerFee = 40; uint256 public operatorFee = 60; uint256 public rewardRate = 300; uint256 public constant feeMaxTotal = 1000; uint256 public constant feeMax = 10000; // 100 = 1% uint256 public withdrawFeeFactor = 9980; // 0.1% withdraw fee uint256 public constant withdrawFeeFactorMax = 10000; uint256 public constant withdrawFeeFactorLL = 9900; // 1% max uint256 public slippageFactor = 950; // 5% default slippage tolerance uint256 public constant slippageFactorUL = 995; /** * @dev Variables that can be changed to config profitability and risk: * {borrowRate} - At What % of our collateral do we borrow per leverage level. * {borrowDepth} - How many levels of leverage do we take. * {BORROW_RATE_MAX} - A limit on how much we can push borrow risk. * {BORROW_DEPTH_MAX} - A limit on how many steps we can leverage. */ uint256 public borrowRate; uint256 public borrowDepth = 6; uint256 public minLeverage; uint256 public BORROW_RATE_MAX; uint256 public BORROW_RATE_MAX_HARD; uint256 public BORROW_DEPTH_MAX = 8; uint256 public constant BORROW_RATE_DIVISOR = 10000; address[] public earnedToWonePath; address[] public earnedToWantPath; constructor( address _vaultChefAddress, uint256 _minLeverage, address _tqTokenAddress, address _woneAddress, address _wantAddress, address _earnedAddress, address _uniRouterAddress, address _rewardAddress, address[] memory _earnedToWonePath, address[] memory _earnedToWantPath ) public { govAddress = msg.sender; vaultChefAddress = _vaultChefAddress; minLeverage = _minLeverage; tqTokenAddress = _tqTokenAddress; woneAddress = _woneAddress; wantAddress = _wantAddress; earnedAddress = _earnedAddress; uniRouterAddress = _uniRouterAddress; rewardAddress = _rewardAddress; earnedToWonePath = _earnedToWonePath; earnedToWantPath = _earnedToWantPath; (, uint256 collateral, ) = ITranqComptroller(comptrollerAddress).markets(tqTokenAddress); // At minimum, borrow rate always 10% lower than liquidation threshold BORROW_RATE_MAX = collateral.mul(90).div(100).mul(BORROW_RATE_DIVISOR).div(1e18); // 10% BORROW_RATE_MAX_HARD = collateral.mul(99).div(100).mul(BORROW_RATE_DIVISOR).div(1e18); // 1% borrowRate = BORROW_RATE_MAX; // Enable borrowing address[] memory markets = new address[](1); markets[0] = tqTokenAddress; ITranqComptroller(comptrollerAddress).enterMarkets(markets); transferOwnership(vaultChefAddress); _resetAllowances(); } event SetSettings( uint256 _controllerFee, uint256 _operatorFee, uint256 _rewardRate, uint256 _withdrawFeeFactor, uint256 _slippageFactor, address _uniRouterAddress, address _rewardAddress, address _withdrawFeeAddress, address _controllerFeeAddress ); modifier onlyGov() { require(msg.sender == govAddress, "!gov"); _; } function deposit(address _userAddress, uint256 _wantAmt) external onlyOwner nonReentrant whenNotPaused returns (uint256) { // Call must happen before transfer uint256 wantLockedBefore = wantLockedTotal(); IERC20(wantAddress).safeTransferFrom( address(msg.sender), address(this), _wantAmt ); // Proper deposit amount for tokens with fees, or vaults with deposit fees uint256 sharesAdded = _farm(_wantAmt); if (sharesTotal > 0) { sharesAdded = sharesAdded.mul(sharesTotal).div(wantLockedBefore); } sharesTotal = sharesTotal.add(sharesAdded); return sharesAdded; } function _farm(uint256 _wantAmt) internal returns (uint256) { uint256 wantAmt = wantLockedInHere(); if (wantAmt == 0) return 0; uint256 sharesBefore = wantLockedTotal().sub(_wantAmt); _leverage(wantAmt); return wantLockedTotal().sub(sharesBefore); } function withdraw(address _userAddress, uint256 _wantAmt) external onlyOwner nonReentrant returns (uint256) { require(_wantAmt > 0, "_wantAmt is 0"); uint256 wantAmt = IERC20(wantAddress).balanceOf(address(this)); if (_wantAmt > wantAmt) { // Fully deleverage, cheap on Harmony _deleverage(); wantAmt = IERC20(wantAddress).balanceOf(address(this)); } if (_wantAmt > wantAmt) { _wantAmt = wantAmt; } if (_wantAmt > wantLockedTotal()) { _wantAmt = wantLockedTotal(); } uint256 sharesRemoved = _wantAmt.mul(sharesTotal).div(wantLockedTotal()); if (sharesRemoved > sharesTotal) { sharesRemoved = sharesTotal; } sharesTotal = sharesTotal.sub(sharesRemoved); // Withdraw fee uint256 withdrawFee = _wantAmt .mul(withdrawFeeFactorMax.sub(withdrawFeeFactor)) .div(withdrawFeeFactorMax); if (withdrawFee > 0) { IERC20(wantAddress).safeTransfer(withdrawFeeAddress, withdrawFee); } _wantAmt = _wantAmt.sub(withdrawFee); IERC20(wantAddress).safeTransfer(vaultChefAddress, _wantAmt); if (!paused()) { // Put it all back in _leverage(wantLockedInHere()); } return sharesRemoved; } function _supply(uint256 _amount) internal { ITranqToken(tqTokenAddress).mint(_amount); } function _removeSupply(uint256 _amount) internal { // Need to convert the amount into tq token amounts uint256 tqAmount; if (_amount == uint256(-1)) { tqAmount = _amount; } else { tqAmount = _amount.mul(1e18).div(ITranqToken(tqTokenAddress).exchangeRateStored()); } if (tqAmount > IERC20(tqTokenAddress).balanceOf(address(this))) { tqAmount = IERC20(tqTokenAddress).balanceOf(address(this)); } ITranqToken(tqTokenAddress).redeem(tqAmount); } function _borrow(uint256 _amount) internal { ITranqToken(tqTokenAddress).borrow(_amount); } function _repayBorrow(uint256 _amount) internal { if (_amount > debtTotal()) { _amount = debtTotal(); } if (_amount > 0) { ITranqToken(tqTokenAddress).repayBorrow(_amount); } } /** * @dev Deposits token, withdraws a percentage, and deposits again * We stop at _borrow because we need some tokens to deleverage */ function _leverage(uint256 _amount) internal { if (borrowDepth == 0) { _supply(_amount); } else if (_amount > minLeverage) { for (uint256 i = 0; i < borrowDepth; i++) { _supply(_amount); _amount = _amount.mul(borrowRate).div(BORROW_RATE_DIVISOR); _borrow(_amount); } } } /** * @dev Manually wind back one step in case contract gets stuck */ function deleverageOnce() external onlyGov { _deleverageOnce(); } function _deleverageOnce() internal { if (tqTokenTotal() <= supplyBalTargeted()) { _removeSupply(tqTokenTotal().sub(supplyBalMin())); } else { _removeSupply(tqTokenTotal().sub(supplyBalTargeted())); } _repayBorrow(wantLockedInHere()); } /** * @dev In Polygon, we can fully deleverage due to absurdly cheap fees */ function _deleverage() internal { uint256 wantBal = wantLockedInHere(); if (borrowDepth > 0) { while (wantBal < debtTotal()) { _repayBorrow(wantBal); _removeSupply(tqTokenTotal().sub(supplyBalMin())); wantBal = wantLockedInHere(); } _repayBorrow(wantBal); } _removeSupply(uint256(-1)); } function earn() external nonReentrant whenNotPaused onlyGov { uint256 preEarn = IERC20(earnedAddress).balanceOf(address(this)); // Harvest farm tokens ITranqComptroller(comptrollerAddress).claimReward(0, address(this)); // Because we keep some tokens in this contract, we have to do this if earned is the same as want uint256 earnedAmt = IERC20(earnedAddress).balanceOf(address(this)).sub(preEarn); if (earnedAmt > 0) { earnedAmt = distributeFees(earnedAmt, earnedAddress); earnedAmt = distributeOperatorFees(earnedAmt, earnedAddress); earnedAmt = distributeRewards(earnedAmt, earnedAddress); if (earnedAddress != wantAddress) { _safeSwap( earnedAmt, earnedToWantPath, address(this) ); } lastEarnBlock = block.number; _leverage(wantLockedInHere()); } } // To pay for earn function function distributeFees(uint256 _earnedAmt, address _earnedAddress) internal returns (uint256) { if (controllerFee > 0) { uint256 fee = _earnedAmt.mul(controllerFee).div(feeMax); if (_earnedAddress == woneAddress) { IWETH(woneAddress).withdraw(fee); safeTransferETH(controllerFeeAddress, fee); } else { _safeSwapWone(fee, earnedToWonePath, controllerFeeAddress); } _earnedAmt = _earnedAmt.sub(fee); } return _earnedAmt; } function distributeOperatorFees(uint256 _earnedAmt, address _earnedAddress) internal returns (uint256) { if (operatorFee > 0) { uint256 fee = _earnedAmt.mul(operatorFee).div(feeMax); if (_earnedAddress == woneAddress) { IWETH(woneAddress).withdraw(fee); safeTransferETH(withdrawFeeAddress, fee); } else { _safeSwapWone( fee, earnedToWonePath, withdrawFeeAddress ); } _earnedAmt = _earnedAmt.sub(fee); } return _earnedAmt; } function distributeRewards(uint256 _earnedAmt, address _earnedAddress) internal returns (uint256) { if (rewardRate > 0) { uint256 fee = _earnedAmt.mul(rewardRate).div(feeMax); if (_earnedAddress == woneAddress) { IStrategyBurnVault(rewardAddress).depositReward(fee); } else { uint256 woneBefore = IERC20(woneAddress).balanceOf(address(this)); _safeSwap( fee, earnedToWonePath, address(this) ); uint256 woneAfter = IERC20(woneAddress).balanceOf(address(this)).sub(woneBefore); IStrategyBurnVault(rewardAddress).depositReward(woneAfter); } _earnedAmt = _earnedAmt.sub(fee); } return _earnedAmt; } // Emergency!! function pause() external onlyGov { _pause(); } // False alarm function unpause() external onlyGov { _unpause(); _resetAllowances(); } function debtTotal() public view returns (uint256) { return ITranqToken(tqTokenAddress).borrowBalanceStored(address(this)); } function supplyBalTargeted() public view returns (uint256) { return debtTotal().mul(BORROW_RATE_DIVISOR).div(borrowRate); } function supplyBalMin() public view returns (uint256) { return debtTotal().mul(BORROW_RATE_DIVISOR).div(BORROW_RATE_MAX_HARD); } function tqTokenTotal() public view returns (uint256) { uint256 tqBalance = IERC20(tqTokenAddress).balanceOf(address(this)); return tqBalance.mul(ITranqToken(tqTokenAddress).exchangeRateStored()).div(1e18); } function wantLockedInHere() public view returns (uint256) { return IERC20(wantAddress).balanceOf(address(this)); } function wantLockedTotal() public view returns (uint256) { return wantLockedInHere() .add(tqTokenTotal()) .sub(debtTotal()); } function _resetAllowances() internal { IERC20(wantAddress).safeApprove(tqTokenAddress, uint256(0)); IERC20(wantAddress).safeIncreaseAllowance( tqTokenAddress, uint256(-1) ); IERC20(earnedAddress).safeApprove(uniRouterAddress, uint256(0)); IERC20(earnedAddress).safeIncreaseAllowance( uniRouterAddress, uint256(-1) ); IERC20(woneAddress).safeApprove(uniRouterAddress, uint256(0)); IERC20(woneAddress).safeIncreaseAllowance( uniRouterAddress, uint256(-1) ); IERC20(woneAddress).safeApprove(rewardAddress, uint256(0)); IERC20(woneAddress).safeIncreaseAllowance( rewardAddress, uint256(-1) ); } function resetAllowances() external onlyGov { _resetAllowances(); } function panic() external onlyGov { _pause(); _deleverage(); } function unpanic() external onlyGov { _unpause(); _leverage(wantLockedInHere()); } function rebalance(uint256 _borrowRate, uint256 _borrowDepth) external onlyGov { require(_borrowRate <= BORROW_RATE_MAX, "!rate"); require(_borrowRate != 0, "borrowRate is used as a divisor"); require(_borrowDepth <= BORROW_DEPTH_MAX, "!depth"); _deleverage(); borrowRate = _borrowRate; borrowDepth = _borrowDepth; _leverage(wantLockedInHere()); } function setSettings( uint256 _controllerFee, uint256 _operatorFee, uint256 _rewardRate, uint256 _withdrawFeeFactor, uint256 _slippageFactor, address _uniRouterAddress, address _rewardAddress, address _withdrawFeeAddress, address _controllerFeeAddress ) external onlyGov { require(_controllerFee.add(_operatorFee).add(_rewardRate) <= feeMaxTotal, "Max fee of 10%"); require(_withdrawFeeFactor >= withdrawFeeFactorLL, "_withdrawFeeFactor too low"); require(_withdrawFeeFactor <= withdrawFeeFactorMax, "_withdrawFeeFactor too high"); require(_slippageFactor <= slippageFactorUL, "_slippageFactor too high"); controllerFee = _controllerFee; operatorFee = _operatorFee; rewardRate = _rewardRate; withdrawFeeFactor = _withdrawFeeFactor; slippageFactor = _slippageFactor; uniRouterAddress = _uniRouterAddress; rewardAddress = _rewardAddress; withdrawFeeAddress = _withdrawFeeAddress; controllerFeeAddress = _controllerFeeAddress; emit SetSettings( _controllerFee, _operatorFee, _rewardRate, _withdrawFeeFactor, _slippageFactor, _uniRouterAddress, _rewardAddress, _withdrawFeeAddress, _controllerFeeAddress ); } function setGov(address _govAddress) external onlyGov { govAddress = _govAddress; } function _safeSwap( uint256 _amountIn, address[] memory _path, address _to ) internal { uint256[] memory amounts = IUniRouter02(uniRouterAddress).getAmountsOut(_amountIn, _path); uint256 amountOut = amounts[amounts.length.sub(1)]; IUniRouter02(uniRouterAddress).swapExactTokensForTokens( _amountIn, amountOut.mul(slippageFactor).div(1000), _path, _to, now.add(600) ); } function _safeSwapWone( uint256 _amountIn, address[] memory _path, address _to ) internal { uint256[] memory amounts = IUniRouter02(uniRouterAddress).getAmountsOut(_amountIn, _path); uint256 amountOut = amounts[amounts.length.sub(1)]; IUniRouter02(uniRouterAddress).swapExactTokensForETH( _amountIn, amountOut.mul(slippageFactor).div(1000), _path, _to, now.add(600) ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } // tg @macatkevin receive() external payable {} }
Fully deleverage, cheap on Harmony Put it all back in
function withdraw(address _userAddress, uint256 _wantAmt) external onlyOwner nonReentrant returns (uint256) { require(_wantAmt > 0, "_wantAmt is 0"); uint256 wantAmt = IERC20(wantAddress).balanceOf(address(this)); if (_wantAmt > wantAmt) { _deleverage(); wantAmt = IERC20(wantAddress).balanceOf(address(this)); } if (_wantAmt > wantAmt) { _wantAmt = wantAmt; } if (_wantAmt > wantLockedTotal()) { _wantAmt = wantLockedTotal(); } uint256 sharesRemoved = _wantAmt.mul(sharesTotal).div(wantLockedTotal()); if (sharesRemoved > sharesTotal) { sharesRemoved = sharesTotal; } sharesTotal = sharesTotal.sub(sharesRemoved); .mul(withdrawFeeFactorMax.sub(withdrawFeeFactor)) .div(withdrawFeeFactorMax); if (withdrawFee > 0) { IERC20(wantAddress).safeTransfer(withdrawFeeAddress, withdrawFee); } _wantAmt = _wantAmt.sub(withdrawFee); IERC20(wantAddress).safeTransfer(vaultChefAddress, _wantAmt); if (!paused()) { _leverage(wantLockedInHere()); } return sharesRemoved; }
6,419,554
./full_match/11155111/0xc9241Cf4cD7d9569cA044d8202EF1080405Bc6C9/sources/src/DripsHub.sol
Verifies that the balance of drips or splits can be increased by the given amount. The sum of dripping and splitting balances is checked to not exceed `MAX_TOTAL_BALANCE` or the amount of tokens held by the DripsHub. erc20 The used ERC-20 token. amt The amount to increase the drips or splits balance by.
function _verifyBalanceIncrease(IERC20 erc20, uint128 amt) internal view { (uint256 dripsBalance, uint128 splitsBalance) = balances(erc20); uint256 newTotalBalance = dripsBalance + splitsBalance + amt; require(newTotalBalance <= MAX_TOTAL_BALANCE, "Total balance too high"); require(newTotalBalance <= _tokenBalance(erc20), "Token balance too low"); }
3,827,080
./partial_match/1/0xA9b74787E2C0d70042e6C06793654957568794D0/sources/BarbieToken.sol
once active, can never be disable off
function tradeStart(address _pair) external onlyOwner { uniswapV2Pair = _pair; isTradingStart = true; enabledSwap = true; tradeEnableFrom = block.number; routerAddress = developmentWalletAddr; _automatedMarketMakers[address(uniswapV2Pair)] = true; _isExcludedMaxTransactionAmount[address(uniswapV2Pair)] = true; _isExcludedmaxAmount[address(uniswapV2Pair)] = true; }
16,023,685
./full_match/1/0xDB3abFA4209621135A924FC2cf190052c39b157D/sources/contracts/SkillTree.sol
get user by address
function get_user(address _address) public view returns (User memory) { return(Users[_address]); }
3,168,146
/** *Submitted for verification at Etherscan.io on 2021-03-06 */ pragma solidity ^0.6.6; // SPDX-License-Identifier: MIT /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT /** * @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 interface IConverter { function convert(address) external returns (uint256); } // SPDX-License-Identifier: MIT interface IOneSplitAudit { function swap( address fromToken, address destToken, uint256 amount, uint256 minReturn, uint256[] calldata distribution, uint256 flags ) external payable returns (uint256 returnAmount); function getExpectedReturn( address fromToken, address destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) external view returns (uint256 returnAmount, uint256[] memory distribution); } // SPDX-License-Identifier: MIT interface IStrategy { function want() external view returns (address); function deposit() external; // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdraw(address) external; // Controller | Vault role - withdraw should always return to Vault function withdraw(uint256) external; // Controller | Vault role - withdraw should always return to Vault function withdrawAll() external returns (uint256); function balanceOf() external view returns (uint256); function withdrawalFee() external view returns (uint256); } // SPDX-License-Identifier: MIT contract Controller2 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public governance; address public strategist; address public onesplit; address public rewards; mapping(address => address) public vaults; mapping(address => address) public strategies; mapping(address => mapping(address => address)) public converters; mapping(address => mapping(address => bool)) public approvedStrategies; uint256 public split = 500; uint256 public constant max = 10000; constructor(address _rewards) public { governance = msg.sender; strategist = msg.sender; onesplit = address(0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e); rewards = _rewards; } function setRewards(address _rewards) public { require(msg.sender == governance, "!governance"); rewards = _rewards; } function setStrategist(address _strategist) public { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setSplit(uint256 _split) public { require(msg.sender == governance, "!governance"); split = _split; } function setOneSplit(address _onesplit) public { require(msg.sender == governance, "!governance"); onesplit = _onesplit; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setVault(address _token, address _vault) public { require(msg.sender == strategist || msg.sender == governance, "!strategist"); require(vaults[_token] == address(0), "vault"); vaults[_token] = _vault; } function approveStrategy(address _token, address _strategy) public { require(msg.sender == governance, "!governance"); approvedStrategies[_token][_strategy] = true; } function revokeStrategy(address _token, address _strategy) public { require(msg.sender == governance, "!governance"); approvedStrategies[_token][_strategy] = false; } function setConverter( address _input, address _output, address _converter ) public { require(msg.sender == strategist || msg.sender == governance, "!strategist"); converters[_input][_output] = _converter; } function setStrategy( address _token, address _strategy, bool withdrawFlag ) public { require(msg.sender == strategist || msg.sender == governance, "!strategist"); require(approvedStrategies[_token][_strategy] == true, "!approved"); if (withdrawFlag) { address _current = strategies[_token]; if (_current != address(0)) { IStrategy(_current).withdrawAll(); } } strategies[_token] = _strategy; } function earn(address _token, uint256 _amount) public { address _strategy = strategies[_token]; address _want = IStrategy(_strategy).want(); if (_want != _token) { address converter = converters[_token][_want]; IERC20(_token).safeTransfer(converter, _amount); _amount = IConverter(converter).convert(_strategy); IERC20(_want).safeTransfer(_strategy, _amount); } else { IERC20(_token).safeTransfer(_strategy, _amount); } IStrategy(_strategy).deposit(); } function balanceOf(address _token) external view returns (uint256) { return IStrategy(strategies[_token]).balanceOf(); } function withdrawAll(address _token) public { require(msg.sender == strategist || msg.sender == governance, "!strategist"); IStrategy(strategies[_token]).withdrawAll(); } function inCaseTokensGetStuck(address _token, uint256 _amount) public { require(msg.sender == strategist || msg.sender == governance, "!governance"); IERC20(_token).safeTransfer(msg.sender, _amount); } function inCaseStrategyTokenGetStuck(address _strategy, address _token) public { require(msg.sender == strategist || msg.sender == governance, "!governance"); IStrategy(_strategy).withdraw(_token); } function getExpectedReturn( address _strategy, address _token, uint256 parts ) public view returns (uint256 expected) { uint256 _balance = IERC20(_token).balanceOf(_strategy); address _want = IStrategy(_strategy).want(); (expected, ) = IOneSplitAudit(onesplit).getExpectedReturn(_token, _want, _balance, parts, 0); } // Only allows to withdraw non-core strategy tokens ~ this is over and above normal yield function yearn( address _strategy, address _token, uint256 parts ) public { require(msg.sender == strategist || msg.sender == governance, "!governance"); // This contract should never have value in it, but just incase since this is a public call uint256 _before = IERC20(_token).balanceOf(address(this)); IStrategy(_strategy).withdraw(_token); uint256 _after = IERC20(_token).balanceOf(address(this)); if (_after > _before) { uint256 _amount = _after.sub(_before); address _want = IStrategy(_strategy).want(); uint256[] memory _distribution; uint256 _expected; _before = IERC20(_want).balanceOf(address(this)); IERC20(_token).safeApprove(onesplit, 0); IERC20(_token).safeApprove(onesplit, _amount); (_expected, _distribution) = IOneSplitAudit(onesplit).getExpectedReturn(_token, _want, _amount, parts, 0); IOneSplitAudit(onesplit).swap(_token, _want, _amount, _expected, _distribution, 0); _after = IERC20(_want).balanceOf(address(this)); if (_after > _before) { _amount = _after.sub(_before); uint256 _reward = _amount.mul(split).div(max); earn(_want, _amount.sub(_reward)); IERC20(_want).safeTransfer(rewards, _reward); } } } function withdraw(address _token, uint256 _amount) public { require(msg.sender == vaults[_token], "!vault"); IStrategy(strategies[_token]).withdraw(_amount); } }
SPDX-License-Identifier: MIT
interface IOneSplitAudit { function swap( address fromToken, address destToken, uint256 amount, uint256 minReturn, uint256[] calldata distribution, uint256 flags ) external payable returns (uint256 returnAmount); function getExpectedReturn( address fromToken, address destToken, uint256 amount, uint256 parts, ) external view returns (uint256 returnAmount, uint256[] memory distribution); }
7,955,352
pragma solidity ^0.4.15; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title SimpleToken * @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator. * Note they can later distribute these tokens as they wish using `transfer` and other * `StandardToken` functions. */ contract OpportyToken is StandardToken { string public constant name = "OpportyToken"; string public constant symbol = "OPP"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals)); /** * @dev Contructor that gives msg.sender all of existing tokens. */ function OpportyToken() public { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } } contract Escrow is Ownable { // status of the project enum Status { NEW, PAYED, WORKDONE, CLAIMED, CLOSED } // status of the current work enum WorkStatus {NEW, STARTED, FULLYDONE, PARTIALLYDONE } // token address address tokenHolder = 0x08990456DC3020C93593DF3CaE79E27935dd69b9; // execute funciton only by token holders modifier onlyShareholders { require (token.balanceOf(msg.sender) > 0); _; } // transaction only after deadline modifier afterDeadline(uint idProject) { Project storage project = projects[idProject]; require (now > project.deadline) ; _; } // transaction can be executed by project client modifier onlyClient(uint idProject) { Project storage project = projects[idProject]; require (project.client == msg.sender); _; } // transaction can be executed only by performer modifier onlyPerformer(uint idProject) { Project storage project = projects[idProject]; require (project.performer == msg.sender); _; } // project in Opporty system // TODO: decrease size of struct struct Project { uint id; string name; address client; address performer; uint deadline; uint sum; Status status; string report; WorkStatus wstatus; uint votingDeadline; uint numberOfVotes; uint totalVotesNeeded; bool withdrawed; Vote[] votes; mapping (address => bool) voted; } // one vote - one element of struct struct Vote { bool inSupport; address voter; } // event - project was added event ProjectAdded(uint idExternal, uint projectID, address performer, string name, uint sum); // event - fund was transferred event FundTransfered(address recipient, uint amount); // work was done event WorkDone(uint projectId, address performer, WorkStatus status, string link); // already voted event Voted(uint projectID, bool position, address voter); // status of project changed event ChangedProjectStatus(uint projectID, Status status); event log(string val); event loga(address addr); event logi(uint i); // token for payments OpportyToken token; // all projects Project[] projects; // number or projects uint public numProjects; function Escrow(address tokenUsed) public { token = OpportyToken(tokenUsed); } function getNumberOfProjects() public constant returns(uint) { return numProjects; } // Add a project to blockchain // idExternal - id in opporty // name // performer // duration // sum function addProject(uint idExternal, string name, address performer, uint durationInMinutes, uint sum) public returns (uint projectId) { projectId = projects.length++; Project storage p = projects[projectId]; p.id = idExternal; p.name = name; p.client = msg.sender; p.performer = performer; p.deadline = now + durationInMinutes * 1 minutes; p.sum = sum * 1 ether; p.status = Status.NEW; ProjectAdded(idExternal, projectId, performer, name, sum); return projectId; } function getProjectReport(uint idProject) public constant returns (string t) { Project storage p = projects[idProject]; return p.report; } function getJudgeVoted(uint idProject, address judge) public constant returns (bool voted) { Project storage p = projects[idProject]; if (p.voted[judge]) return true; else return false; } // get status of project function getStatus(uint idProject) public constant returns (uint t) { Project storage p = projects[idProject]; return uint(p.status); } // is deadline function isDeadline(uint idProject) public constant returns (bool f) { Project storage p = projects[idProject]; if (now >= p.deadline) { return true; } else { return false; } } // pay for project by client function payFor(uint idProject) payable onlyClient(idProject) public returns (bool) { Project storage project = projects[idProject]; uint price = project.sum; require (project.status == Status.NEW); if (msg.value >= price) { project.status = Status.PAYED; FundTransfered(this, msg.value); ChangedProjectStatus(idProject, Status.PAYED); return true; } else { revert(); } } // pay by project in tokens function payByTokens(uint idProject) onlyClient(idProject) onlyShareholders public { Project storage project = projects[idProject]; require (project.sum <= token.balanceOf(project.client)); require (token.transferFrom(project.client, tokenHolder, project.sum)); ChangedProjectStatus(idProject, Status.PAYED); } // change status of project - done // and provide report function workDone(uint idProject, string report, WorkStatus status) onlyPerformer(idProject) afterDeadline(idProject) public { Project storage project = projects[idProject]; require (project.status == Status.PAYED); project.status = Status.WORKDONE; project.report = report; project.wstatus = status; WorkDone(idProject, project.performer, project.wstatus, project.report); ChangedProjectStatus(idProject, Status.WORKDONE); } // work is done - execured by client function acceptWork(uint idProject) onlyClient(idProject) afterDeadline(idProject) public { Project storage project = projects[idProject]; require (project.status == Status.WORKDONE); project.status = Status.CLOSED; ChangedProjectStatus(idProject, Status.CLOSED); } // claim - project was undone (?) // numberOfVoters // debatePeriod - time for voting function claimWork(uint idProject, uint numberOfVoters, uint debatePeriod) afterDeadline(idProject) public { Project storage project = projects[idProject]; require (project.status == Status.WORKDONE); project.status = Status.CLAIMED; project.votingDeadline = now + debatePeriod * 1 minutes; project.totalVotesNeeded = numberOfVoters; ChangedProjectStatus(idProject, Status.CLAIMED); } // voting process function vote(uint idProject, bool supportsProject) public returns (uint voteID) { Project storage p = projects[idProject]; require(p.voted[msg.sender] != true); require(p.status == Status.CLAIMED); require(p.numberOfVotes < p.totalVotesNeeded); require(now >= p.votingDeadline ); voteID = p.votes.length++; p.votes[voteID] = Vote({inSupport: supportsProject, voter: msg.sender}); p.voted[msg.sender] = true; p.numberOfVotes = voteID + 1; Voted(idProject, supportsProject, msg.sender); return voteID; } // safeWithdrawal - get money by performer / return money for client function safeWithdrawal(uint idProject) afterDeadline(idProject) public { Project storage p = projects[idProject]; // if status closed and was not withdrawed require(p.status == Status.CLAIMED || p.status == Status.CLOSED && !p.withdrawed); // if project closed if (p.status == Status.CLOSED) { if (msg.sender == p.performer && !p.withdrawed && msg.sender.send(p.sum) ) { FundTransfered(msg.sender, p.sum); p.withdrawed = true; } else { revert(); } } else { // claim uint yea = 0; uint nay = 0; // calculating votes for (uint i = 0; i < p.votes.length; ++i) { Vote storage v = p.votes[i]; if (v.inSupport) { yea += 1; } else { nay += 1; } } // если уже время голосования закончилось if (now >= p.votingDeadline) { if (msg.sender == p.performer && p.numberOfVotes >= p.totalVotesNeeded ) { if (yea>nay && !p.withdrawed && msg.sender.send(p.sum)) { FundTransfered(msg.sender, p.sum); p.withdrawed = true; p.status = Status.CLOSED; ChangedProjectStatus(idProject, Status.CLOSED); } } if (msg.sender == p.client) { if (nay>=yea && !p.withdrawed && msg.sender.send(p.sum)) { FundTransfered(msg.sender, p.sum); p.withdrawed = true; p.status = Status.CLOSED; // меняем статус проекта ChangedProjectStatus(idProject, Status.CLOSED); } } } else { revert(); } } } // get tokens function safeWithdrawalTokens(uint idProject) afterDeadline(idProject) public { Project storage p = projects[idProject]; require(p.status == Status.CLAIMED || p.status == Status.CLOSED && !p.withdrawed); if (p.status == Status.CLOSED) { if (msg.sender == p.performer && token.transfer(p.performer, p.sum) && !p.withdrawed) { FundTransfered(msg.sender, p.sum); p.withdrawed = true; } else { revert(); } } } }
work is done - execured by client
function acceptWork(uint idProject) onlyClient(idProject) afterDeadline(idProject) public { Project storage project = projects[idProject]; require (project.status == Status.WORKDONE); project.status = Status.CLOSED; ChangedProjectStatus(idProject, Status.CLOSED); }
1,160,986
./full_match/1/0x1E71f41DDA7db34D0423d26CD202a7A8f0c796E5/sources/browser/liquidation.sol
will pause the system pause the system pause satellitepool
function pause(address[] memory pools) public onlyPauser { if (msg.sender == coreDev) { shouldPauseDev = true; shouldPauseTrustee = true; } if (shouldPauseDev && shouldPauseTrustee) { systemPause = true; boringDAO().pause(); for(uint i=0; i < pools.length; i++) { if(isSatellitePool[pools[i]] == true) { IPause(pools[i]).pause(); } } } }
9,741,099
./full_match/5/0xe50Dd55273050b49415D69a29Fe691dbe3806aA7/sources/project_/contracts/StandardController.sol
Unpause the function protected by Pausable modifier./
function unpause() public onlyOwner { _unpause(); }
1,928,310
// File contracts/interfaces/IERC20Expanded.sol // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; interface IERC20Expanded { function symbol() external view returns (string memory); function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); 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 contracts/libraries/SafeMath.sol pragma solidity ^0.6.12; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; 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) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; require(c >= _a); return c; } } // File contracts/interfaces/IStakingPool.sol pragma solidity ^0.6.12; interface IStakingPool { function computeUserWeight(address user) external view returns (uint256); } // File contracts/TokenPool.sol pragma solidity ^0.6.12; contract TokenPool { // Using SafeMath library for uint256 operations using SafeMath for *; // Contract state in terms of deposit enum ContractState {PENDING_SUPPLY, TOKENS_SUPPLIED, SALE_ENDED} // State in which is contract ContractState state; // Participation structure struct Participation { uint amountBNBPaid; uint amountOfTokensReceived; uint timestamp; bool isWithdrawn; } // List all participation's Participation [] participations; // Mapping if user has participated in private/public sale or not mapping(address => bool) isParticipated; // Mapping user to his participation ids; mapping(address => uint256) userToHisParticipationId; // Total amount of tokens sold uint totalTokensSold; // Total BNB raised uint totalBNBRaised; // Public sale max participation uint publicMaxParticipation; // Timestamps for private sale uint256 salePrivateStartTime; uint256 salePrivateEndTime; // Timestamp for public sale uint256 salePublicStartTime; uint256 salePublicEndTime; // Token price is quoted against BNB token and represents how much 1 token is worth BNB // So, given example: If user wants to set token price to be 0.5 BNB tokens, the token price value will be // 0.5 ** 10**18 uint256 tokenPrice; // Allocation for private sell uint256 privateSellAllocation; // Amount sold during private sell uint256 privateSellTokensSold; // Amount of tokens user wants to sell uint256 amountOfTokensToSell; // Time at which tokens are getting unlocked uint256 tokensUnlockingTime; // Token which is being sold IERC20Expanded tokenSold; // Wallet address of project owner address projectOwnerWallet; // Address of staking pool contract IStakingPool stakingPool; // Modifier checking if private sale is active modifier isPrivateSaleActive { require(block.timestamp >= salePrivateStartTime && block.timestamp <= salePrivateEndTime); require(state == ContractState.TOKENS_SUPPLIED); _; } // Modifier checking if public sale is active modifier isPublicSaleActive { require(block.timestamp >= salePublicStartTime && block.timestamp <= salePublicEndTime); require(state == ContractState.TOKENS_SUPPLIED); _; } // Constructor to create contract constructor( uint256 _salePrivateStartTime, uint256 _salePrivateEndTime, uint256 _salePublicStartTime, uint256 _salePublicEndTime, uint256 _tokensUnlockingTime, address _tokenAddress, uint256 _tokenPrice, uint256 _amountOfTokensToSell, address _projectOwnerWallet, address _stakingPool ) public { // Requirements for contract creation require(_tokenPrice > 0 , "Token price can not be 0"); require(_projectOwnerWallet != address(0x0)); // Private sale timestamps salePrivateStartTime = _salePrivateStartTime; salePrivateEndTime = _salePrivateEndTime; // Public sale timestamps salePublicStartTime = _salePublicStartTime; salePublicEndTime = _salePublicEndTime; // Set time after which tokens can be withdrawn tokensUnlockingTime = _tokensUnlockingTime; // Token price and amount of tokens selling tokenSold = IERC20Expanded(_tokenAddress); // 1 BNB publicMaxParticipation = 10 ** 18; // Allow selling only tokens with 18 decimals require(tokenSold.decimals() == 18); tokenPrice = _tokenPrice; amountOfTokensToSell = _amountOfTokensToSell; // Wallet of project owner projectOwnerWallet = _projectOwnerWallet; // Set staking pool address inside contract stakingPool = IStakingPool(_stakingPool); // Set initial state to pending supply state = ContractState.PENDING_SUPPLY; } // Function for project owner or anyone who's in charge to deposit initial amount of tokens function depositTokensToSell() public { // This can be called only once, while contract is in the state of PENDING_SUPPLY require(state == ContractState.PENDING_SUPPLY, "Fund Contract : Must be in PENDING_SUPPLY state"); // Make sure all tokens to be sold are deposited to the contract tokenSold.transferFrom(msg.sender, address(this), amountOfTokensToSell); // Compute private sell allocation privateSellAllocation = amountOfTokensToSell.mul(94).div(100); // Mark contract state to SUPPLIED state = ContractState.TOKENS_SUPPLIED; } // Function to participate in private sale function participatePrivateSale() public payable isPrivateSaleActive { // Require that user can participate only once require(isParticipated[msg.sender] == false, "User already participated"); // amountOfTokens = purchaseAmount / tokenPrice uint256 amountOfTokensBuying = (msg.value).mul(10**18).div(tokenPrice); // Compute maximal participation for user uint256 maximalParticipationForUser = computeMaxPrivateParticipationAmount(msg.sender); // Require user wants to participate with amount his staking weight allows him require(amountOfTokensBuying <= maximalParticipationForUser, "Overflow -> Weighting score"); // Require that there's enough tokens require( privateSellTokensSold.add(amountOfTokensBuying) <= privateSellAllocation, "Overflow -> Buying more than available" ); // Account sold tokens privateSellTokensSold = privateSellTokensSold.add(amountOfTokensBuying); // Internal sell tokens function sellTokens(msg.value, amountOfTokensBuying); // Mark that user have participated isParticipated[msg.sender] = true; } // Function to participate in public sale function participatePublicSale() public payable isPublicSaleActive { require(publicMaxParticipation >= msg.value, "Contribution amount greater than max participation."); // amountOfTokens = purchaseAmount / tokenPrice uint amountOfTokensBuying = (msg.value).mul(10**18).div(tokenPrice); // Require that there's enough tokens require(amountOfTokensToSell.sub(totalTokensSold) > amountOfTokensBuying); // Internal sell tokens function sellTokens(msg.value, amountOfTokensBuying); // Mark that user have participated isParticipated[msg.sender] = true; } // Internal function to handle selling tokens per given price function sellTokens( uint participationAmount, uint amountOfTokensBuying ) internal { // Add amount of tokens user is buying to total sold amount totalTokensSold = totalTokensSold.add(amountOfTokensBuying); // Add amount of BNBs raised totalBNBRaised = totalBNBRaised.add(participationAmount); // Compute participation id uint participationId = participations.length; // Create participation object Participation memory p = Participation({ amountBNBPaid: participationAmount, amountOfTokensReceived: amountOfTokensBuying, timestamp: block.timestamp, isWithdrawn: false }); // Push participation to array of all participations participations.push(p); // Map user to his participation ids userToHisParticipationId[msg.sender] = participationId; } // Internal function to handle safe transfer function safeTransferBNB( address to, uint value ) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: BNB_TRANSFER_FAILED'); } function withdrawEarningsAndLeftover() public { require(msg.sender == projectOwnerWallet); // Make sure both private and public sale expired require(block.timestamp >= salePublicEndTime && block.timestamp >= salePrivateEndTime); // Earnings amount of the owner uint totalEarnings = address(this).balance; // Amount of tokens which are not sold uint leftover = amountOfTokensToSell.sub(totalTokensSold); safeTransferBNB(msg.sender, totalEarnings); if(leftover > 0) { tokenSold.transfer(msg.sender, leftover); } // Set state of the contract to ENDED state = ContractState.SALE_ENDED; } // Function where user can withdraw tokens he has bought function withdrawTokens() public { require(isParticipated[msg.sender] == true, "User is not participant."); require(now > tokensUnlockingTime, "Tokens are not unlocked yet."); // Get user participation id uint participationId = userToHisParticipationId[msg.sender]; // Same unit can't be withdrawn twice Participation storage p = participations[participationId]; require(p.isWithdrawn == false, "Can not withdraw same thing twice."); // Transfer bought tokens to address tokenSold.transfer(msg.sender, p.amountOfTokensReceived); // Mark participation as withdrawn p.isWithdrawn = true; } // Function to check user participation ids function getUserParticipationId( address user ) public view returns (uint256) { return userToHisParticipationId[user]; } // Function to return total number of participations function getNumberOfParticipations() public view returns (uint256) { return participations.length; } // Function to fetch high level overview of pool sale stats function getSaleStats() public view returns (uint256,uint256) { return (totalTokensSold, totalBNBRaised); } // Function to return when purchased tokens can be withdrawn function getTokensUnlockingTime() public view returns (uint) { return tokensUnlockingTime; } // Function to compute maximal private sell participation amount based on the weighting score function computeMaxPrivateParticipationAmount( address user ) public view returns (uint256) { if(isParticipated[user] == true) { // User can participate only once return 0; } uint256 userWeight = stakingPool.computeUserWeight(user); // Compute the maximum user can participate in the private sell uint256 userMaxParticipation = userWeight.mul(privateSellAllocation).div(10**18); // Add 10% on top uint256 maxParticipation = userMaxParticipation.mul(110).div(100); // Compute how much tokens are left in private sell allocation uint256 leftoverInPrivate = privateSellAllocation.sub(privateSellTokensSold); // Return return maxParticipation > leftoverInPrivate ? leftoverInPrivate : maxParticipation; } // Function to check in which state is the contract at the moment function getInventoryState() public view returns (string memory) { if(state == ContractState.PENDING_SUPPLY) { return "PENDING_SUPPLY"; } return "TOKENS_SUPPLIED"; } // Function to get pool state depending on time and allocation function getPoolState() public view returns (string memory) { if(state == ContractState.PENDING_SUPPLY && now < salePublicEndTime) { return "UPCOMING"; } if(now < salePrivateStartTime) { return "UPCOMING"; } if(totalTokensSold >= amountOfTokensToSell.mul(999).div(1000)) { return "FINISHED"; } else if (now < salePublicEndTime) { return "ONGOING"; } return "FINISHED"; } function getPoolInformation() public view returns ( string memory, uint256, uint256, uint256, uint256, uint256, uint256, uint256, bool, // Is private sell active bool // is public sell active ) { string memory tokenSymbol = tokenSold.symbol(); bool isPrivateSellActive; bool isPublicSellActive; if(block.timestamp >= salePrivateStartTime && block.timestamp <= salePrivateEndTime) { isPrivateSellActive = true; } else if(block.timestamp >= salePublicStartTime && block.timestamp <= salePublicEndTime) { isPublicSellActive = true; } return ( tokenSymbol, totalTokensSold, amountOfTokensToSell, salePrivateStartTime, salePrivateEndTime, salePublicStartTime, salePublicEndTime, tokenPrice, isPrivateSellActive, isPublicSellActive ); } // Function to get participation for specific user. function getParticipation( address user ) public view returns (uint,uint,uint,uint,bool) { if(isParticipated[user] == false) { return (0,0,0,0,false); } Participation memory p = participations[userToHisParticipationId[user]]; return ( p.amountBNBPaid, p.amountOfTokensReceived, p.timestamp, tokensUnlockingTime, p.isWithdrawn ); } } // File contracts/KPADTokenPool.sol pragma solidity ^0.6.12; contract SM2LPPool { // Using SafeMath library for uint256 operations using SafeMath for *; // Contract state in terms of deposit enum ContractState {PENDING_SUPPLY, TOKENS_SUPPLIED, SALE_ENDED} // State in which is contract ContractState state; // Participation structure struct Participation { uint amountBNBPaid; uint amountOfTokensReceived; uint timestamp; bool isWithdrawn; } address [] whitelistedParticipants; mapping(address => bool) isParticipantWhitelisted; // List all participation's Participation [] participations; // Mapping if user has participated in private/public sale or not mapping(address => bool) isParticipated; // Mapping user to his participation ids; mapping(address => uint256) userToHisParticipationId; // Total amount of tokens sold uint totalTokensSold; // Total BNB raised uint totalBNBRaised; // Public sale max participation uint publicMaxParticipation; // Timestamps for private sale uint256 salePrivateStartTime; uint256 salePrivateEndTime; // Timestamp for public sale uint256 salePublicStartTime; uint256 salePublicEndTime; // Token price is quoted against BNB token and represents how much 1 token is worth BNB // So, given example: If user wants to set token price to be 0.5 BNB tokens, the token price value will be // 0.5 ** 10**18 uint256 tokenPrice; // Allocation for private sell uint256 privateSellAllocation; // Amount sold during private sell uint256 privateSellTokensSold; // Amount of tokens user wants to sell uint256 amountOfTokensToSell; // Time at which tokens are getting unlocked uint256 tokensUnlockingTime; // Token which is being sold IERC20Expanded tokenSold; // Wallet address of project owner address projectOwnerWallet; // Address of staking pool contract IStakingPool stakingPool; // Modifier checking if private sale is active modifier isPrivateSaleActive { require(block.timestamp >= salePrivateStartTime && block.timestamp <= salePrivateEndTime); require(state == ContractState.TOKENS_SUPPLIED); _; } // Modifier checking if public sale is active modifier isPublicSaleActive { require(block.timestamp >= salePublicStartTime && block.timestamp <= salePublicEndTime); require(state == ContractState.TOKENS_SUPPLIED); _; } // Constructor to create contract constructor( uint256 _salePrivateStartTime, uint256 _salePrivateEndTime, uint256 _salePublicStartTime, uint256 _salePublicEndTime, uint256 _tokensUnlockingTime, address _tokenAddress, uint256 _tokenPrice, uint256 _amountOfTokensToSell, address _projectOwnerWallet, address _stakingPool ) public { // Requirements for contract creation require(_tokenPrice > 0 , "Token price can not be 0"); require(_projectOwnerWallet != address(0x0)); // Private sale timestamps salePrivateStartTime = _salePrivateStartTime; salePrivateEndTime = _salePrivateEndTime; // Public sale timestamps salePublicStartTime = _salePublicStartTime; salePublicEndTime = _salePublicEndTime; // Set time after which tokens can be withdrawn tokensUnlockingTime = _tokensUnlockingTime; // Token price and amount of tokens selling tokenSold = IERC20Expanded(_tokenAddress); // 0.5 BNB publicMaxParticipation = (10 ** 18) / 2; // Allow selling only tokens with 18 decimals require(tokenSold.decimals() == 18); tokenPrice = _tokenPrice; amountOfTokensToSell = _amountOfTokensToSell; // Wallet of project owner projectOwnerWallet = _projectOwnerWallet; // Set staking pool address inside contract stakingPool = IStakingPool(_stakingPool); // Set initial state to pending supply state = ContractState.PENDING_SUPPLY; } // Function for project owner or anyone who's in charge to deposit initial amount of tokens function depositTokensToSell() public { // This can be called only once, while contract is in the state of PENDING_SUPPLY require(state == ContractState.PENDING_SUPPLY, "Fund Contract : Must be in PENDING_SUPPLY state"); // Make sure all tokens to be sold are deposited to the contract tokenSold.transferFrom(msg.sender, address(this), amountOfTokensToSell); // Compute private sell allocation privateSellAllocation = amountOfTokensToSell.mul(94).div(100); // Mark contract state to SUPPLIED state = ContractState.TOKENS_SUPPLIED; } // Function to participate in private sale function participatePrivateSale() public payable isPrivateSaleActive { require(isParticipantWhitelisted[msg.sender] == true,"Not whitelisted."); // Require that user can participate only once require(isParticipated[msg.sender] == false, "User already participated"); // amountOfTokens = purchaseAmount / tokenPrice uint256 amountOfTokensBuying = (msg.value).mul(10**18).div(tokenPrice); // Compute maximal participation for user uint256 maximalParticipationForUser = computeMaxPrivateParticipationAmount(msg.sender); // Require user wants to participate with amount his staking weight allows him require(amountOfTokensBuying <= maximalParticipationForUser, "Overflow -> Weighting score"); // Require that there's enough tokens require( privateSellTokensSold.add(amountOfTokensBuying) <= privateSellAllocation, "Overflow -> Buying more than available" ); // Account sold tokens privateSellTokensSold = privateSellTokensSold.add(amountOfTokensBuying); // Internal sell tokens function sellTokens(msg.value, amountOfTokensBuying); // Mark that user have participated isParticipated[msg.sender] = true; } // Function to participate in public sale function participatePublicSale() public payable isPublicSaleActive { require(publicMaxParticipation >= msg.value, "Contribution amount greater than max participation."); // amountOfTokens = purchaseAmount / tokenPrice uint amountOfTokensBuying = (msg.value).mul(10**18).div(tokenPrice); // Require that there's enough tokens require(amountOfTokensToSell.sub(totalTokensSold) > amountOfTokensBuying); // Internal sell tokens function sellTokens(msg.value, amountOfTokensBuying); // Mark that user have participated isParticipated[msg.sender] = true; } // Internal function to handle selling tokens per given price function sellTokens( uint participationAmount, uint amountOfTokensBuying ) internal { // Add amount of tokens user is buying to total sold amount totalTokensSold = totalTokensSold.add(amountOfTokensBuying); // Add amount of BNBs raised totalBNBRaised = totalBNBRaised.add(participationAmount); // Compute participation id uint participationId = participations.length; // Create participation object Participation memory p = Participation({ amountBNBPaid: participationAmount, amountOfTokensReceived: amountOfTokensBuying, timestamp: block.timestamp, isWithdrawn: false }); // Push participation to array of all participations participations.push(p); // Map user to his participation ids userToHisParticipationId[msg.sender] = participationId; } // Internal function to handle safe transfer function safeTransferBNB( address to, uint value ) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: BNB_TRANSFER_FAILED'); } function withdrawEarningsAndLeftover() public { require(msg.sender == projectOwnerWallet); // Make sure both private and public sale expired require(block.timestamp >= salePublicEndTime && block.timestamp >= salePrivateEndTime); // Earnings amount of the owner uint totalEarnings = address(this).balance; // Amount of tokens which are not sold uint leftover = amountOfTokensToSell.sub(totalTokensSold); safeTransferBNB(msg.sender, totalEarnings); if(leftover > 0) { tokenSold.transfer(msg.sender, leftover); } // Set state of the contract to ENDED state = ContractState.SALE_ENDED; } // Function where user can withdraw tokens he has bought function withdrawTokens() public { require(isParticipated[msg.sender] == true, "User is not participant."); require(now > tokensUnlockingTime, "Tokens are not unlocked yet."); // Get user participation id uint participationId = userToHisParticipationId[msg.sender]; // Same unit can't be withdrawn twice Participation storage p = participations[participationId]; require(p.isWithdrawn == false, "Can not withdraw same thing twice."); // Transfer bought tokens to address tokenSold.transfer(msg.sender, p.amountOfTokensReceived); // Mark participation as withdrawn p.isWithdrawn = true; } // Function to check user participation ids function getUserParticipationId( address user ) public view returns (uint256) { return userToHisParticipationId[user]; } // Function to return total number of participations function getNumberOfParticipations() public view returns (uint256) { return participations.length; } // Function to fetch high level overview of pool sale stats function getSaleStats() public view returns (uint256,uint256) { return (totalTokensSold, totalBNBRaised); } // Function to return when purchased tokens can be withdrawn function getTokensUnlockingTime() public view returns (uint) { return tokensUnlockingTime; } // Function to compute maximal private sell participation amount based on the weighting score function computeMaxPrivateParticipationAmount( address user ) public view returns (uint256) { if(isParticipated[user] == true) { // User can participate only once return 0; } // Compute the maximum user can participate in the private sell uint256 maxParticipation = (privateSellAllocation).div(whitelistedParticipants.length); // Compute how much tokens are left in private sell allocation uint256 leftoverInPrivate = privateSellAllocation.sub(privateSellTokensSold); // Return return maxParticipation > leftoverInPrivate ? leftoverInPrivate : maxParticipation; } // Function to check in which state is the contract at the moment function getInventoryState() public view returns (string memory) { if(state == ContractState.PENDING_SUPPLY) { return "PENDING_SUPPLY"; } return "TOKENS_SUPPLIED"; } // Function to get pool state depending on time and allocation function getPoolState() public view returns (string memory) { if(state == ContractState.PENDING_SUPPLY && now < salePublicEndTime) { return "UPCOMING"; } if(now < salePrivateStartTime) { return "UPCOMING"; } if(totalTokensSold >= amountOfTokensToSell.mul(999).div(1000)) { return "FINISHED"; } else if (now < salePublicEndTime) { return "ONGOING"; } return "FINISHED"; } function getPoolInformation() public view returns ( string memory, uint256, uint256, uint256, uint256, uint256, uint256, uint256, bool, // Is private sell active bool // is public sell active ) { string memory tokenSymbol = tokenSold.symbol(); bool isPrivateSellActive; bool isPublicSellActive; if(block.timestamp >= salePrivateStartTime && block.timestamp <= salePrivateEndTime) { isPrivateSellActive = true; } else if(block.timestamp >= salePublicStartTime && block.timestamp <= salePublicEndTime) { isPublicSellActive = true; } return ( tokenSymbol, totalTokensSold, amountOfTokensToSell, salePrivateStartTime, salePrivateEndTime, salePublicStartTime, salePublicEndTime, tokenPrice, isPrivateSellActive, isPublicSellActive ); } // Function to get participation for specific user. function getParticipation( address user ) public view returns (uint,uint,uint,uint,bool) { if(isParticipated[user] == false) { return (0,0,0,0,false); } Participation memory p = participations[userToHisParticipationId[user]]; return ( p.amountBNBPaid, p.amountOfTokensReceived, p.timestamp, tokensUnlockingTime, p.isWithdrawn ); } /** * @notice Function to whitelist participants for private sale */ function whitelistParticipants( address [] memory participants ) public { require(msg.sender == projectOwnerWallet); for(uint i=0; i < participants.length; i++) { whitelistedParticipants.push(participants[i]); // Whitelist this participant isParticipantWhitelisted[participants[i]] = true; } } function getNumberOfWhitelistedParticipants() public view returns (uint) { return whitelistedParticipants.length; } function getWhitelistedParticipants( uint startIndex, uint endIndex ) public view returns (address [] memory) { if(startIndex == 0 && endIndex == 0) { return whitelistedParticipants; } else { uint len = endIndex - startIndex; address [] memory whitelistedParticipantsPart = new address[](len); uint counter = 0; for(uint i=startIndex; i<endIndex; i++) { whitelistedParticipantsPart[counter] = whitelistedParticipants[i]; counter++; } return whitelistedParticipantsPart; } } } // File contracts/interfaces/IRBAC.sol pragma solidity ^0.6.12; interface IRBAC { function isAdmin(address user) external view returns (bool); } // File contracts/interfaces/ITokenPool.sol pragma solidity ^0.6.12; interface ITokenPool { function getPoolState() external view returns (string memory); } // File contracts/Factory.sol pragma solidity ^0.6.12; /** * Factory for deploying private/public sale contracts after being whitelisted */ contract Factory { using SafeMath for uint256; // Address of staking pool contract address public stakingPool; // Pointer to RBAC contract IRBAC rbac; // Storing all pools deployed in publicly visible array address [] poolsDeployed; // Mapping project owner wallet to his pools mapping(address => address[]) projectOwnerToPoolAddresses; // Length of private sell uint256 public privateSellLength; // Length of public sell uint256 public publicSellLength; // Period of how long the tokens will be locked after purchased uint256 public tokensLockingPeriod; // Only admin modifier restricting calls only to admins registered inside RBAC contract modifier onlyAdmin { require(rbac.isAdmin(msg.sender) == true); _; } // Constructor to set initial values constructor( address _stakingPool, address _rbac ) public { stakingPool = _stakingPool; rbac = IRBAC(_rbac); } // Function to deploy pool --> Only admin can call this function deployPool( uint256 _salePrivateStartTime, address _tokenAddress, uint256 _tokenPrice, uint256 _amountOfTokensToSell, address _projectOwnerWallet ) onlyAdmin public { // Compute public and private sell length (time wise) uint256 privateSellEndTime = _salePrivateStartTime.add(privateSellLength); uint256 publicSellStartTime = privateSellEndTime; uint256 publicSellEndTime = publicSellStartTime.add(publicSellLength); address poolAddress; if(poolsDeployed.length == 0) { SM2LPPool tp = new SM2LPPool( _salePrivateStartTime, privateSellEndTime, publicSellStartTime, publicSellEndTime, publicSellEndTime + tokensLockingPeriod, _tokenAddress, _tokenPrice, _amountOfTokensToSell, _projectOwnerWallet, stakingPool ); poolAddress = address(tp); } else { TokenPool tp = new TokenPool( _salePrivateStartTime, privateSellEndTime, publicSellStartTime, publicSellEndTime, publicSellEndTime + tokensLockingPeriod, _tokenAddress, _tokenPrice, _amountOfTokensToSell, _projectOwnerWallet, stakingPool ); poolAddress = address(tp); } // Push address of newly deployed token pool to list of all addresses poolsDeployed.push(poolAddress); // Push address of newly created token pool to list of project owner addresses projectOwnerToPoolAddresses[_projectOwnerWallet].push(poolAddress); } // Function to return number of pools deployed function getNumberOfPoolsDeployed() public view returns (uint) { return poolsDeployed.length; } // Function to return all deployed pools function getAllPoolsDeployed() public view returns (address[] memory) { return poolsDeployed; } function getPoolsPerState( string memory state ) public view returns (address[] memory) { uint counter = 0; for(uint i = 0; i < poolsDeployed.length; i++) { ITokenPool tp = ITokenPool(poolsDeployed[i]); if(keccak256(abi.encodePacked(tp.getPoolState())) == keccak256(abi.encodePacked(state))) { counter++; } } address [] memory poolsInState = new address[](counter); uint index = 0; for(uint j=0; j < poolsDeployed.length; j++) { ITokenPool tp = ITokenPool(poolsDeployed[j]); if(keccak256(abi.encodePacked(tp.getPoolState())) == keccak256(abi.encodePacked(state))) { poolsInState[index] = poolsDeployed[j]; index++; } } return poolsInState; } // Get pools, pagination enabled in order to avoid getting out of gas function getPools( uint startIndex, uint endIndex ) public view returns (address[] memory) { uint len = endIndex.sub(startIndex); address [] memory pools = new address[](len); for(uint i = 0 ; i < len ; i++) { pools[i] = poolsDeployed[startIndex+i]; } return pools; } // Get pools owned by specific user function getUserPoolsOwned( address user ) public view returns (address[] memory) { return projectOwnerToPoolAddresses[user]; } // Function to set length of public sell function setPublicSellLength( uint256 _publicSellLength ) public onlyAdmin { publicSellLength = _publicSellLength; } // Function to set length of private sell function setPrivateSellLength( uint256 _privateSellLength ) public onlyAdmin { privateSellLength = _privateSellLength; } // Function to set period for how long the tokens will be locked function setTokensLockingPeriod( uint256 _lockPeriod ) public onlyAdmin { tokensLockingPeriod = _lockPeriod; } }
Function to return number of pools deployed
function getNumberOfPoolsDeployed() public view returns (uint) { return poolsDeployed.length; }
2,514,321
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; import { IJustCausePool } from './Interfaces.sol'; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol"; /** * @title JCDepositorERC721 * @author JustCause * This is a proof of concept starter contract for lossless donations * * Aave v3 is used to generate interest for crowdfunding * * Creates an ERC721 with info regarding each Just Cause Pool depositor * * Inherets from openzeppelin ERC721 contracts * **/ contract JCDepositorERC721 is ERC721URIStorageUpgradeable { struct Deposit { uint256 balance; uint256 timeStamp; address asset; } address jcPool; address poolTracker; //key = keccak hash of depositor, pool and asset addresses mapping (uint256 => Deposit) deposits; /** * @dev Only Master can call functions marked by this modifier. **/ modifier onlyPoolTracker(){ require(poolTracker == msg.sender, "not the owner"); _; } function initialize(address _jcPool) initializer public { __ERC721_init("JCP Contributor Token", "JCPC"); jcPool = _jcPool; poolTracker = msg.sender; } /** * @dev Creates NFT for depositor if first deposit for pool and asset * @param _tokenOwner address of depositor * @param _timeStamp timeStamp of token creation * @param _metaUri meta info uri for nft of JCP * @param _asset The address of the underlying asset of the reserve * @return tokenId unique tokenId keccak hash of depositor, pool and asset addresses **/ function addFunds( address _tokenOwner, uint256 _amount, uint256 _timeStamp, address _asset, string memory _metaUri ) public onlyPoolTracker returns (bool) { //tokenId is keccak hash of depositor, pool and asset addresses uint256 tokenId = uint256(keccak256(abi.encodePacked(_tokenOwner, jcPool, _asset))); bool firstDeposit = false; if(_exists(tokenId)){ deposits[tokenId].timeStamp = _timeStamp; deposits[tokenId].balance += _amount; } else{ deposits[tokenId] = Deposit(_amount, _timeStamp, _asset); _mint(_tokenOwner, tokenId); _setTokenURI(tokenId, _metaUri); firstDeposit = true; } return firstDeposit; } /** * @dev Withdraw balance for depositor * @param _tokenOwner address of depositor * @param _amount amount to withdraw * @param _asset The address of the underlying asset of the reserve **/ function withdrawFunds(address _tokenOwner, uint256 _amount, address _asset) onlyPoolTracker external{ uint256 tokenId = uint256(keccak256(abi.encodePacked(_tokenOwner, jcPool, _asset))); require(_exists(tokenId), "tokenId doesn't exist"); uint256 balance = deposits[tokenId].balance; require(balance >= _amount, "insufficient balance"); balance -= _amount; if(balance == 0){ deposits[tokenId].timeStamp = 0; } deposits[tokenId].balance = balance; } /** * @param _tokenId unique tokenId keccak hash of depositor, pool and asset addresses * @return Deposit struct containing info about deposit **/ function getDepositInfo(uint256 _tokenId) public view returns (Deposit memory){ return deposits[_tokenId]; } /** * @param _tokenId unique tokenId keccak hash of depositor, pool and asset addresses * @return asset balance of user in pool **/ function getUserBalance(uint256 _tokenId) public view returns (uint256){ return deposits[_tokenId].balance; } function getUserTokens(address _tokenOwner) external view returns(uint256[] memory){ address[] memory assets = IJustCausePool(jcPool).getAcceptedTokens(); uint256 len = assets.length; uint256[] memory ids = new uint256[](len); for(uint256 i = 0; i < len; i++){ uint256 tokenId = uint256(keccak256(abi.encodePacked(_tokenOwner, jcPool, assets[i]))); if(_exists(tokenId)){ ids[i] = tokenId; //counter = counter + 1; } } return ids; } function getPool() public view returns(address){ return jcPool; } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721Upgradeable) { require(from == address(0), "non-transferrable"); super._beforeTokenTransfer(from, to, tokenId); } function tokenURI(uint256 tokenId) public view override(ERC721URIStorageUpgradeable) returns (string memory) { return super.tokenURI(tokenId); } }
_tokenId unique tokenId keccak hash of depositor, pool and asset addresses return Deposit struct containing info about deposit/
function getDepositInfo(uint256 _tokenId) public view returns (Deposit memory){ return deposits[_tokenId]; }
1,758,681
pragma solidity ^0.5.13; import "openzeppelin-solidity/contracts/math/Math.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "solidity-bytes-utils/contracts/BytesLib.sol"; import "./interfaces/IValidators.sol"; import "../common/CalledByVm.sol"; import "../common/InitializableV2.sol"; import "../common/FixidityLib.sol"; import "../common/linkedlists/AddressLinkedList.sol"; import "../common/UsingRegistry.sol"; import "../common/UsingPrecompiles.sol"; import "../common/interfaces/ICeloVersionedContract.sol"; import "../common/libraries/ReentrancyGuard.sol"; /** * @title A contract for registering and electing Validator Groups and Validators. */ contract Validators is IValidators, ICeloVersionedContract, Ownable, ReentrancyGuard, InitializableV2, UsingRegistry, UsingPrecompiles, CalledByVm { using FixidityLib for FixidityLib.Fraction; using AddressLinkedList for LinkedList.List; using SafeMath for uint256; using BytesLib for bytes; // For Validators, these requirements must be met in order to: // 1. Register a validator // 2. Affiliate with and be added to a group // 3. Receive epoch payments (note that the group must meet the group requirements as well) // Accounts may de-register their Validator `duration` seconds after they were last a member of a // group, after which no restrictions on Locked Gold will apply to the account. // // For Validator Groups, these requirements must be met in order to: // 1. Register a group // 2. Add a member to a group // 3. Receive epoch payments // Note that for groups, the requirement value is multiplied by the number of members, and is // enforced for `duration` seconds after the group last had that number of members. // Accounts may de-register their Group `duration` seconds after they were last non-empty, after // which no restrictions on Locked Gold will apply to the account. struct LockedGoldRequirements { uint256 value; // In seconds. uint256 duration; } struct ValidatorGroup { bool exists; LinkedList.List members; FixidityLib.Fraction commission; FixidityLib.Fraction nextCommission; uint256 nextCommissionBlock; // sizeHistory[i] contains the last time the group contained i members. uint256[] sizeHistory; SlashingInfo slashInfo; } // Stores the epoch number at which a validator joined a particular group. struct MembershipHistoryEntry { uint256 epochNumber; address group; } // Stores the per-epoch membership history of a validator, used to determine which group // commission should be paid to at the end of an epoch. // Stores a timestamp of the last time the validator was removed from a group, used to determine // whether or not a group can de-register. struct MembershipHistory { // The key to the most recent entry in the entries mapping. uint256 tail; // The number of entries in this validators membership history. uint256 numEntries; mapping(uint256 => MembershipHistoryEntry) entries; uint256 lastRemovedFromGroupTimestamp; } struct SlashingInfo { FixidityLib.Fraction multiplier; uint256 lastSlashed; } struct PublicKeys { bytes ecdsa; bytes bls; } struct Validator { PublicKeys publicKeys; address affiliation; FixidityLib.Fraction score; MembershipHistory membershipHistory; } // Parameters that govern the calculation of validator's score. struct ValidatorScoreParameters { uint256 exponent; FixidityLib.Fraction adjustmentSpeed; } mapping(address => ValidatorGroup) private groups; mapping(address => Validator) private validators; address[] private registeredGroups; address[] private registeredValidators; LockedGoldRequirements public validatorLockedGoldRequirements; LockedGoldRequirements public groupLockedGoldRequirements; ValidatorScoreParameters private validatorScoreParameters; uint256 public membershipHistoryLength; uint256 public maxGroupSize; // The number of blocks to delay a ValidatorGroup's commission update uint256 public commissionUpdateDelay; uint256 public slashingMultiplierResetPeriod; uint256 public downtimeGracePeriod; event MaxGroupSizeSet(uint256 size); event CommissionUpdateDelaySet(uint256 delay); event ValidatorScoreParametersSet(uint256 exponent, uint256 adjustmentSpeed); event GroupLockedGoldRequirementsSet(uint256 value, uint256 duration); event ValidatorLockedGoldRequirementsSet(uint256 value, uint256 duration); event MembershipHistoryLengthSet(uint256 length); event ValidatorRegistered(address indexed validator); event ValidatorDeregistered(address indexed validator); event ValidatorAffiliated(address indexed validator, address indexed group); event ValidatorDeaffiliated(address indexed validator, address indexed group); event ValidatorEcdsaPublicKeyUpdated(address indexed validator, bytes ecdsaPublicKey); event ValidatorBlsPublicKeyUpdated(address indexed validator, bytes blsPublicKey); event ValidatorScoreUpdated(address indexed validator, uint256 score, uint256 epochScore); event ValidatorGroupRegistered(address indexed group, uint256 commission); event ValidatorGroupDeregistered(address indexed group); event ValidatorGroupMemberAdded(address indexed group, address indexed validator); event ValidatorGroupMemberRemoved(address indexed group, address indexed validator); event ValidatorGroupMemberReordered(address indexed group, address indexed validator); event ValidatorGroupCommissionUpdateQueued( address indexed group, uint256 commission, uint256 activationBlock ); event ValidatorGroupCommissionUpdated(address indexed group, uint256 commission); event ValidatorEpochPaymentDistributed( address indexed validator, uint256 validatorPayment, address indexed group, uint256 groupPayment ); modifier onlySlasher() { require(getLockedGold().isSlasher(msg.sender), "Only registered slasher can call"); _; } /** * @notice Returns the storage, major, minor, and patch version of the contract. * @return The storage, major, minor, and patch version of the contract. */ function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) { return (1, 2, 0, 1); } /** * @notice Used in place of the constructor to allow the contract to be upgradable via proxy. * @param registryAddress The address of the registry core smart contract. * @param groupRequirementValue The Locked Gold requirement amount for groups. * @param groupRequirementDuration The Locked Gold requirement duration for groups. * @param validatorRequirementValue The Locked Gold requirement amount for validators. * @param validatorRequirementDuration The Locked Gold requirement duration for validators. * @param validatorScoreExponent The exponent used in calculating validator scores. * @param validatorScoreAdjustmentSpeed The speed at which validator scores are adjusted. * @param _membershipHistoryLength The max number of entries for validator membership history. * @param _maxGroupSize The maximum group size. * @param _commissionUpdateDelay The number of blocks to delay a ValidatorGroup's commission * update. * @dev Should be called only once. */ function initialize( address registryAddress, uint256 groupRequirementValue, uint256 groupRequirementDuration, uint256 validatorRequirementValue, uint256 validatorRequirementDuration, uint256 validatorScoreExponent, uint256 validatorScoreAdjustmentSpeed, uint256 _membershipHistoryLength, uint256 _slashingMultiplierResetPeriod, uint256 _maxGroupSize, uint256 _commissionUpdateDelay, uint256 _downtimeGracePeriod ) external initializer { _transferOwnership(msg.sender); setRegistry(registryAddress); setGroupLockedGoldRequirements(groupRequirementValue, groupRequirementDuration); setValidatorLockedGoldRequirements(validatorRequirementValue, validatorRequirementDuration); setValidatorScoreParameters(validatorScoreExponent, validatorScoreAdjustmentSpeed); setMaxGroupSize(_maxGroupSize); setCommissionUpdateDelay(_commissionUpdateDelay); setMembershipHistoryLength(_membershipHistoryLength); setSlashingMultiplierResetPeriod(_slashingMultiplierResetPeriod); setDowntimeGracePeriod(_downtimeGracePeriod); } /** * @notice Sets initialized == true on implementation contracts * @param test Set to true to skip implementation initialization */ constructor(bool test) public InitializableV2(test) {} /** * @notice Updates the block delay for a ValidatorGroup's commission udpdate * @param delay Number of blocks to delay the update */ function setCommissionUpdateDelay(uint256 delay) public onlyOwner { require(delay != commissionUpdateDelay, "commission update delay not changed"); commissionUpdateDelay = delay; emit CommissionUpdateDelaySet(delay); } /** * @notice Updates the maximum number of members a group can have. * @param size The maximum group size. * @return True upon success. */ function setMaxGroupSize(uint256 size) public onlyOwner returns (bool) { require(0 < size, "Max group size cannot be zero"); require(size != maxGroupSize, "Max group size not changed"); maxGroupSize = size; emit MaxGroupSizeSet(size); return true; } /** * @notice Updates the number of validator group membership entries to store. * @param length The number of validator group membership entries to store. * @return True upon success. */ function setMembershipHistoryLength(uint256 length) public onlyOwner returns (bool) { require(0 < length, "Membership history length cannot be zero"); require(length != membershipHistoryLength, "Membership history length not changed"); membershipHistoryLength = length; emit MembershipHistoryLengthSet(length); return true; } /** * @notice Updates the validator score parameters. * @param exponent The exponent used in calculating the score. * @param adjustmentSpeed The speed at which the score is adjusted. * @return True upon success. */ function setValidatorScoreParameters(uint256 exponent, uint256 adjustmentSpeed) public onlyOwner returns (bool) { require( adjustmentSpeed <= FixidityLib.fixed1().unwrap(), "Adjustment speed cannot be larger than 1" ); require( exponent != validatorScoreParameters.exponent || !FixidityLib.wrap(adjustmentSpeed).equals(validatorScoreParameters.adjustmentSpeed), "Adjustment speed and exponent not changed" ); validatorScoreParameters = ValidatorScoreParameters( exponent, FixidityLib.wrap(adjustmentSpeed) ); emit ValidatorScoreParametersSet(exponent, adjustmentSpeed); return true; } /** * @notice Returns the maximum number of members a group can add. * @return The maximum number of members a group can add. */ function getMaxGroupSize() external view returns (uint256) { return maxGroupSize; } /** * @notice Returns the block delay for a ValidatorGroup's commission udpdate. * @return The block delay for a ValidatorGroup's commission udpdate. */ function getCommissionUpdateDelay() external view returns (uint256) { return commissionUpdateDelay; } /** * @notice Updates the Locked Gold requirements for Validator Groups. * @param value The per-member amount of Locked Gold required. * @param duration The time (in seconds) that these requirements persist for. * @return True upon success. */ function setGroupLockedGoldRequirements(uint256 value, uint256 duration) public onlyOwner returns (bool) { LockedGoldRequirements storage requirements = groupLockedGoldRequirements; require( value != requirements.value || duration != requirements.duration, "Group requirements not changed" ); groupLockedGoldRequirements = LockedGoldRequirements(value, duration); emit GroupLockedGoldRequirementsSet(value, duration); return true; } /** * @notice Updates the Locked Gold requirements for Validators. * @param value The amount of Locked Gold required. * @param duration The time (in seconds) that these requirements persist for. * @return True upon success. */ function setValidatorLockedGoldRequirements(uint256 value, uint256 duration) public onlyOwner returns (bool) { LockedGoldRequirements storage requirements = validatorLockedGoldRequirements; require( value != requirements.value || duration != requirements.duration, "Validator requirements not changed" ); validatorLockedGoldRequirements = LockedGoldRequirements(value, duration); emit ValidatorLockedGoldRequirementsSet(value, duration); return true; } /** * @notice Registers a validator unaffiliated with any validator group. * @param ecdsaPublicKey The ECDSA public key that the validator is using for consensus, should * match the validator signer. 64 bytes. * @param blsPublicKey The BLS public key that the validator is using for consensus, should pass * proof of possession. 96 bytes. * @param blsPop The BLS public key proof-of-possession, which consists of a signature on the * account address. 48 bytes. * @return True upon success. * @dev Fails if the account is already a validator or validator group. * @dev Fails if the account does not have sufficient Locked Gold. */ function registerValidator( bytes calldata ecdsaPublicKey, bytes calldata blsPublicKey, bytes calldata blsPop ) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(!isValidator(account) && !isValidatorGroup(account), "Already registered"); uint256 lockedGoldBalance = getLockedGold().getAccountTotalLockedGold(account); require(lockedGoldBalance >= validatorLockedGoldRequirements.value, "Deposit too small"); Validator storage validator = validators[account]; address signer = getAccounts().getValidatorSigner(account); require( _updateEcdsaPublicKey(validator, account, signer, ecdsaPublicKey), "Error updating ECDSA public key" ); require( _updateBlsPublicKey(validator, account, blsPublicKey, blsPop), "Error updating BLS public key" ); registeredValidators.push(account); updateMembershipHistory(account, address(0)); emit ValidatorRegistered(account); return true; } /** * @notice Returns the parameters that govern how a validator's score is calculated. * @return The parameters that goven how a validator's score is calculated. */ function getValidatorScoreParameters() external view returns (uint256, uint256) { return (validatorScoreParameters.exponent, validatorScoreParameters.adjustmentSpeed.unwrap()); } /** * @notice Returns the group membership history of a validator. * @param account The validator whose membership history to return. * @return The group membership history of a validator. */ function getMembershipHistory(address account) external view returns (uint256[] memory, address[] memory, uint256, uint256) { MembershipHistory storage history = validators[account].membershipHistory; uint256[] memory epochs = new uint256[](history.numEntries); address[] memory membershipGroups = new address[](history.numEntries); for (uint256 i = 0; i < history.numEntries; i = i.add(1)) { uint256 index = history.tail.add(i); epochs[i] = history.entries[index].epochNumber; membershipGroups[i] = history.entries[index].group; } return (epochs, membershipGroups, history.lastRemovedFromGroupTimestamp, history.tail); } /** * @notice Calculates the validator score for an epoch from the uptime value for the epoch. * @param uptime The Fixidity representation of the validator's uptime, between 0 and 1. * @dev epoch_score = uptime ** exponent * @return Fixidity representation of the epoch score between 0 and 1. */ function calculateEpochScore(uint256 uptime) public view returns (uint256) { require(uptime <= FixidityLib.fixed1().unwrap(), "Uptime cannot be larger than one"); uint256 numerator; uint256 denominator; uptime = Math.min(uptime.add(downtimeGracePeriod), FixidityLib.fixed1().unwrap()); (numerator, denominator) = fractionMulExp( FixidityLib.fixed1().unwrap(), FixidityLib.fixed1().unwrap(), uptime, FixidityLib.fixed1().unwrap(), validatorScoreParameters.exponent, 18 ); return FixidityLib.newFixedFraction(numerator, denominator).unwrap(); } /** * @notice Calculates the aggregate score of a group for an epoch from individual uptimes. * @param uptimes Array of Fixidity representations of the validators' uptimes, between 0 and 1. * @dev group_score = average(uptimes ** exponent) * @return Fixidity representation of the group epoch score between 0 and 1. */ function calculateGroupEpochScore(uint256[] calldata uptimes) external view returns (uint256) { require(uptimes.length > 0, "Uptime array empty"); require(uptimes.length <= maxGroupSize, "Uptime array larger than maximum group size"); FixidityLib.Fraction memory sum; for (uint256 i = 0; i < uptimes.length; i = i.add(1)) { sum = sum.add(FixidityLib.wrap(calculateEpochScore(uptimes[i]))); } return sum.divide(FixidityLib.newFixed(uptimes.length)).unwrap(); } /** * @notice Updates a validator's score based on its uptime for the epoch. * @param signer The validator signer of the validator account whose score needs updating. * @param uptime The Fixidity representation of the validator's uptime, between 0 and 1. * @return True upon success. */ function updateValidatorScoreFromSigner(address signer, uint256 uptime) external onlyVm() { _updateValidatorScoreFromSigner(signer, uptime); } /** * @notice Updates a validator's score based on its uptime for the epoch. * @param signer The validator signer of the validator whose score needs updating. * @param uptime The Fixidity representation of the validator's uptime, between 0 and 1. * @dev new_score = uptime ** exponent * adjustmentSpeed + old_score * (1 - adjustmentSpeed) * @return True upon success. */ function _updateValidatorScoreFromSigner(address signer, uint256 uptime) internal { address account = getAccounts().signerToAccount(signer); require(isValidator(account), "Not a validator"); FixidityLib.Fraction memory epochScore = FixidityLib.wrap(calculateEpochScore(uptime)); FixidityLib.Fraction memory newComponent = validatorScoreParameters.adjustmentSpeed.multiply( epochScore ); FixidityLib.Fraction memory currentComponent = FixidityLib.fixed1().subtract( validatorScoreParameters.adjustmentSpeed ); currentComponent = currentComponent.multiply(validators[account].score); validators[account].score = FixidityLib.wrap( Math.min(epochScore.unwrap(), newComponent.add(currentComponent).unwrap()) ); emit ValidatorScoreUpdated(account, validators[account].score.unwrap(), epochScore.unwrap()); } /** * @notice Distributes epoch payments to the account associated with `signer` and its group. * @param signer The validator signer of the account to distribute the epoch payment to. * @param maxPayment The maximum payment to the validator. Actual payment is based on score and * group commission. * @return The total payment paid to the validator and their group. */ function distributeEpochPaymentsFromSigner(address signer, uint256 maxPayment) external onlyVm() returns (uint256) { return _distributeEpochPaymentsFromSigner(signer, maxPayment); } /** * @notice Distributes epoch payments to the account associated with `signer` and its group. * @param signer The validator signer of the validator to distribute the epoch payment to. * @param maxPayment The maximum payment to the validator. Actual payment is based on score and * group commission. * @return The total payment paid to the validator and their group. */ function _distributeEpochPaymentsFromSigner(address signer, uint256 maxPayment) internal returns (uint256) { address account = getAccounts().signerToAccount(signer); require(isValidator(account), "Not a validator"); // The group that should be paid is the group that the validator was a member of at the // time it was elected. address group = getMembershipInLastEpoch(account); require(group != address(0), "Validator not registered with a group"); // Both the validator and the group must maintain the minimum locked gold balance in order to // receive epoch payments. if (meetsAccountLockedGoldRequirements(account) && meetsAccountLockedGoldRequirements(group)) { FixidityLib.Fraction memory totalPayment = FixidityLib .newFixed(maxPayment) .multiply(validators[account].score) .multiply(groups[group].slashInfo.multiplier); uint256 groupPayment = totalPayment.multiply(groups[group].commission).fromFixed(); uint256 validatorPayment = totalPayment.fromFixed().sub(groupPayment); IStableToken stableToken = getStableToken(); require(stableToken.mint(group, groupPayment), "mint failed to validator group"); require(stableToken.mint(account, validatorPayment), "mint failed to validator account"); emit ValidatorEpochPaymentDistributed(account, validatorPayment, group, groupPayment); return totalPayment.fromFixed(); } else { return 0; } } /** * @notice De-registers a validator. * @param index The index of this validator in the list of all registered validators. * @return True upon success. * @dev Fails if the account is not a validator. * @dev Fails if the validator has been a member of a group too recently. */ function deregisterValidator(uint256 index) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidator(account), "Not a validator"); // Require that the validator has not been a member of a validator group for // `validatorLockedGoldRequirements.duration` seconds. Validator storage validator = validators[account]; if (validator.affiliation != address(0)) { require( !groups[validator.affiliation].members.contains(account), "Has been group member recently" ); } uint256 requirementEndTime = validator.membershipHistory.lastRemovedFromGroupTimestamp.add( validatorLockedGoldRequirements.duration ); require(requirementEndTime < now, "Not yet requirement end time"); // Remove the validator. deleteElement(registeredValidators, account, index); delete validators[account]; emit ValidatorDeregistered(account); return true; } /** * @notice Affiliates a validator with a group, allowing it to be added as a member. * @param group The validator group with which to affiliate. * @return True upon success. * @dev De-affiliates with the previously affiliated group if present. */ function affiliate(address group) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidator(account), "Not a validator"); require(isValidatorGroup(group), "Not a validator group"); require(meetsAccountLockedGoldRequirements(account), "Validator doesn't meet requirements"); require(meetsAccountLockedGoldRequirements(group), "Group doesn't meet requirements"); Validator storage validator = validators[account]; if (validator.affiliation != address(0)) { _deaffiliate(validator, account); } validator.affiliation = group; emit ValidatorAffiliated(account, group); return true; } /** * @notice De-affiliates a validator, removing it from the group for which it is a member. * @return True upon success. * @dev Fails if the account is not a validator with non-zero affiliation. */ function deaffiliate() external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidator(account), "Not a validator"); Validator storage validator = validators[account]; require(validator.affiliation != address(0), "deaffiliate: not affiliated"); _deaffiliate(validator, account); return true; } /** * @notice Updates a validator's BLS key. * @param blsPublicKey The BLS public key that the validator is using for consensus, should pass * proof of possession. 48 bytes. * @param blsPop The BLS public key proof-of-possession, which consists of a signature on the * account address. 48 bytes. * @return True upon success. */ function updateBlsPublicKey(bytes calldata blsPublicKey, bytes calldata blsPop) external returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidator(account), "Not a validator"); Validator storage validator = validators[account]; require( _updateBlsPublicKey(validator, account, blsPublicKey, blsPop), "Error updating BLS public key" ); return true; } /** * @notice Updates a validator's BLS key. * @param validator The validator whose BLS public key should be updated. * @param account The address under which the validator is registered. * @param blsPublicKey The BLS public key that the validator is using for consensus, should pass * proof of possession. 96 bytes. * @param blsPop The BLS public key proof-of-possession, which consists of a signature on the * account address. 48 bytes. * @return True upon success. */ function _updateBlsPublicKey( Validator storage validator, address account, bytes memory blsPublicKey, bytes memory blsPop ) private returns (bool) { require(blsPublicKey.length == 96, "Wrong BLS public key length"); require(blsPop.length == 48, "Wrong BLS PoP length"); require(checkProofOfPossession(account, blsPublicKey, blsPop), "Invalid BLS PoP"); validator.publicKeys.bls = blsPublicKey; emit ValidatorBlsPublicKeyUpdated(account, blsPublicKey); return true; } /** * @notice Updates a validator's ECDSA key. * @param account The address under which the validator is registered. * @param signer The address which the validator is using to sign consensus messages. * @param ecdsaPublicKey The ECDSA public key corresponding to `signer`. * @return True upon success. */ function updateEcdsaPublicKey(address account, address signer, bytes calldata ecdsaPublicKey) external onlyRegisteredContract(ACCOUNTS_REGISTRY_ID) returns (bool) { require(isValidator(account), "Not a validator"); Validator storage validator = validators[account]; require( _updateEcdsaPublicKey(validator, account, signer, ecdsaPublicKey), "Error updating ECDSA public key" ); return true; } /** * @notice Updates a validator's ECDSA key. * @param validator The validator whose ECDSA public key should be updated. * @param signer The address with which the validator is signing consensus messages. * @param ecdsaPublicKey The ECDSA public key that the validator is using for consensus. Should * match `signer`. 64 bytes. * @return True upon success. */ function _updateEcdsaPublicKey( Validator storage validator, address account, address signer, bytes memory ecdsaPublicKey ) private returns (bool) { require(ecdsaPublicKey.length == 64, "Wrong ECDSA public key length"); require( address(uint160(uint256(keccak256(ecdsaPublicKey)))) == signer, "ECDSA key does not match signer" ); validator.publicKeys.ecdsa = ecdsaPublicKey; emit ValidatorEcdsaPublicKeyUpdated(account, ecdsaPublicKey); return true; } /** * @notice Updates a validator's ECDSA and BLS keys. * @param account The address under which the validator is registered. * @param signer The address which the validator is using to sign consensus messages. * @param ecdsaPublicKey The ECDSA public key corresponding to `signer`. * @param blsPublicKey The BLS public key that the validator is using for consensus, should pass * proof of possession. 96 bytes. * @param blsPop The BLS public key proof-of-possession, which consists of a signature on the * account address. 48 bytes. * @return True upon success. */ function updatePublicKeys( address account, address signer, bytes calldata ecdsaPublicKey, bytes calldata blsPublicKey, bytes calldata blsPop ) external onlyRegisteredContract(ACCOUNTS_REGISTRY_ID) returns (bool) { require(isValidator(account), "Not a validator"); Validator storage validator = validators[account]; require( _updateEcdsaPublicKey(validator, account, signer, ecdsaPublicKey), "Error updating ECDSA public key" ); require( _updateBlsPublicKey(validator, account, blsPublicKey, blsPop), "Error updating BLS public key" ); return true; } /** * @notice Registers a validator group with no member validators. * @param commission Fixidity representation of the commission this group receives on epoch * payments made to its members. * @return True upon success. * @dev Fails if the account is already a validator or validator group. * @dev Fails if the account does not have sufficient weight. */ function registerValidatorGroup(uint256 commission) external nonReentrant returns (bool) { require(commission <= FixidityLib.fixed1().unwrap(), "Commission can't be greater than 100%"); address account = getAccounts().validatorSignerToAccount(msg.sender); require(!isValidator(account), "Already registered as validator"); require(!isValidatorGroup(account), "Already registered as group"); uint256 lockedGoldBalance = getLockedGold().getAccountTotalLockedGold(account); require(lockedGoldBalance >= groupLockedGoldRequirements.value, "Not enough locked gold"); ValidatorGroup storage group = groups[account]; group.exists = true; group.commission = FixidityLib.wrap(commission); group.slashInfo = SlashingInfo(FixidityLib.fixed1(), 0); registeredGroups.push(account); emit ValidatorGroupRegistered(account, commission); return true; } /** * @notice De-registers a validator group. * @param index The index of this validator group in the list of all validator groups. * @return True upon success. * @dev Fails if the account is not a validator group with no members. * @dev Fails if the group has had members too recently. */ function deregisterValidatorGroup(uint256 index) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); // Only Validator Groups that have never had members or have been empty for at least // `groupLockedGoldRequirements.duration` seconds can be deregistered. require(isValidatorGroup(account), "Not a validator group"); require(groups[account].members.numElements == 0, "Validator group not empty"); uint256[] storage sizeHistory = groups[account].sizeHistory; if (sizeHistory.length > 1) { require( sizeHistory[1].add(groupLockedGoldRequirements.duration) < now, "Hasn't been empty for long enough" ); } delete groups[account]; deleteElement(registeredGroups, account, index); emit ValidatorGroupDeregistered(account); return true; } /** * @notice Adds a member to the end of a validator group's list of members. * @param validator The validator to add to the group * @return True upon success. * @dev Fails if `validator` has not set their affiliation to this account. * @dev Fails if the group has zero members. */ function addMember(address validator) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(groups[account].members.numElements > 0, "Validator group empty"); return _addMember(account, validator, address(0), address(0)); } /** * @notice Adds the first member to a group's list of members and marks it eligible for election. * @param validator The validator to add to the group * @param lesser The address of the group that has received fewer votes than this group. * @param greater The address of the group that has received more votes than this group. * @return True upon success. * @dev Fails if `validator` has not set their affiliation to this account. * @dev Fails if the group has > 0 members. */ function addFirstMember(address validator, address lesser, address greater) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(groups[account].members.numElements == 0, "Validator group not empty"); return _addMember(account, validator, lesser, greater); } /** * @notice Adds a member to the end of a validator group's list of members. * @param group The address of the validator group. * @param validator The validator to add to the group. * @param lesser The address of the group that has received fewer votes than this group. * @param greater The address of the group that has received more votes than this group. * @return True upon success. * @dev Fails if `validator` has not set their affiliation to this account. * @dev Fails if the group has > 0 members. */ function _addMember(address group, address validator, address lesser, address greater) private returns (bool) { require(isValidatorGroup(group) && isValidator(validator), "Not validator and group"); ValidatorGroup storage _group = groups[group]; require(_group.members.numElements < maxGroupSize, "group would exceed maximum size"); require(validators[validator].affiliation == group, "Not affiliated to group"); require(!_group.members.contains(validator), "Already in group"); uint256 numMembers = _group.members.numElements.add(1); _group.members.push(validator); require(meetsAccountLockedGoldRequirements(group), "Group requirements not met"); require(meetsAccountLockedGoldRequirements(validator), "Validator requirements not met"); if (numMembers == 1) { getElection().markGroupEligible(group, lesser, greater); } updateMembershipHistory(validator, group); updateSizeHistory(group, numMembers.sub(1)); emit ValidatorGroupMemberAdded(group, validator); return true; } /** * @notice Removes a member from a validator group. * @param validator The validator to remove from the group * @return True upon success. * @dev Fails if `validator` is not a member of the account's group. */ function removeMember(address validator) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidatorGroup(account) && isValidator(validator), "is not group and validator"); return _removeMember(account, validator); } /** * @notice Reorders a member within a validator group. * @param validator The validator to reorder. * @param lesserMember The member who will be behind `validator`, or 0 if `validator` will be the * last member. * @param greaterMember The member who will be ahead of `validator`, or 0 if `validator` will be * the first member. * @return True upon success. * @dev Fails if `validator` is not a member of the account's validator group. */ function reorderMember(address validator, address lesserMember, address greaterMember) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidatorGroup(account), "Not a group"); require(isValidator(validator), "Not a validator"); ValidatorGroup storage group = groups[account]; require(group.members.contains(validator), "Not a member of the group"); group.members.update(validator, lesserMember, greaterMember); emit ValidatorGroupMemberReordered(account, validator); return true; } /** * @notice Queues an update to a validator group's commission. * If there was a previously scheduled update, that is overwritten. * @param commission Fixidity representation of the commission this group receives on epoch * payments made to its members. Must be in the range [0, 1.0]. */ function setNextCommissionUpdate(uint256 commission) external { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidatorGroup(account), "Not a validator group"); ValidatorGroup storage group = groups[account]; require(commission <= FixidityLib.fixed1().unwrap(), "Commission can't be greater than 100%"); require(commission != group.commission.unwrap(), "Commission must be different"); group.nextCommission = FixidityLib.wrap(commission); group.nextCommissionBlock = block.number.add(commissionUpdateDelay); emit ValidatorGroupCommissionUpdateQueued(account, commission, group.nextCommissionBlock); } /** * @notice Updates a validator group's commission based on the previously queued update */ function updateCommission() external { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidatorGroup(account), "Not a validator group"); ValidatorGroup storage group = groups[account]; require(group.nextCommissionBlock != 0, "No commission update queued"); require(group.nextCommissionBlock <= block.number, "Can't apply commission update yet"); group.commission = group.nextCommission; delete group.nextCommission; delete group.nextCommissionBlock; emit ValidatorGroupCommissionUpdated(account, group.commission.unwrap()); } /** * @notice Returns the current locked gold balance requirement for the supplied account. * @param account The account that may have to meet locked gold balance requirements. * @return The current locked gold balance requirement for the supplied account. */ function getAccountLockedGoldRequirement(address account) public view returns (uint256) { if (isValidator(account)) { return validatorLockedGoldRequirements.value; } else if (isValidatorGroup(account)) { uint256 multiplier = Math.max(1, groups[account].members.numElements); uint256[] storage sizeHistory = groups[account].sizeHistory; if (sizeHistory.length > 0) { for (uint256 i = sizeHistory.length.sub(1); i > 0; i = i.sub(1)) { if (sizeHistory[i].add(groupLockedGoldRequirements.duration) >= now) { multiplier = Math.max(i, multiplier); break; } } } return groupLockedGoldRequirements.value.mul(multiplier); } return 0; } /** * @notice Returns whether or not an account meets its Locked Gold requirements. * @param account The address of the account. * @return Whether or not an account meets its Locked Gold requirements. */ function meetsAccountLockedGoldRequirements(address account) public view returns (bool) { uint256 balance = getLockedGold().getAccountTotalLockedGold(account); // Add a bit of "wiggle room" to accommodate the fact that vote activation can result in ~1 // wei rounding errors. Using 10 as an additional margin of safety. return balance.add(10) >= getAccountLockedGoldRequirement(account); } /** * @notice Returns the validator BLS key. * @param signer The account that registered the validator or its authorized signing address. * @return The validator BLS key. */ function getValidatorBlsPublicKeyFromSigner(address signer) external view returns (bytes memory blsPublicKey) { address account = getAccounts().signerToAccount(signer); require(isValidator(account), "Not a validator"); return validators[account].publicKeys.bls; } /** * @notice Returns validator information. * @param account The account that registered the validator. * @return The unpacked validator struct. */ function getValidator(address account) public view returns ( bytes memory ecdsaPublicKey, bytes memory blsPublicKey, address affiliation, uint256 score, address signer ) { require(isValidator(account), "Not a validator"); Validator storage validator = validators[account]; return ( validator.publicKeys.ecdsa, validator.publicKeys.bls, validator.affiliation, validator.score.unwrap(), getAccounts().getValidatorSigner(account) ); } /** * @notice Returns validator group information. * @param account The account that registered the validator group. * @return The unpacked validator group struct. */ function getValidatorGroup(address account) external view returns (address[] memory, uint256, uint256, uint256, uint256[] memory, uint256, uint256) { require(isValidatorGroup(account), "Not a validator group"); ValidatorGroup storage group = groups[account]; return ( group.members.getKeys(), group.commission.unwrap(), group.nextCommission.unwrap(), group.nextCommissionBlock, group.sizeHistory, group.slashInfo.multiplier.unwrap(), group.slashInfo.lastSlashed ); } /** * @notice Returns the number of members in a validator group. * @param account The address of the validator group. * @return The number of members in a validator group. */ function getGroupNumMembers(address account) public view returns (uint256) { require(isValidatorGroup(account), "Not validator group"); return groups[account].members.numElements; } /** * @notice Returns the top n group members for a particular group. * @param account The address of the validator group. * @param n The number of members to return. * @return The top n group members for a particular group. */ function getTopGroupValidators(address account, uint256 n) external view returns (address[] memory) { address[] memory topAccounts = groups[account].members.headN(n); address[] memory topValidators = new address[](n); for (uint256 i = 0; i < n; i = i.add(1)) { topValidators[i] = getAccounts().getValidatorSigner(topAccounts[i]); } return topValidators; } /** * @notice Returns the number of members in the provided validator groups. * @param accounts The addresses of the validator groups. * @return The number of members in the provided validator groups. */ function getGroupsNumMembers(address[] calldata accounts) external view returns (uint256[] memory) { uint256[] memory numMembers = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; i = i.add(1)) { numMembers[i] = getGroupNumMembers(accounts[i]); } return numMembers; } /** * @notice Returns the number of registered validators. * @return The number of registered validators. */ function getNumRegisteredValidators() external view returns (uint256) { return registeredValidators.length; } /** * @notice Returns the Locked Gold requirements for validators. * @return The Locked Gold requirements for validators. */ function getValidatorLockedGoldRequirements() external view returns (uint256, uint256) { return (validatorLockedGoldRequirements.value, validatorLockedGoldRequirements.duration); } /** * @notice Returns the Locked Gold requirements for validator groups. * @return The Locked Gold requirements for validator groups. */ function getGroupLockedGoldRequirements() external view returns (uint256, uint256) { return (groupLockedGoldRequirements.value, groupLockedGoldRequirements.duration); } /** * @notice Returns the list of registered validator accounts. * @return The list of registered validator accounts. */ function getRegisteredValidators() external view returns (address[] memory) { return registeredValidators; } /** * @notice Returns the list of signers for the registered validator accounts. * @return The list of signers for registered validator accounts. */ function getRegisteredValidatorSigners() external view returns (address[] memory) { IAccounts accounts = getAccounts(); address[] memory signers = new address[](registeredValidators.length); for (uint256 i = 0; i < signers.length; i = i.add(1)) { signers[i] = accounts.getValidatorSigner(registeredValidators[i]); } return signers; } /** * @notice Returns the list of registered validator group accounts. * @return The list of registered validator group addresses. */ function getRegisteredValidatorGroups() external view returns (address[] memory) { return registeredGroups; } /** * @notice Returns whether a particular account has a registered validator group. * @param account The account. * @return Whether a particular address is a registered validator group. */ function isValidatorGroup(address account) public view returns (bool) { return groups[account].exists; } /** * @notice Returns whether a particular account has a registered validator. * @param account The account. * @return Whether a particular address is a registered validator. */ function isValidator(address account) public view returns (bool) { return validators[account].publicKeys.bls.length > 0; } /** * @notice Deletes an element from a list of addresses. * @param list The list of addresses. * @param element The address to delete. * @param index The index of `element` in the list. */ function deleteElement(address[] storage list, address element, uint256 index) private { require(index < list.length && list[index] == element, "deleteElement: index out of range"); uint256 lastIndex = list.length.sub(1); list[index] = list[lastIndex]; delete list[lastIndex]; list.length = lastIndex; } /** * @notice Removes a member from a validator group. * @param group The group from which the member should be removed. * @param validator The validator to remove from the group. * @return True upon success. * @dev If `validator` was the only member of `group`, `group` becomes unelectable. * @dev Fails if `validator` is not a member of `group`. */ function _removeMember(address group, address validator) private returns (bool) { ValidatorGroup storage _group = groups[group]; require(validators[validator].affiliation == group, "Not affiliated to group"); require(_group.members.contains(validator), "Not a member of the group"); _group.members.remove(validator); uint256 numMembers = _group.members.numElements; // Empty validator groups are not electable. if (numMembers == 0) { getElection().markGroupIneligible(group); } updateMembershipHistory(validator, address(0)); updateSizeHistory(group, numMembers.add(1)); emit ValidatorGroupMemberRemoved(group, validator); return true; } /** * @notice Updates the group membership history of a particular account. * @param account The account whose group membership has changed. * @param group The group that the account is now a member of. * @return True upon success. * @dev Note that this is used to determine a validator's membership at the time of an election, * and so group changes within an epoch will overwrite eachother. */ function updateMembershipHistory(address account, address group) private returns (bool) { MembershipHistory storage history = validators[account].membershipHistory; uint256 epochNumber = getEpochNumber(); uint256 head = history.numEntries == 0 ? 0 : history.tail.add(history.numEntries.sub(1)); if (history.numEntries > 0 && group == address(0)) { history.lastRemovedFromGroupTimestamp = now; } if (history.numEntries > 0 && history.entries[head].epochNumber == epochNumber) { // There have been no elections since the validator last changed membership, overwrite the // previous entry. history.entries[head] = MembershipHistoryEntry(epochNumber, group); return true; } // There have been elections since the validator last changed membership, create a new entry. uint256 index = history.numEntries == 0 ? 0 : head.add(1); history.entries[index] = MembershipHistoryEntry(epochNumber, group); if (history.numEntries < membershipHistoryLength) { // Not enough entries, don't remove any. history.numEntries = history.numEntries.add(1); } else if (history.numEntries == membershipHistoryLength) { // Exactly enough entries, delete the oldest one to account for the one we added. delete history.entries[history.tail]; history.tail = history.tail.add(1); } else { // Too many entries, delete the oldest two to account for the one we added. delete history.entries[history.tail]; delete history.entries[history.tail.add(1)]; history.numEntries = history.numEntries.sub(1); history.tail = history.tail.add(2); } return true; } /** * @notice Updates the size history of a validator group. * @param group The account whose group size has changed. * @param size The new size of the group. * @dev Used to determine how much gold an account needs to keep locked. */ function updateSizeHistory(address group, uint256 size) private { uint256[] storage sizeHistory = groups[group].sizeHistory; if (size == sizeHistory.length) { sizeHistory.push(now); } else if (size < sizeHistory.length) { sizeHistory[size] = now; } else { require(false, "Unable to update size history"); } } /** * @notice Returns the group that `account` was a member of at the end of the last epoch. * @param signer The signer of the account whose group membership should be returned. * @return The group that `account` was a member of at the end of the last epoch. */ function getMembershipInLastEpochFromSigner(address signer) external view returns (address) { address account = getAccounts().signerToAccount(signer); require(isValidator(account), "Not a validator"); return getMembershipInLastEpoch(account); } /** * @notice Returns the group that `account` was a member of at the end of the last epoch. * @param account The account whose group membership should be returned. * @return The group that `account` was a member of at the end of the last epoch. */ function getMembershipInLastEpoch(address account) public view returns (address) { uint256 epochNumber = getEpochNumber(); MembershipHistory storage history = validators[account].membershipHistory; uint256 head = history.numEntries == 0 ? 0 : history.tail.add(history.numEntries.sub(1)); // If the most recent entry in the membership history is for the current epoch number, we need // to look at the previous entry. if (history.entries[head].epochNumber == epochNumber) { if (head > history.tail) { head = head.sub(1); } } return history.entries[head].group; } /** * @notice De-affiliates a validator, removing it from the group for which it is a member. * @param validator The validator to deaffiliate from their affiliated validator group. * @param validatorAccount The LockedGold account of the validator. * @return True upon success. */ function _deaffiliate(Validator storage validator, address validatorAccount) private returns (bool) { address affiliation = validator.affiliation; ValidatorGroup storage group = groups[affiliation]; if (group.members.contains(validatorAccount)) { _removeMember(affiliation, validatorAccount); } validator.affiliation = address(0); emit ValidatorDeaffiliated(validatorAccount, affiliation); return true; } /** * @notice Removes a validator from the group for which it is a member. * @param validatorAccount The validator to deaffiliate from their affiliated validator group. */ function forceDeaffiliateIfValidator(address validatorAccount) external nonReentrant onlySlasher { if (isValidator(validatorAccount)) { Validator storage validator = validators[validatorAccount]; if (validator.affiliation != address(0)) { _deaffiliate(validator, validatorAccount); } } } /** * @notice Sets the slashingMultiplierRestPeriod property if called by owner. * @param value New reset period for slashing multiplier. */ function setSlashingMultiplierResetPeriod(uint256 value) public nonReentrant onlyOwner { slashingMultiplierResetPeriod = value; } /** * @notice Sets the downtimeGracePeriod property if called by owner. * @param value New downtime grace period for calculating epoch scores. */ function setDowntimeGracePeriod(uint256 value) public nonReentrant onlyOwner { downtimeGracePeriod = value; } /** * @notice Resets a group's slashing multiplier if it has been >= the reset period since * the last time the group was slashed. */ function resetSlashingMultiplier() external nonReentrant { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidatorGroup(account), "Not a validator group"); ValidatorGroup storage group = groups[account]; require( now >= group.slashInfo.lastSlashed.add(slashingMultiplierResetPeriod), "`resetSlashingMultiplier` called before resetPeriod expired" ); group.slashInfo.multiplier = FixidityLib.fixed1(); } /** * @notice Halves the group's slashing multiplier. * @param account The group being slashed. */ function halveSlashingMultiplier(address account) external nonReentrant onlySlasher { require(isValidatorGroup(account), "Not a validator group"); ValidatorGroup storage group = groups[account]; group.slashInfo.multiplier = FixidityLib.wrap(group.slashInfo.multiplier.unwrap().div(2)); group.slashInfo.lastSlashed = now; } /** * @notice Getter for a group's slashing multiplier. * @param account The group to fetch slashing multiplier for. */ function getValidatorGroupSlashingMultiplier(address account) external view returns (uint256) { require(isValidatorGroup(account), "Not a validator group"); ValidatorGroup storage group = groups[account]; return group.slashInfo.multiplier.unwrap(); } /** * @notice Returns the group that `account` was a member of during `epochNumber`. * @param account The account whose group membership should be returned. * @param epochNumber The epoch number we are querying this account's membership at. * @param index The index into the validator's history struct for their history at `epochNumber`. * @return The group that `account` was a member of during `epochNumber`. */ function groupMembershipInEpoch(address account, uint256 epochNumber, uint256 index) external view returns (address) { require(isValidator(account), "Not a validator"); require(epochNumber <= getEpochNumber(), "Epoch cannot be larger than current"); MembershipHistory storage history = validators[account].membershipHistory; require(index < history.tail.add(history.numEntries), "index out of bounds"); require(index >= history.tail && history.numEntries > 0, "index out of bounds"); bool isExactMatch = history.entries[index].epochNumber == epochNumber; bool isLastEntry = index.sub(history.tail) == history.numEntries.sub(1); bool isWithinRange = history.entries[index].epochNumber < epochNumber && (history.entries[index.add(1)].epochNumber > epochNumber || isLastEntry); require( isExactMatch || isWithinRange, "provided index does not match provided epochNumber at index in history." ); return history.entries[index].group; } }
Adds a member to the end of a validator group's list of members. validator The validator to add to the group return True upon success. Fails if `validator` has not set their affiliation to this account. Fails if the group has zero members./
function addMember(address validator) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(groups[account].members.numElements > 0, "Validator group empty"); return _addMember(account, validator, address(0), address(0)); }
905,901
./partial_match/1/0x8a3515f5D127342fcBba56E13514D4A2391327e6/sources/contracts/protocol/tokenization/NTokenStakefish.sol
@inheritdoc INTokenStakefish
function claimFeePool( uint256[] calldata tokenIds, uint256[] calldata amountsRequested, address to ) external nonReentrant { require( tokenIds.length == amountsRequested.length, Errors.INCONSISTENT_PARAMS_LENGTH ); uint256 beforeBalance = address(this).balance; for (uint256 index = 0; index < tokenIds.length; index++) { require( msg.sender == _ERC721Data.owners[tokenIds[index]], Errors.NOT_THE_OWNER ); address validatorAddr = _getValidatorAddr(tokenIds[index]); IStakefishValidator(validatorAddr).claimFeePool( amountsRequested[index] ); } uint256 diff = address(this).balance - beforeBalance; if (diff > 0) { POOL.supply(address(WETH), diff, to, 0); } }
4,312,004
/** * SPDX-License-Identifier: UNLICENSED */ pragma solidity =0.6.10; pragma experimental ABIEncoderV2; // File: contracts/packages/oz/upgradeability/Initializable.sol /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: contracts/packages/oz/upgradeability/GSN/ContextUpgradeable.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; } // File: contracts/packages/oz/upgradeability/OwnableUpgradeSafe.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 OwnableUpgradeSafe 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(address _sender) internal initializer { __Context_init_unchained(); __Ownable_init_unchained(_sender); } function __Ownable_init_unchained(address _sender) internal initializer { _owner = _sender; emit OwnershipTransferred(address(0), _sender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File: contracts/packages/oz/upgradeability/ReentrancyGuardUpgradeSafe.sol /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuardUpgradeSafe is Initializable { bool private _notEntered; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { // 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; } uint256[49] private __gap; } // File: contracts/packages/oz/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/libs/MarginVault.sol /** * MarginVault Error Codes * V1: invalid short otoken amount * V2: invalid short otoken index * V3: short otoken address mismatch * V4: invalid long otoken amount * V5: invalid long otoken index * V6: long otoken address mismatch * V7: invalid collateral amount * V8: invalid collateral token index * V9: collateral token address mismatch */ /** * @title MarginVault * @author Opyn Team * @notice A library that provides the Controller with a Vault struct and the functions that manipulate vaults. * Vaults describe discrete position combinations of long options, short options, and collateral assets that a user can have. */ library MarginVault { using SafeMath for uint256; // vault is a struct of 6 arrays that describe a position a user has, a user can have multiple vaults. struct Vault { // addresses of oTokens a user has shorted (i.e. written) against this vault address[] shortOtokens; // addresses of oTokens a user has bought and deposited in this vault // user can be long oTokens without opening a vault (e.g. by buying on a DEX) // generally, long oTokens will be 'deposited' in vaults to act as collateral in order to write oTokens against (i.e. in spreads) address[] longOtokens; // addresses of other ERC-20s a user has deposited as collateral in this vault address[] collateralAssets; // quantity of oTokens minted/written for each oToken address in shortOtokens uint256[] shortAmounts; // quantity of oTokens owned and held in the vault for each oToken address in longOtokens uint256[] longAmounts; // quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets uint256[] collateralAmounts; } /** * @dev increase the short oToken balance in a vault when a new oToken is minted * @param _vault vault to add or increase the short position in * @param _shortOtoken address of the _shortOtoken being minted from the user's vault * @param _amount number of _shortOtoken being minted from the user's vault * @param _index index of _shortOtoken in the user's vault.shortOtokens array */ function addShort( Vault storage _vault, address _shortOtoken, uint256 _amount, uint256 _index ) external { require(_amount > 0, "V1"); // valid indexes in any array are between 0 and array.length - 1. // if adding an amount to an preexisting short oToken, check that _index is in the range of 0->length-1 if ((_index == _vault.shortOtokens.length) && (_index == _vault.shortAmounts.length)) { _vault.shortOtokens.push(_shortOtoken); _vault.shortAmounts.push(_amount); } else { require((_index < _vault.shortOtokens.length) && (_index < _vault.shortAmounts.length), "V2"); address existingShort = _vault.shortOtokens[_index]; require((existingShort == _shortOtoken) || (existingShort == address(0)), "V3"); _vault.shortAmounts[_index] = _vault.shortAmounts[_index].add(_amount); _vault.shortOtokens[_index] = _shortOtoken; } } /** * @dev decrease the short oToken balance in a vault when an oToken is burned * @param _vault vault to decrease short position in * @param _shortOtoken address of the _shortOtoken being reduced in the user's vault * @param _amount number of _shortOtoken being reduced in the user's vault * @param _index index of _shortOtoken in the user's vault.shortOtokens array */ function removeShort( Vault storage _vault, address _shortOtoken, uint256 _amount, uint256 _index ) external { // check that the removed short oToken exists in the vault at the specified index require(_index < _vault.shortOtokens.length, "V2"); require(_vault.shortOtokens[_index] == _shortOtoken, "V3"); uint256 newShortAmount = _vault.shortAmounts[_index].sub(_amount); if (newShortAmount == 0) { delete _vault.shortOtokens[_index]; } _vault.shortAmounts[_index] = newShortAmount; } /** * @dev increase the long oToken balance in a vault when an oToken is deposited * @param _vault vault to add a long position to * @param _longOtoken address of the _longOtoken being added to the user's vault * @param _amount number of _longOtoken the protocol is adding to the user's vault * @param _index index of _longOtoken in the user's vault.longOtokens array */ function addLong( Vault storage _vault, address _longOtoken, uint256 _amount, uint256 _index ) external { require(_amount > 0, "V4"); // valid indexes in any array are between 0 and array.length - 1. // if adding an amount to an preexisting short oToken, check that _index is in the range of 0->length-1 if ((_index == _vault.longOtokens.length) && (_index == _vault.longAmounts.length)) { _vault.longOtokens.push(_longOtoken); _vault.longAmounts.push(_amount); } else { require((_index < _vault.longOtokens.length) && (_index < _vault.longAmounts.length), "V5"); address existingLong = _vault.longOtokens[_index]; require((existingLong == _longOtoken) || (existingLong == address(0)), "V6"); _vault.longAmounts[_index] = _vault.longAmounts[_index].add(_amount); _vault.longOtokens[_index] = _longOtoken; } } /** * @dev decrease the long oToken balance in a vault when an oToken is withdrawn * @param _vault vault to remove a long position from * @param _longOtoken address of the _longOtoken being removed from the user's vault * @param _amount number of _longOtoken the protocol is removing from the user's vault * @param _index index of _longOtoken in the user's vault.longOtokens array */ function removeLong( Vault storage _vault, address _longOtoken, uint256 _amount, uint256 _index ) external { // check that the removed long oToken exists in the vault at the specified index require(_index < _vault.longOtokens.length, "V5"); require(_vault.longOtokens[_index] == _longOtoken, "V6"); uint256 newLongAmount = _vault.longAmounts[_index].sub(_amount); if (newLongAmount == 0) { delete _vault.longOtokens[_index]; } _vault.longAmounts[_index] = newLongAmount; } /** * @dev increase the collateral balance in a vault * @param _vault vault to add collateral to * @param _collateralAsset address of the _collateralAsset being added to the user's vault * @param _amount number of _collateralAsset being added to the user's vault * @param _index index of _collateralAsset in the user's vault.collateralAssets array */ function addCollateral( Vault storage _vault, address _collateralAsset, uint256 _amount, uint256 _index ) external { require(_amount > 0, "V7"); // valid indexes in any array are between 0 and array.length - 1. // if adding an amount to an preexisting short oToken, check that _index is in the range of 0->length-1 if ((_index == _vault.collateralAssets.length) && (_index == _vault.collateralAmounts.length)) { _vault.collateralAssets.push(_collateralAsset); _vault.collateralAmounts.push(_amount); } else { require((_index < _vault.collateralAssets.length) && (_index < _vault.collateralAmounts.length), "V8"); address existingCollateral = _vault.collateralAssets[_index]; require((existingCollateral == _collateralAsset) || (existingCollateral == address(0)), "V9"); _vault.collateralAmounts[_index] = _vault.collateralAmounts[_index].add(_amount); _vault.collateralAssets[_index] = _collateralAsset; } } /** * @dev decrease the collateral balance in a vault * @param _vault vault to remove collateral from * @param _collateralAsset address of the _collateralAsset being removed from the user's vault * @param _amount number of _collateralAsset being removed from the user's vault * @param _index index of _collateralAsset in the user's vault.collateralAssets array */ function removeCollateral( Vault storage _vault, address _collateralAsset, uint256 _amount, uint256 _index ) external { // check that the removed collateral exists in the vault at the specified index require(_index < _vault.collateralAssets.length, "V8"); require(_vault.collateralAssets[_index] == _collateralAsset, "V9"); uint256 newCollateralAmount = _vault.collateralAmounts[_index].sub(_amount); if (newCollateralAmount == 0) { delete _vault.collateralAssets[_index]; } _vault.collateralAmounts[_index] = newCollateralAmount; } } // File: contracts/libs/Actions.sol /** * @title Actions * @author Opyn Team * @notice A library that provides a ActionArgs struct, sub types of Action structs, and functions to parse ActionArgs into specific Actions. * errorCode * A1 can only parse arguments for open vault actions * A2 cannot open vault for an invalid account * A3 cannot open vault with an invalid type * A4 can only parse arguments for mint actions * A5 cannot mint from an invalid account * A6 can only parse arguments for burn actions * A7 cannot burn from an invalid account * A8 can only parse arguments for deposit actions * A9 cannot deposit to an invalid account * A10 can only parse arguments for withdraw actions * A11 cannot withdraw from an invalid account * A12 cannot withdraw to an invalid account * A13 can only parse arguments for redeem actions * A14 cannot redeem to an invalid account * A15 can only parse arguments for settle vault actions * A16 cannot settle vault for an invalid account * A17 cannot withdraw payout to an invalid account * A18 can only parse arguments for liquidate action * A19 cannot liquidate vault for an invalid account owner * A20 cannot send collateral to an invalid account * A21 cannot parse liquidate action with no round id * A22 can only parse arguments for call actions * A23 target address cannot be address(0) */ library Actions { // possible actions that can be performed enum ActionType { OpenVault, MintShortOption, BurnShortOption, DepositLongOption, WithdrawLongOption, DepositCollateral, WithdrawCollateral, SettleVault, Redeem, Call, Liquidate } struct ActionArgs { // type of action that is being performed on the system ActionType actionType; // address of the account owner address owner; // address which we move assets from or to (depending on the action type) address secondAddress; // asset that is to be transfered address asset; // index of the vault that is to be modified (if any) uint256 vaultId; // amount of asset that is to be transfered uint256 amount; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // any other data that needs to be passed in for arbitrary function calls bytes data; } struct MintArgs { // address of the account owner address owner; // index of the vault from which the asset will be minted uint256 vaultId; // address to which we transfer the minted oTokens address to; // oToken that is to be minted address otoken; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of oTokens that is to be minted uint256 amount; } struct BurnArgs { // address of the account owner address owner; // index of the vault from which the oToken will be burned uint256 vaultId; // address from which we transfer the oTokens address from; // oToken that is to be burned address otoken; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of oTokens that is to be burned uint256 amount; } struct OpenVaultArgs { // address of the account owner address owner; // vault id to create uint256 vaultId; // vault type, 0 for spread/max loss and 1 for naked margin vault uint256 vaultType; } struct DepositArgs { // address of the account owner address owner; // index of the vault to which the asset will be added uint256 vaultId; // address from which we transfer the asset address from; // asset that is to be deposited address asset; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of asset that is to be deposited uint256 amount; } struct RedeemArgs { // address to which we pay out the oToken proceeds address receiver; // oToken that is to be redeemed address otoken; // amount of oTokens that is to be redeemed uint256 amount; } struct WithdrawArgs { // address of the account owner address owner; // index of the vault from which the asset will be withdrawn uint256 vaultId; // address to which we transfer the asset address to; // asset that is to be withdrawn address asset; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of asset that is to be withdrawn uint256 amount; } struct SettleVaultArgs { // address of the account owner address owner; // index of the vault to which is to be settled uint256 vaultId; // address to which we transfer the remaining collateral address to; } struct LiquidateArgs { // address of the vault owner to liquidate address owner; // address of the liquidated collateral receiver address receiver; // vault id to liquidate uint256 vaultId; // amount of debt(otoken) to repay uint256 amount; // chainlink round id uint256 roundId; } struct CallArgs { // address of the callee contract address callee; // data field for external calls bytes data; } /** * @notice parses the passed in action arguments to get the arguments for an open vault action * @param _args general action arguments structure * @return arguments for a open vault action */ function _parseOpenVaultArgs(ActionArgs memory _args) internal pure returns (OpenVaultArgs memory) { require(_args.actionType == ActionType.OpenVault, "A1"); require(_args.owner != address(0), "A2"); // if not _args.data included, vault type will be 0 by default uint256 vaultType; if (_args.data.length == 32) { // decode vault type from _args.data vaultType = abi.decode(_args.data, (uint256)); } // for now we only have 2 vault types require(vaultType < 2, "A3"); return OpenVaultArgs({owner: _args.owner, vaultId: _args.vaultId, vaultType: vaultType}); } /** * @notice parses the passed in action arguments to get the arguments for a mint action * @param _args general action arguments structure * @return arguments for a mint action */ function _parseMintArgs(ActionArgs memory _args) internal pure returns (MintArgs memory) { require(_args.actionType == ActionType.MintShortOption, "A4"); require(_args.owner != address(0), "A5"); return MintArgs({ owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress, otoken: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for a burn action * @param _args general action arguments structure * @return arguments for a burn action */ function _parseBurnArgs(ActionArgs memory _args) internal pure returns (BurnArgs memory) { require(_args.actionType == ActionType.BurnShortOption, "A6"); require(_args.owner != address(0), "A7"); return BurnArgs({ owner: _args.owner, vaultId: _args.vaultId, from: _args.secondAddress, otoken: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for a deposit action * @param _args general action arguments structure * @return arguments for a deposit action */ function _parseDepositArgs(ActionArgs memory _args) internal pure returns (DepositArgs memory) { require( (_args.actionType == ActionType.DepositLongOption) || (_args.actionType == ActionType.DepositCollateral), "A8" ); require(_args.owner != address(0), "A9"); return DepositArgs({ owner: _args.owner, vaultId: _args.vaultId, from: _args.secondAddress, asset: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for a withdraw action * @param _args general action arguments structure * @return arguments for a withdraw action */ function _parseWithdrawArgs(ActionArgs memory _args) internal pure returns (WithdrawArgs memory) { require( (_args.actionType == ActionType.WithdrawLongOption) || (_args.actionType == ActionType.WithdrawCollateral), "A10" ); require(_args.owner != address(0), "A11"); require(_args.secondAddress != address(0), "A12"); return WithdrawArgs({ owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress, asset: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for an redeem action * @param _args general action arguments structure * @return arguments for a redeem action */ function _parseRedeemArgs(ActionArgs memory _args) internal pure returns (RedeemArgs memory) { require(_args.actionType == ActionType.Redeem, "A13"); require(_args.secondAddress != address(0), "A14"); return RedeemArgs({receiver: _args.secondAddress, otoken: _args.asset, amount: _args.amount}); } /** * @notice parses the passed in action arguments to get the arguments for a settle vault action * @param _args general action arguments structure * @return arguments for a settle vault action */ function _parseSettleVaultArgs(ActionArgs memory _args) internal pure returns (SettleVaultArgs memory) { require(_args.actionType == ActionType.SettleVault, "A15"); require(_args.owner != address(0), "A16"); require(_args.secondAddress != address(0), "A17"); return SettleVaultArgs({owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress}); } function _parseLiquidateArgs(ActionArgs memory _args) internal pure returns (LiquidateArgs memory) { require(_args.actionType == ActionType.Liquidate, "A18"); require(_args.owner != address(0), "A19"); require(_args.secondAddress != address(0), "A20"); require(_args.data.length == 32, "A21"); // decode chainlink round id from _args.data uint256 roundId = abi.decode(_args.data, (uint256)); return LiquidateArgs({ owner: _args.owner, receiver: _args.secondAddress, vaultId: _args.vaultId, amount: _args.amount, roundId: roundId }); } /** * @notice parses the passed in action arguments to get the arguments for a call action * @param _args general action arguments structure * @return arguments for a call action */ function _parseCallArgs(ActionArgs memory _args) internal pure returns (CallArgs memory) { require(_args.actionType == ActionType.Call, "A22"); require(_args.secondAddress != address(0), "A23"); return CallArgs({callee: _args.secondAddress, data: _args.data}); } } // File: contracts/interfaces/AddressBookInterface.sol interface AddressBookInterface { /* Getters */ function getOtokenImpl() external view returns (address); function getOtokenFactory() external view returns (address); function getWhitelist() external view returns (address); function getController() external view returns (address); function getOracle() external view returns (address); function getMarginPool() external view returns (address); function getMarginCalculator() external view returns (address); function getLiquidationManager() external view returns (address); function getAddress(bytes32 _id) external view returns (address); /* Setters */ function setOtokenImpl(address _otokenImpl) external; function setOtokenFactory(address _factory) external; function setOracleImpl(address _otokenImpl) external; function setWhitelist(address _whitelist) external; function setController(address _controller) external; function setMarginPool(address _marginPool) external; function setMarginCalculator(address _calculator) external; function setLiquidationManager(address _liquidationManager) external; function setAddress(bytes32 _id, address _newImpl) external; } // File: contracts/interfaces/OtokenInterface.sol interface OtokenInterface { function addressBook() external view returns (address); function underlyingAsset() external view returns (address); function strikeAsset() external view returns (address); function collateralAsset() external view returns (address); function strikePrice() external view returns (uint256); function expiryTimestamp() external view returns (uint256); function isPut() external view returns (bool); function init( address _addressBook, address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external; function getOtokenDetails() external view returns ( address, address, address, uint256, uint256, bool ); function mintOtoken(address account, uint256 amount) external; function burnOtoken(address account, uint256 amount) external; } // File: contracts/interfaces/MarginCalculatorInterface.sol interface MarginCalculatorInterface { function addressBook() external view returns (address); function getExpiredPayoutRate(address _otoken) external view returns (uint256); function getExcessCollateral(MarginVault.Vault calldata _vault, uint256 _vaultType) external view returns (uint256 netValue, bool isExcess); function isLiquidatable( MarginVault.Vault memory _vault, uint256 _vaultType, uint256 _vaultLatestUpdate, uint256 _roundId ) external view returns ( bool, uint256, uint256 ); } // File: contracts/interfaces/OracleInterface.sol interface OracleInterface { function isLockingPeriodOver(address _asset, uint256 _expiryTimestamp) external view returns (bool); function isDisputePeriodOver(address _asset, uint256 _expiryTimestamp) external view returns (bool); function getExpiryPrice(address _asset, uint256 _expiryTimestamp) external view returns (uint256, bool); function getDisputer() external view returns (address); function getPricer(address _asset) external view returns (address); function getPrice(address _asset) external view returns (uint256); function getPricerLockingPeriod(address _pricer) external view returns (uint256); function getPricerDisputePeriod(address _pricer) external view returns (uint256); function getChainlinkRoundData(address _asset, uint80 _roundId) external view returns (uint256, uint256); // Non-view function function setAssetPricer(address _asset, address _pricer) external; function setLockingPeriod(address _pricer, uint256 _lockingPeriod) external; function setDisputePeriod(address _pricer, uint256 _disputePeriod) external; function setExpiryPrice( address _asset, uint256 _expiryTimestamp, uint256 _price ) external; function disputeExpiryPrice( address _asset, uint256 _expiryTimestamp, uint256 _price ) external; function setDisputer(address _disputer) external; } // File: contracts/interfaces/WhitelistInterface.sol interface WhitelistInterface { /* View functions */ function addressBook() external view returns (address); function isWhitelistedProduct( address _underlying, address _strike, address _collateral, bool _isPut ) external view returns (bool); function isWhitelistedCollateral(address _collateral) external view returns (bool); function isWhitelistedOtoken(address _otoken) external view returns (bool); function isWhitelistedCallee(address _callee) external view returns (bool); /* Admin / factory only functions */ function whitelistProduct( address _underlying, address _strike, address _collateral, bool _isPut ) external; function blacklistProduct( address _underlying, address _strike, address _collateral, bool _isPut ) external; function whitelistCollateral(address _collateral) external; function blacklistCollateral(address _collateral) external; function whitelistOtoken(address _otoken) external; function blacklistOtoken(address _otoken) external; function whitelistCallee(address _callee) external; function blacklistCallee(address _callee) external; } // File: contracts/interfaces/MarginPoolInterface.sol interface MarginPoolInterface { /* Getters */ function addressBook() external view returns (address); function farmer() external view returns (address); function getStoredBalance(address _asset) external view returns (uint256); /* Admin-only functions */ function setFarmer(address _farmer) external; function farm( address _asset, address _receiver, uint256 _amount ) external; /* Controller-only functions */ function transferToPool( address _asset, address _user, uint256 _amount ) external; function transferToUser( address _asset, address _user, uint256 _amount ) external; function batchTransferToPool( address[] calldata _asset, address[] calldata _user, uint256[] calldata _amount ) external; function batchTransferToUser( address[] calldata _asset, address[] calldata _user, uint256[] calldata _amount ) external; } // File: contracts/interfaces/CalleeInterface.sol /** * @dev Contract interface that can be called from Controller as a call action. */ interface CalleeInterface { /** * Allows users to send this contract arbitrary data. * @param _sender The msg.sender to Controller * @param _data Arbitrary data given by the sender */ function callFunction(address payable _sender, bytes memory _data) external; } // File: contracts/core/Controller.sol /** * Controller Error Codes * C1: sender is not full pauser * C2: sender is not partial pauser * C3: callee is not a whitelisted address * C4: system is partially paused * C5: system is fully paused * C6: msg.sender is not authorized to run action * C7: invalid addressbook address * C8: invalid owner address * C9: invalid input * C10: fullPauser cannot be set to address zero * C11: partialPauser cannot be set to address zero * C12: can not run actions for different owners * C13: can not run actions on different vaults * C14: invalid final vault state * C15: can not run actions on inexistent vault * C16: cannot deposit long otoken from this address * C17: otoken is not whitelisted to be used as collateral * C18: otoken used as collateral is already expired * C19: can not withdraw an expired otoken * C20: cannot deposit collateral from this address * C21: asset is not whitelisted to be used as collateral * C22: can not withdraw collateral from a vault with an expired short otoken * C23: otoken is not whitelisted to be minted * C24: can not mint expired otoken * C25: cannot burn from this address * C26: can not burn expired otoken * C27: otoken is not whitelisted to be redeemed * C28: can not redeem un-expired otoken * C29: asset prices not finalized yet * C30: can't settle vault with no otoken * C31: can not settle vault with un-expired otoken * C32: can not settle undercollateralized vault * C33: can not liquidate vault * C34: can not leave less than collateral dust * C35: invalid vault id * C36: cap amount should be greater than zero * C37: collateral exceed naked margin cap */ /** * @title Controller * @author Opyn Team * @notice Contract that controls the Gamma Protocol and the interaction of all sub contracts */ contract Controller is Initializable, OwnableUpgradeSafe, ReentrancyGuardUpgradeSafe { using MarginVault for MarginVault.Vault; using SafeMath for uint256; AddressBookInterface public addressbook; WhitelistInterface public whitelist; OracleInterface public oracle; MarginCalculatorInterface public calculator; MarginPoolInterface public pool; ///@dev scale used in MarginCalculator uint256 internal constant BASE = 8; /// @notice address that has permission to partially pause the system, where system functionality is paused /// except redeem and settleVault address public partialPauser; /// @notice address that has permission to fully pause the system, where all system functionality is paused address public fullPauser; /// @notice True if all system functionality is paused other than redeem and settle vault bool public systemPartiallyPaused; /// @notice True if all system functionality is paused bool public systemFullyPaused; /// @notice True if a call action can only be executed to a whitelisted callee bool public callRestricted; /// @dev mapping between an owner address and the number of owner address vaults mapping(address => uint256) internal accountVaultCounter; /// @dev mapping between an owner address and a specific vault using a vault id mapping(address => mapping(uint256 => MarginVault.Vault)) internal vaults; /// @dev mapping between an account owner and their approved or unapproved account operators mapping(address => mapping(address => bool)) internal operators; /******************************************************************** V2.0.0 storage upgrade ******************************************************/ /// @dev mapping to map vault by each vault type, naked margin vault should be set to 1, spread/max loss vault should be set to 0 mapping(address => mapping(uint256 => uint256)) internal vaultType; /// @dev mapping to store the timestamp at which the vault was last updated, will be updated in every action that changes the vault state or when calling sync() mapping(address => mapping(uint256 => uint256)) internal vaultLatestUpdate; /// @dev mapping to store cap amount for naked margin vault per options collateral asset (scaled by collateral asset decimals) mapping(address => uint256) internal nakedCap; /// @dev mapping to store amount of naked margin vaults in pool mapping(address => uint256) internal nakedPoolBalance; /// @notice emits an event when an account operator is updated for a specific account owner event AccountOperatorUpdated(address indexed accountOwner, address indexed operator, bool isSet); /// @notice emits an event when a new vault is opened event VaultOpened(address indexed accountOwner, uint256 vaultId, uint256 indexed vaultType); /// @notice emits an event when a long oToken is deposited into a vault event LongOtokenDeposited( address indexed otoken, address indexed accountOwner, address indexed from, uint256 vaultId, uint256 amount ); /// @notice emits an event when a long oToken is withdrawn from a vault event LongOtokenWithdrawed( address indexed otoken, address indexed AccountOwner, address indexed to, uint256 vaultId, uint256 amount ); /// @notice emits an event when a collateral asset is deposited into a vault event CollateralAssetDeposited( address indexed asset, address indexed accountOwner, address indexed from, uint256 vaultId, uint256 amount ); /// @notice emits an event when a collateral asset is withdrawn from a vault event CollateralAssetWithdrawed( address indexed asset, address indexed AccountOwner, address indexed to, uint256 vaultId, uint256 amount ); /// @notice emits an event when a short oToken is minted from a vault event ShortOtokenMinted( address indexed otoken, address indexed AccountOwner, address indexed to, uint256 vaultId, uint256 amount ); /// @notice emits an event when a short oToken is burned event ShortOtokenBurned( address indexed otoken, address indexed AccountOwner, address indexed from, uint256 vaultId, uint256 amount ); /// @notice emits an event when an oToken is redeemed event Redeem( address indexed otoken, address indexed redeemer, address indexed receiver, address collateralAsset, uint256 otokenBurned, uint256 payout ); /// @notice emits an event when a vault is settled event VaultSettled( address indexed accountOwner, address indexed oTokenAddress, address to, uint256 payout, uint256 vaultId, uint256 indexed vaultType ); /// @notice emits an event when a vault is liquidated event VaultLiquidated( address indexed liquidator, address indexed receiver, address indexed vaultOwner, uint256 auctionPrice, uint256 auctionStartingRound, uint256 collateralPayout, uint256 debtAmount, uint256 vaultId ); /// @notice emits an event when a call action is executed event CallExecuted(address indexed from, address indexed to, bytes data); /// @notice emits an event when the fullPauser address changes event FullPauserUpdated(address indexed oldFullPauser, address indexed newFullPauser); /// @notice emits an event when the partialPauser address changes event PartialPauserUpdated(address indexed oldPartialPauser, address indexed newPartialPauser); /// @notice emits an event when the system partial paused status changes event SystemPartiallyPaused(bool isPaused); /// @notice emits an event when the system fully paused status changes event SystemFullyPaused(bool isPaused); /// @notice emits an event when the call action restriction changes event CallRestricted(bool isRestricted); /// @notice emits an event when a donation transfer executed event Donated(address indexed donator, address indexed asset, uint256 amount); /// @notice emits an event when naked cap is updated event NakedCapUpdated(address indexed collateral, uint256 cap); /** * @notice modifier to check if the system is not partially paused, where only redeem and settleVault is allowed */ modifier notPartiallyPaused() { _isNotPartiallyPaused(); _; } /** * @notice modifier to check if the system is not fully paused, where no functionality is allowed */ modifier notFullyPaused() { _isNotFullyPaused(); _; } /** * @notice modifier to check if sender is the fullPauser address */ modifier onlyFullPauser() { require(msg.sender == fullPauser, "C1"); _; } /** * @notice modifier to check if the sender is the partialPauser address */ modifier onlyPartialPauser() { require(msg.sender == partialPauser, "C2"); _; } /** * @notice modifier to check if the sender is the account owner or an approved account operator * @param _sender sender address * @param _accountOwner account owner address */ modifier onlyAuthorized(address _sender, address _accountOwner) { _isAuthorized(_sender, _accountOwner); _; } /** * @notice modifier to check if the called address is a whitelisted callee address * @param _callee called address */ modifier onlyWhitelistedCallee(address _callee) { if (callRestricted) { require(_isCalleeWhitelisted(_callee), "C3"); } _; } /** * @dev check if the system is not in a partiallyPaused state */ function _isNotPartiallyPaused() internal view { require(!systemPartiallyPaused, "C4"); } /** * @dev check if the system is not in an fullyPaused state */ function _isNotFullyPaused() internal view { require(!systemFullyPaused, "C5"); } /** * @dev check if the sender is an authorized operator * @param _sender msg.sender * @param _accountOwner owner of a vault */ function _isAuthorized(address _sender, address _accountOwner) internal view { require((_sender == _accountOwner) || (operators[_accountOwner][_sender]), "C6"); } /** * @notice initalize the deployed contract * @param _addressBook addressbook module * @param _owner account owner address */ function initialize(address _addressBook, address _owner) external initializer { require(_addressBook != address(0), "C7"); require(_owner != address(0), "C8"); __Ownable_init(_owner); __ReentrancyGuard_init_unchained(); addressbook = AddressBookInterface(_addressBook); _refreshConfigInternal(); callRestricted = true; } /** * @notice send asset amount to margin pool * @dev use donate() instead of direct transfer() to store the balance in assetBalance * @param _asset asset address * @param _amount amount to donate to pool */ function donate(address _asset, uint256 _amount) external { pool.transferToPool(_asset, msg.sender, _amount); emit Donated(msg.sender, _asset, _amount); } /** * @notice allows the partialPauser to toggle the systemPartiallyPaused variable and partially pause or partially unpause the system * @dev can only be called by the partialPauser * @param _partiallyPaused new boolean value to set systemPartiallyPaused to */ function setSystemPartiallyPaused(bool _partiallyPaused) external onlyPartialPauser { require(systemPartiallyPaused != _partiallyPaused, "C9"); systemPartiallyPaused = _partiallyPaused; emit SystemPartiallyPaused(systemPartiallyPaused); } /** * @notice allows the fullPauser to toggle the systemFullyPaused variable and fully pause or fully unpause the system * @dev can only be called by the fullyPauser * @param _fullyPaused new boolean value to set systemFullyPaused to */ function setSystemFullyPaused(bool _fullyPaused) external onlyFullPauser { require(systemFullyPaused != _fullyPaused, "C9"); systemFullyPaused = _fullyPaused; emit SystemFullyPaused(systemFullyPaused); } /** * @notice allows the owner to set the fullPauser address * @dev can only be called by the owner * @param _fullPauser new fullPauser address */ function setFullPauser(address _fullPauser) external onlyOwner { require(_fullPauser != address(0), "C10"); require(fullPauser != _fullPauser, "C9"); emit FullPauserUpdated(fullPauser, _fullPauser); fullPauser = _fullPauser; } /** * @notice allows the owner to set the partialPauser address * @dev can only be called by the owner * @param _partialPauser new partialPauser address */ function setPartialPauser(address _partialPauser) external onlyOwner { require(_partialPauser != address(0), "C11"); require(partialPauser != _partialPauser, "C9"); emit PartialPauserUpdated(partialPauser, _partialPauser); partialPauser = _partialPauser; } /** * @notice allows the owner to toggle the restriction on whitelisted call actions and only allow whitelisted * call addresses or allow any arbitrary call addresses * @dev can only be called by the owner * @param _isRestricted new call restriction state */ function setCallRestriction(bool _isRestricted) external onlyOwner { require(callRestricted != _isRestricted, "C9"); callRestricted = _isRestricted; emit CallRestricted(callRestricted); } /** * @notice allows a user to give or revoke privileges to an operator which can act on their behalf on their vaults * @dev can only be updated by the vault owner * @param _operator operator that the sender wants to give privileges to or revoke them from * @param _isOperator new boolean value that expresses if the sender is giving or revoking privileges for _operator */ function setOperator(address _operator, bool _isOperator) external { require(operators[msg.sender][_operator] != _isOperator, "C9"); operators[msg.sender][_operator] = _isOperator; emit AccountOperatorUpdated(msg.sender, _operator, _isOperator); } /** * @dev updates the configuration of the controller. can only be called by the owner */ function refreshConfiguration() external onlyOwner { _refreshConfigInternal(); } /** * @notice set cap amount for collateral asset used in naked margin * @dev can only be called by owner * @param _collateral collateral asset address * @param _cap cap amount, should be scaled by collateral asset decimals */ function setNakedCap(address _collateral, uint256 _cap) external onlyOwner { require(_cap > 0, "C36"); nakedCap[_collateral] = _cap; emit NakedCapUpdated(_collateral, _cap); } /** * @notice execute a number of actions on specific vaults * @dev can only be called when the system is not fully paused * @param _actions array of actions arguments */ function operate(Actions.ActionArgs[] memory _actions) external nonReentrant notFullyPaused { (bool vaultUpdated, address vaultOwner, uint256 vaultId) = _runActions(_actions); if (vaultUpdated) { _verifyFinalState(vaultOwner, vaultId); vaultLatestUpdate[vaultOwner][vaultId] = now; } } /** * @notice sync vault latest update timestamp * @dev anyone can update the latest time the vault was touched by calling this function * vaultLatestUpdate will sync if the vault is well collateralized * @param _owner vault owner address * @param _vaultId vault id */ function sync(address _owner, uint256 _vaultId) external nonReentrant notFullyPaused { _verifyFinalState(_owner, _vaultId); vaultLatestUpdate[_owner][_vaultId] = now; } /** * @notice check if a specific address is an operator for an owner account * @param _owner account owner address * @param _operator account operator address * @return True if the _operator is an approved operator for the _owner account */ function isOperator(address _owner, address _operator) external view returns (bool) { return operators[_owner][_operator]; } /** * @notice returns the current controller configuration * @return whitelist, the address of the whitelist module * @return oracle, the address of the oracle module * @return calculator, the address of the calculator module * @return pool, the address of the pool module */ function getConfiguration() external view returns ( address, address, address, address ) { return (address(whitelist), address(oracle), address(calculator), address(pool)); } /** * @notice return a vault's proceeds pre or post expiry, the amount of collateral that can be removed from a vault * @param _owner account owner of the vault * @param _vaultId vaultId to return balances for * @return amount of collateral that can be taken out */ function getProceed(address _owner, uint256 _vaultId) external view returns (uint256) { (MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_owner, _vaultId); (uint256 netValue, bool isExcess) = calculator.getExcessCollateral(vault, typeVault); if (!isExcess) return 0; return netValue; } /** * @notice check if a vault is liquidatable in a specific round id * @param _owner vault owner address * @param _vaultId vault id to check * @param _roundId chainlink round id to check vault status at * @return isUnderCollat, true if vault is undercollateralized, the price of 1 repaid otoken and the otoken collateral dust amount */ function isLiquidatable( address _owner, uint256 _vaultId, uint256 _roundId ) external view returns ( bool, uint256, uint256 ) { (, bool isUnderCollat, uint256 price, uint256 dust) = _isLiquidatable(_owner, _vaultId, _roundId); return (isUnderCollat, price, dust); } /** * @notice get an oToken's payout/cash value after expiry, in the collateral asset * @param _otoken oToken address * @param _amount amount of the oToken to calculate the payout for, always represented in 1e8 * @return amount of collateral to pay out */ function getPayout(address _otoken, uint256 _amount) public view returns (uint256) { return calculator.getExpiredPayoutRate(_otoken).mul(_amount).div(10**BASE); } /** * @dev return if an expired oToken is ready to be settled, only true when price for underlying, * strike and collateral assets at this specific expiry is available in our Oracle module * @param _otoken oToken */ function isSettlementAllowed(address _otoken) external view returns (bool) { (address underlying, address strike, address collateral, uint256 expiry) = _getOtokenDetails(_otoken); return _canSettleAssets(underlying, strike, collateral, expiry); } /** * @dev return if underlying, strike, collateral are all allowed to be settled * @param _underlying oToken underlying asset * @param _strike oToken strike asset * @param _collateral oToken collateral asset * @param _expiry otoken expiry timestamp * @return True if the oToken has expired AND all oracle prices at the expiry timestamp have been finalized, False if not */ function canSettleAssets( address _underlying, address _strike, address _collateral, uint256 _expiry ) external view returns (bool) { return _canSettleAssets(_underlying, _strike, _collateral, _expiry); } /** * @notice get the number of vaults for a specified account owner * @param _accountOwner account owner address * @return number of vaults */ function getAccountVaultCounter(address _accountOwner) external view returns (uint256) { return accountVaultCounter[_accountOwner]; } /** * @notice check if an oToken has expired * @param _otoken oToken address * @return True if the otoken has expired, False if not */ function hasExpired(address _otoken) external view returns (bool) { return now >= OtokenInterface(_otoken).expiryTimestamp(); } /** * @notice return a specific vault * @param _owner account owner * @param _vaultId vault id of vault to return * @return Vault struct that corresponds to the _vaultId of _owner */ function getVault(address _owner, uint256 _vaultId) external view returns (MarginVault.Vault memory) { return (vaults[_owner][_vaultId]); } /** * @notice return a specific vault * @param _owner account owner * @param _vaultId vault id of vault to return * @return Vault struct that corresponds to the _vaultId of _owner, vault type and the latest timestamp when the vault was updated */ function getVaultWithDetails(address _owner, uint256 _vaultId) public view returns ( MarginVault.Vault memory, uint256, uint256 ) { return (vaults[_owner][_vaultId], vaultType[_owner][_vaultId], vaultLatestUpdate[_owner][_vaultId]); } /** * @notice get cap amount for collateral asset * @param _asset collateral asset address * @return cap amount */ function getNakedCap(address _asset) external view returns (uint256) { return nakedCap[_asset]; } /** * @notice get amount of collateral deposited in all naked margin vaults * @param _asset collateral asset address * @return naked pool balance */ function getNakedPoolBalance(address _asset) external view returns (uint256) { return nakedPoolBalance[_asset]; } /** * @notice execute a variety of actions * @dev for each action in the action array, execute the corresponding action, only one vault can be modified * for all actions except SettleVault, Redeem, and Call * @param _actions array of type Actions.ActionArgs[], which expresses which actions the user wants to execute * @return vaultUpdated, indicates if a vault has changed * @return owner, the vault owner if a vault has changed * @return vaultId, the vault Id if a vault has changed */ function _runActions(Actions.ActionArgs[] memory _actions) internal returns ( bool, address, uint256 ) { address vaultOwner; uint256 vaultId; bool vaultUpdated; for (uint256 i = 0; i < _actions.length; i++) { Actions.ActionArgs memory action = _actions[i]; Actions.ActionType actionType = action.actionType; // actions except Settle, Redeem, Liquidate and Call are "Vault-updating actinos" // only allow update 1 vault in each operate call if ( (actionType != Actions.ActionType.SettleVault) && (actionType != Actions.ActionType.Redeem) && (actionType != Actions.ActionType.Liquidate) && (actionType != Actions.ActionType.Call) ) { // check if this action is manipulating the same vault as all other actions, if a vault has already been updated if (vaultUpdated) { require(vaultOwner == action.owner, "C12"); require(vaultId == action.vaultId, "C13"); } vaultUpdated = true; vaultId = action.vaultId; vaultOwner = action.owner; } if (actionType == Actions.ActionType.OpenVault) { _openVault(Actions._parseOpenVaultArgs(action)); } else if (actionType == Actions.ActionType.DepositLongOption) { _depositLong(Actions._parseDepositArgs(action)); } else if (actionType == Actions.ActionType.WithdrawLongOption) { _withdrawLong(Actions._parseWithdrawArgs(action)); } else if (actionType == Actions.ActionType.DepositCollateral) { _depositCollateral(Actions._parseDepositArgs(action)); } else if (actionType == Actions.ActionType.WithdrawCollateral) { _withdrawCollateral(Actions._parseWithdrawArgs(action)); } else if (actionType == Actions.ActionType.MintShortOption) { _mintOtoken(Actions._parseMintArgs(action)); } else if (actionType == Actions.ActionType.BurnShortOption) { _burnOtoken(Actions._parseBurnArgs(action)); } else if (actionType == Actions.ActionType.Redeem) { _redeem(Actions._parseRedeemArgs(action)); } else if (actionType == Actions.ActionType.SettleVault) { _settleVault(Actions._parseSettleVaultArgs(action)); } else if (actionType == Actions.ActionType.Liquidate) { _liquidate(Actions._parseLiquidateArgs(action)); } else if (actionType == Actions.ActionType.Call) { _call(Actions._parseCallArgs(action)); } } return (vaultUpdated, vaultOwner, vaultId); } /** * @notice verify the vault final state after executing all actions * @param _owner account owner address * @param _vaultId vault id of the final vault */ function _verifyFinalState(address _owner, uint256 _vaultId) internal view { (MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_owner, _vaultId); (, bool isValidVault) = calculator.getExcessCollateral(vault, typeVault); require(isValidVault, "C14"); } /** * @notice open a new vault inside an account * @dev only the account owner or operator can open a vault, cannot be called when system is partiallyPaused or fullyPaused * @param _args OpenVaultArgs structure */ function _openVault(Actions.OpenVaultArgs memory _args) internal notPartiallyPaused onlyAuthorized(msg.sender, _args.owner) { uint256 vaultId = accountVaultCounter[_args.owner].add(1); require(_args.vaultId == vaultId, "C15"); // store new vault accountVaultCounter[_args.owner] = vaultId; vaultType[_args.owner][vaultId] = _args.vaultType; emit VaultOpened(_args.owner, vaultId, _args.vaultType); } /** * @notice deposit a long oToken into a vault * @dev only the account owner or operator can deposit a long oToken, cannot be called when system is partiallyPaused or fullyPaused * @param _args DepositArgs structure */ function _depositLong(Actions.DepositArgs memory _args) internal notPartiallyPaused onlyAuthorized(msg.sender, _args.owner) { require(_checkVaultId(_args.owner, _args.vaultId), "C35"); // only allow vault owner or vault operator to deposit long otoken require((_args.from == msg.sender) || (_args.from == _args.owner), "C16"); require(whitelist.isWhitelistedOtoken(_args.asset), "C17"); OtokenInterface otoken = OtokenInterface(_args.asset); require(now < otoken.expiryTimestamp(), "C18"); vaults[_args.owner][_args.vaultId].addLong(_args.asset, _args.amount, _args.index); pool.transferToPool(_args.asset, _args.from, _args.amount); emit LongOtokenDeposited(_args.asset, _args.owner, _args.from, _args.vaultId, _args.amount); } /** * @notice withdraw a long oToken from a vault * @dev only the account owner or operator can withdraw a long oToken, cannot be called when system is partiallyPaused or fullyPaused * @param _args WithdrawArgs structure */ function _withdrawLong(Actions.WithdrawArgs memory _args) internal notPartiallyPaused onlyAuthorized(msg.sender, _args.owner) { require(_checkVaultId(_args.owner, _args.vaultId), "C35"); OtokenInterface otoken = OtokenInterface(_args.asset); require(now < otoken.expiryTimestamp(), "C19"); vaults[_args.owner][_args.vaultId].removeLong(_args.asset, _args.amount, _args.index); pool.transferToUser(_args.asset, _args.to, _args.amount); emit LongOtokenWithdrawed(_args.asset, _args.owner, _args.to, _args.vaultId, _args.amount); } /** * @notice deposit a collateral asset into a vault * @dev only the account owner or operator can deposit collateral, cannot be called when system is partiallyPaused or fullyPaused * @param _args DepositArgs structure */ function _depositCollateral(Actions.DepositArgs memory _args) internal notPartiallyPaused onlyAuthorized(msg.sender, _args.owner) { require(_checkVaultId(_args.owner, _args.vaultId), "C35"); // only allow vault owner or vault operator to deposit collateral require((_args.from == msg.sender) || (_args.from == _args.owner), "C20"); require(whitelist.isWhitelistedCollateral(_args.asset), "C21"); (, uint256 typeVault, ) = getVaultWithDetails(_args.owner, _args.vaultId); if (typeVault == 1) { nakedPoolBalance[_args.asset] = nakedPoolBalance[_args.asset].add(_args.amount); require(nakedPoolBalance[_args.asset] <= nakedCap[_args.asset], "C37"); } vaults[_args.owner][_args.vaultId].addCollateral(_args.asset, _args.amount, _args.index); pool.transferToPool(_args.asset, _args.from, _args.amount); emit CollateralAssetDeposited(_args.asset, _args.owner, _args.from, _args.vaultId, _args.amount); } /** * @notice withdraw a collateral asset from a vault * @dev only the account owner or operator can withdraw collateral, cannot be called when system is partiallyPaused or fullyPaused * @param _args WithdrawArgs structure */ function _withdrawCollateral(Actions.WithdrawArgs memory _args) internal notPartiallyPaused onlyAuthorized(msg.sender, _args.owner) { require(_checkVaultId(_args.owner, _args.vaultId), "C35"); (MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_args.owner, _args.vaultId); if (_isNotEmpty(vault.shortOtokens)) { OtokenInterface otoken = OtokenInterface(vault.shortOtokens[0]); require(now < otoken.expiryTimestamp(), "C22"); } if (typeVault == 1) { nakedPoolBalance[_args.asset] = nakedPoolBalance[_args.asset].sub(_args.amount); } vaults[_args.owner][_args.vaultId].removeCollateral(_args.asset, _args.amount, _args.index); pool.transferToUser(_args.asset, _args.to, _args.amount); emit CollateralAssetWithdrawed(_args.asset, _args.owner, _args.to, _args.vaultId, _args.amount); } /** * @notice mint short oTokens from a vault which creates an obligation that is recorded in the vault * @dev only the account owner or operator can mint an oToken, cannot be called when system is partiallyPaused or fullyPaused * @param _args MintArgs structure */ function _mintOtoken(Actions.MintArgs memory _args) internal notPartiallyPaused onlyAuthorized(msg.sender, _args.owner) { require(_checkVaultId(_args.owner, _args.vaultId), "C35"); require(whitelist.isWhitelistedOtoken(_args.otoken), "C23"); OtokenInterface otoken = OtokenInterface(_args.otoken); require(now < otoken.expiryTimestamp(), "C24"); vaults[_args.owner][_args.vaultId].addShort(_args.otoken, _args.amount, _args.index); otoken.mintOtoken(_args.to, _args.amount); emit ShortOtokenMinted(_args.otoken, _args.owner, _args.to, _args.vaultId, _args.amount); } /** * @notice burn oTokens to reduce or remove the minted oToken obligation recorded in a vault * @dev only the account owner or operator can burn an oToken, cannot be called when system is partiallyPaused or fullyPaused * @param _args MintArgs structure */ function _burnOtoken(Actions.BurnArgs memory _args) internal notPartiallyPaused onlyAuthorized(msg.sender, _args.owner) { // check that vault id is valid for this vault owner require(_checkVaultId(_args.owner, _args.vaultId), "C35"); // only allow vault owner or vault operator to burn otoken require((_args.from == msg.sender) || (_args.from == _args.owner), "C25"); OtokenInterface otoken = OtokenInterface(_args.otoken); // do not allow burning expired otoken require(now < otoken.expiryTimestamp(), "C26"); // remove otoken from vault vaults[_args.owner][_args.vaultId].removeShort(_args.otoken, _args.amount, _args.index); // burn otoken otoken.burnOtoken(_args.from, _args.amount); emit ShortOtokenBurned(_args.otoken, _args.owner, _args.from, _args.vaultId, _args.amount); } /** * @notice redeem an oToken after expiry, receiving the payout of the oToken in the collateral asset * @dev cannot be called when system is fullyPaused * @param _args RedeemArgs structure */ function _redeem(Actions.RedeemArgs memory _args) internal { OtokenInterface otoken = OtokenInterface(_args.otoken); // check that otoken to redeem is whitelisted require(whitelist.isWhitelistedOtoken(_args.otoken), "C27"); (address collateral, address underlying, address strike, uint256 expiry) = _getOtokenDetails(address(otoken)); // only allow redeeming expired otoken require(now >= expiry, "C28"); require(_canSettleAssets(underlying, strike, collateral, expiry), "C29"); uint256 payout = getPayout(_args.otoken, _args.amount); otoken.burnOtoken(msg.sender, _args.amount); pool.transferToUser(collateral, _args.receiver, payout); emit Redeem(_args.otoken, msg.sender, _args.receiver, collateral, _args.amount, payout); } /** * @notice settle a vault after expiry, removing the net proceeds/collateral after both long and short oToken payouts have settled * @dev deletes a vault of vaultId after net proceeds/collateral is removed, cannot be called when system is fullyPaused * @param _args SettleVaultArgs structure */ function _settleVault(Actions.SettleVaultArgs memory _args) internal onlyAuthorized(msg.sender, _args.owner) { require(_checkVaultId(_args.owner, _args.vaultId), "C35"); (MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_args.owner, _args.vaultId); OtokenInterface otoken; // new scope to avoid stack too deep error // check if there is short or long otoken in vault // do not allow settling vault that have no short or long otoken // if there is a long otoken, burn it // store otoken address outside of this scope { bool hasShort = _isNotEmpty(vault.shortOtokens); bool hasLong = _isNotEmpty(vault.longOtokens); require(hasShort || hasLong, "C30"); otoken = hasShort ? OtokenInterface(vault.shortOtokens[0]) : OtokenInterface(vault.longOtokens[0]); if (hasLong) { OtokenInterface longOtoken = OtokenInterface(vault.longOtokens[0]); longOtoken.burnOtoken(address(pool), vault.longAmounts[0]); } } (address collateral, address underlying, address strike, uint256 expiry) = _getOtokenDetails(address(otoken)); // do not allow settling vault with un-expired otoken require(now >= expiry, "C31"); require(_canSettleAssets(underlying, strike, collateral, expiry), "C29"); (uint256 payout, bool isValidVault) = calculator.getExcessCollateral(vault, typeVault); // require that vault is valid (has excess collateral) before settling // to avoid allowing settling undercollateralized naked margin vault require(isValidVault, "C32"); delete vaults[_args.owner][_args.vaultId]; if (typeVault == 1) { nakedPoolBalance[collateral] = nakedPoolBalance[collateral].sub(payout); } pool.transferToUser(collateral, _args.to, payout); uint256 vaultId = _args.vaultId; address payoutRecipient = _args.to; emit VaultSettled(_args.owner, address(otoken), payoutRecipient, payout, vaultId, typeVault); } /** * @notice liquidate naked margin vault * @dev can liquidate different vaults id in the same operate() call * @param _args liquidation action arguments struct */ function _liquidate(Actions.LiquidateArgs memory _args) internal notPartiallyPaused { require(_checkVaultId(_args.owner, _args.vaultId), "C35"); // check if vault is undercollateralized // the price is the amount of collateral asset to pay per 1 repaid debt(otoken) // collateralDust is the minimum amount of collateral that can be left in the vault when a partial liquidation occurs (MarginVault.Vault memory vault, bool isUnderCollat, uint256 price, uint256 collateralDust) = _isLiquidatable( _args.owner, _args.vaultId, _args.roundId ); require(isUnderCollat, "C33"); // amount of collateral to offer to liquidator uint256 collateralToSell = _args.amount.mul(price).div(1e8); // if vault is partially liquidated (amount of short otoken is still greater than zero) // make sure remaining collateral amount is greater than dust amount if (vault.shortAmounts[0].sub(_args.amount) > 0) { require(vault.collateralAmounts[0].sub(collateralToSell) >= collateralDust, "C34"); } // burn short otoken from liquidator address, index of short otoken hardcoded at 0 // this should always work, if vault have no short otoken, it will not reach this step OtokenInterface(vault.shortOtokens[0]).burnOtoken(msg.sender, _args.amount); // decrease amount of collateral in liquidated vault, index of collateral to decrease is hardcoded at 0 vaults[_args.owner][_args.vaultId].removeCollateral(vault.collateralAssets[0], collateralToSell, 0); // decrease amount of short otoken in liquidated vault, index of short otoken to decrease is hardcoded at 0 vaults[_args.owner][_args.vaultId].removeShort(vault.shortOtokens[0], _args.amount, 0); // decrease internal naked margin collateral amount nakedPoolBalance[vault.collateralAssets[0]] = nakedPoolBalance[vault.collateralAssets[0]].sub(collateralToSell); pool.transferToUser(vault.collateralAssets[0], _args.receiver, collateralToSell); emit VaultLiquidated( msg.sender, _args.receiver, _args.owner, price, _args.roundId, collateralToSell, _args.amount, _args.vaultId ); } /** * @notice execute arbitrary calls * @dev cannot be called when system is partiallyPaused or fullyPaused * @param _args Call action */ function _call(Actions.CallArgs memory _args) internal notPartiallyPaused onlyWhitelistedCallee(_args.callee) { CalleeInterface(_args.callee).callFunction(msg.sender, _args.data); emit CallExecuted(msg.sender, _args.callee, _args.data); } /** * @notice check if a vault id is valid for a given account owner address * @param _accountOwner account owner address * @param _vaultId vault id to check * @return True if the _vaultId is valid, False if not */ function _checkVaultId(address _accountOwner, uint256 _vaultId) internal view returns (bool) { return ((_vaultId > 0) && (_vaultId <= accountVaultCounter[_accountOwner])); } function _isNotEmpty(address[] memory _array) internal pure returns (bool) { return (_array.length > 0) && (_array[0] != address(0)); } /** * @notice return if a callee address is whitelisted or not * @param _callee callee address * @return True if callee address is whitelisted, False if not */ function _isCalleeWhitelisted(address _callee) internal view returns (bool) { return whitelist.isWhitelistedCallee(_callee); } /** * @notice check if a vault is liquidatable in a specific round id * @param _owner vault owner address * @param _vaultId vault id to check * @param _roundId chainlink round id to check vault status at * @return vault struct, isLiquidatable, true if vault is undercollateralized, the price of 1 repaid otoken and the otoken collateral dust amount */ function _isLiquidatable( address _owner, uint256 _vaultId, uint256 _roundId ) internal view returns ( MarginVault.Vault memory, bool, uint256, uint256 ) { (MarginVault.Vault memory vault, uint256 typeVault, uint256 latestUpdateTimestamp) = getVaultWithDetails( _owner, _vaultId ); (bool isUnderCollat, uint256 price, uint256 collateralDust) = calculator.isLiquidatable( vault, typeVault, latestUpdateTimestamp, _roundId ); return (vault, isUnderCollat, price, collateralDust); } /** * @dev get otoken detail, from both otoken versions */ function _getOtokenDetails(address _otoken) internal view returns ( address, address, address, uint256 ) { OtokenInterface otoken = OtokenInterface(_otoken); try otoken.getOtokenDetails() returns ( address collateral, address underlying, address strike, uint256, uint256 expiry, bool ) { return (collateral, underlying, strike, expiry); } catch { return (otoken.collateralAsset(), otoken.underlyingAsset(), otoken.strikeAsset(), otoken.expiryTimestamp()); } } /** * @dev return if an expired oToken is ready to be settled, only true when price for underlying, * strike and collateral assets at this specific expiry is available in our Oracle module * @return True if the oToken has expired AND all oracle prices at the expiry timestamp have been finalized, False if not */ function _canSettleAssets( address _underlying, address _strike, address _collateral, uint256 _expiry ) internal view returns (bool) { return oracle.isDisputePeriodOver(_underlying, _expiry) && oracle.isDisputePeriodOver(_strike, _expiry) && oracle.isDisputePeriodOver(_collateral, _expiry); } /** * @dev updates the internal configuration of the controller */ function _refreshConfigInternal() internal { whitelist = WhitelistInterface(addressbook.getWhitelist()); oracle = OracleInterface(addressbook.getOracle()); calculator = MarginCalculatorInterface(addressbook.getMarginCalculator()); pool = MarginPoolInterface(addressbook.getMarginPool()); } }
return if an expired oToken is ready to be settled, only true when price for underlying, strike and collateral assets at this specific expiry is available in our Oracle module return True if the oToken has expired AND all oracle prices at the expiry timestamp have been finalized, False if not/
function _canSettleAssets( address _underlying, address _strike, address _collateral, uint256 _expiry ) internal view returns (bool) { return oracle.isDisputePeriodOver(_underlying, _expiry) && oracle.isDisputePeriodOver(_strike, _expiry) && oracle.isDisputePeriodOver(_collateral, _expiry); }
6,146,135
./full_match/1/0xb27e1b2c43803fF063184B8ae03791ea36De3B84/sources/src/MembershipManager.sol
Finds the corresponding for the tier points
function tierForPoints(uint40 _tierPoints) public view returns (uint8) { uint8 tierId = 0; while (tierId < tierData.length && _tierPoints >= tierData[tierId].requiredTierPoints) { tierId++; } return tierId - 1; }
4,849,172
pragma solidity ^ 0.5.8; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false mapping(address => bool) private authorizedCallers; // Addresses that can access this contract // data structure to determine an airline struct Airline { address airlineAccount; // account address of airline string name; // name of airline bool isRegistered; // is this airline registered or not bool isFunded; // is this airline funded or not uint256 fund; // amount of fund available } // mapping to store airlines data mapping(address => Airline) private airlines; // number of airlines available uint256 internal airlinesCount = 0; // data structure to determine insurance struct Insurance { address payable insureeAccount; // account address of insuree uint256 amount; // insurance amount address airlineAccount; // account address of airline string airlineName; // name of airline uint256 timestamp; // timestamp of airline } // mapping to store insurances data mapping(bytes32 => Insurance[]) private insurances; // mapping to indicate flights whose payout have been credited mapping(bytes32 => bool) private payoutCredited; // mapping to store credits available for each insuree mapping(address => uint256) private creditPayoutsToInsuree; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ // event to trigger when airline gets registered event AirlineRegistered( address indexed airlineAccount, // account address of airline string airlineName // name of airline ); // event to trigger when airline gets funded event AirlineFunded( address indexed airlineAccount, // account address of airline uint256 amount // amount funded to airline ); // event to trigger when insurance is purchased event InsurancePurchased( address indexed insureeAccount, // account address of insuree uint256 amount, // insurance amount address airlineAccount, // account address of airline string airlineName, // name of airline uint256 timestamp // timestamp of airline ); // event to trigger when insurance credit is available event InsuranceCreditAvailable( address indexed airlineAccount, // account address of airline string indexed airlineName, // name of airline uint256 indexed timestamp // timestamp of airline ); // event to trigger when insurance is credited event InsuranceCredited( address indexed insureeAccount, // account address of insuree uint256 amount // insurance amount ); // event to trigger when insurance is paid event InsurancePaid( address indexed insureeAccount, // account address of insuree uint256 amount // insurance amount ); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor( address _initialAirlineAccount, string memory _initialAirlineName ) public { contractOwner = msg.sender; addAirline(_initialAirlineAccount, _initialAirlineName); } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the caller address either be registered as "authorized" or be the owner of the contract. * This is used to avoid that other accounts may alter this data contract. */ modifier requireIsCallerAuthorized() { require(authorizedCallers[msg.sender] == true || msg.sender == contractOwner, "Caller is not authorized"); _; } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** * @dev Modifier that requires an airline account to be the function caller */ modifier requireIsAirline() { require(airlines[msg.sender].isRegistered == true, "Caller is not airline"); _; } /** * @dev Modifier that requires an airline account to be funded */ modifier requireIsAirlineFunded(address _airlineAccount) { require(airlines[_airlineAccount].isFunded == true, "Airline is not funded"); _; } /** * @dev Modifier that requires message data to be filled */ modifier requireMsgData() { require(msg.data.length > 0, "Message data is empty"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Add a new address to the list of authorized callers * Can only be called by the contract owner */ function authorizeCaller(address contractAddress) external requireContractOwner { authorizedCallers[contractAddress] = true; } /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() external view returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus( bool mode ) external requireContractOwner { operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline( address _airlineAccount, string calldata _airlineName ) external requireIsCallerAuthorized { addAirline(_airlineAccount, _airlineName); } function addAirline( address _airlineAccount, string memory _airlineName ) private { airlinesCount = airlinesCount.add(1); airlines[_airlineAccount] = Airline( _airlineAccount, _airlineName, true, false, 0 ); emit AirlineRegistered(_airlineAccount, _airlineName); } /** * @dev Buy insurance for a flight * */ function buy( address payable _insureeAccount, address _airlineAccount, string calldata _airlineName, uint256 _timestamp ) external payable { bytes32 flightKey = getFlightKey(_airlineAccount, _airlineName, _timestamp); airlines[_airlineAccount].fund = airlines[_airlineAccount].fund.add(msg.value); insurances[flightKey].push( Insurance( _insureeAccount, msg.value, _airlineAccount, _airlineName, _timestamp ) ); emit InsurancePurchased( _insureeAccount, msg.value, _airlineAccount, _airlineName, _timestamp ); } /** * @dev Credits payouts to insurees */ function creditInsurees( uint256 _creditPercentage, address _airlineAccount, string calldata _airlineName, uint256 _timestamp ) external requireIsCallerAuthorized { bytes32 flightKey = getFlightKey(_airlineAccount, _airlineName, _timestamp); require(!payoutCredited[flightKey], "Insurance payout have already been credited"); for (uint i = 0; i < insurances[flightKey].length; i++) { address insureeAccount = insurances[flightKey][i].insureeAccount; uint256 amountToReceive = insurances[flightKey][i].amount.mul(_creditPercentage).div(100); creditPayoutsToInsuree[insureeAccount] = creditPayoutsToInsuree[insureeAccount].add(amountToReceive); airlines[_airlineAccount].fund = airlines[_airlineAccount].fund.sub(amountToReceive); emit InsuranceCredited(insureeAccount, amountToReceive); } payoutCredited[flightKey] = true; emit InsuranceCreditAvailable(_airlineAccount, _airlineName, _timestamp); } /** * @dev Transfers eligible payout funds to insuree * */ function pay( address payable _insureeAccount ) external requireIsCallerAuthorized { uint256 payableAmount = creditPayoutsToInsuree[_insureeAccount]; delete(creditPayoutsToInsuree[_insureeAccount]); _insureeAccount.transfer(payableAmount); emit InsurancePaid(_insureeAccount, payableAmount); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund( address _airlineAccount ) external payable requireIsCallerAuthorized { addFund(_airlineAccount, msg.value); airlines[_airlineAccount].isFunded = true; emit AirlineFunded(_airlineAccount, msg.value); } function addFund( address _airlineAccount, uint256 _fundValue ) private { airlines[_airlineAccount].fund = airlines[_airlineAccount].fund.add(_fundValue); } function getFlightKey( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev check if address is of airline or not * */ function isAirline( address _airlineAccount ) external view returns(bool) { return airlines[_airlineAccount].isRegistered == true; } /** * @dev check if address is of airline or not * */ function isAirlineFunded( address _airlineAccount ) external view requireIsCallerAuthorized returns(bool) { return airlines[_airlineAccount].isFunded == true; } /** * @dev get fund of airline */ function getFund( address _airlineAccount ) external view requireIsCallerAuthorized returns(uint256) { return airlines[_airlineAccount].fund; } /** * @dev check if address is of airline or not * */ function getAirlinesCount() external view returns(uint256) { return airlinesCount; } /** * @dev get amount paid by insuree * */ function getAmountPaidByInsuree( address payable _insureeAccount, address _airlineAccount, string calldata _airlineName, uint256 _timestamp ) external view returns(uint256 amountPaid) { amountPaid = 0; bytes32 flightKey = getFlightKey(_airlineAccount, _airlineName, _timestamp); for (uint i = 0; i < insurances[flightKey].length; i++) { if (insurances[flightKey][i].insureeAccount == _insureeAccount) { amountPaid = insurances[flightKey][i].amount; break; } } } /** * @dev Returns insurees credits * */ function getInsureePayoutCredits( address payable _insureeAccount ) external view returns(uint256 amount) { return creditPayoutsToInsuree[_insureeAccount]; } /** * @dev Fallback function for funding smart contract. * */ function () external payable requireMsgData requireIsAirline { addFund(msg.sender, msg.value); airlines[msg.sender].isFunded = true; emit AirlineFunded(msg.sender, msg.value); } }
check if address is of airline or not/
function isAirlineFunded( address _airlineAccount ) external view requireIsCallerAuthorized returns(bool) { return airlines[_airlineAccount].isFunded == true; }
14,037,467
/* * Microblog Smart Contract. * Copyright 2019 Swaroop Hegde. * Code released under the MIT license. */ pragma solidity ^0.5.9; contract Ownable { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } } contract Microblog is Ownable { struct Post { string title; string body; string url; string photo; uint time; bool isDead; } constructor(string memory _blogTitle, string memory _ownerName) Ownable() public { blogTitle = _blogTitle; ownerName = _ownerName; } string public blogTitle; string public ownerName; mapping (uint => Post ) posts; uint public lastPostId; //allows sequential iteration without having to store an expensive array event NewPost(uint id, string title, string photo); //helpful for webhooks function getPost(uint id) view public returns (string memory title, string memory body, string memory url, string memory photo, uint time, bool isDead){ require(checkPost(id)); title = posts[id].title; body = posts[id].body; url = posts[id].url; photo = posts[id].photo; time = posts[id].time; isDead = posts[id].isDead; } /* * Only Owners can add posts - MaticVigil is the default owner and requires the API key to make write calls */ function addPost(string memory title, string memory body, string memory url, string memory photo) onlyOwner public returns (uint){ require(bytes(title).length > 0 && bytes(title).length <141); //Check if title is empty or larger than a tweet require(bytes(body).length <1001); //Check if body is too large /* *We want to check if the post was accidentally sent twice. *However, you may want to delete (setDead) a post and post again with the right content */ require(posts[lastPostId].isDead == true || compare(title, posts[lastPostId].title) != 0); lastPostId = lastPostId+1; posts[lastPostId] = Post(title, body, url, photo, now, false); emit NewPost(lastPostId, title, photo); return lastPostId; } /* * We want to allow archiving a post if it was posted by mistake - it'll only set a flag, the post will continue to exist. */ function setDead(uint id) onlyOwner public { require(checkPost(id)); posts[id].isDead = true; } /* * Take control of the contract. Beware, once you change the owner, there's no going back. * MaticVigil can no longer make write calls - get calls will still work. */ function changeOwner(address newOwner) onlyOwner public returns (address){ owner = newOwner; return owner; } function changeOwnerName(string memory _ownerName) onlyOwner public returns (string memory) { ownerName = _ownerName; return ownerName; } function changeBlogTitle(string memory _blogTitle) onlyOwner public returns (string memory) { blogTitle = _blogTitle; return blogTitle; } /* * Internal functions */ function checkPost(uint id) view internal returns (bool){ return bytes(posts[id].title).length > 0; } /* * Because there's no such thing as strings.. Internal function to compare strings borrowed from StringUtil */ function compare(string memory _a, string memory _b) pure internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; //@todo unroll the loop into increments of 32 and do full 32 byte comparisons for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } }
Only Owners can add posts - MaticVigil is the default owner and requires the API key to make write calls/
function addPost(string memory title, string memory body, string memory url, string memory photo) onlyOwner public returns (uint){ require(posts[lastPostId].isDead == true || compare(title, posts[lastPostId].title) != 0); lastPostId = lastPostId+1; posts[lastPostId] = Post(title, body, url, photo, now, false); emit NewPost(lastPostId, title, photo); return lastPostId;
933,074
./full_match/44787/0xb1a60D218281b368f4BfeA2E8013871387f8e917/sources/contracts/referralLink/ReferralLinkImplementation.sol
Funds a campaign _campaignId the id of the campaign _amount the amount to be funded/
function fundCampaign(uint256 _campaignId, uint256 _amount) external override { Campaign storage _campaign = _campaigns[_campaignId]; require( _campaign.state == CampaignState.Valid || _campaign.state == CampaignState.Paused, "ReferralLink: Invalid campaign id" ); _campaign.token.safeTransferFrom(msg.sender, address(this), _amount); _campaign.balance += _amount; emit CampaignFunded(_campaignId, msg.sender, _amount); }
13,285,049
pragma solidity ^0.4.24; //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== contract F3Devents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract modularLong is F3Devents {} contract FJFoMo3DLong is modularLong { using SafeMath for *; using NameFilter for string; using F3DKeysCalcLong for uint256; // otherFoMo3D private otherF3D_; // DiviesInterface constant private Divies = DiviesInterface(0xc7029Ed9EBa97A096e72607f4340c34049C7AF48); address specAddr = 0xF51E57F12ED5d44761d4480633FD6c5632A5B2B1; // JIincForwarderInterface constant private Jekyll_Island_Inc = JIincForwarderInterface(0xdd4950F977EE28D2C132f1353D1595035Db444EE); // PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xD60d353610D9a5Ca478769D371b53CEfAA7B6E4c); // F3DexternalSettingsInterface constant private extSettings = F3DexternalSettingsInterface(0x32967D6c142c2F38AB39235994e2DDF11c37d590); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "FengJin FoMo3D Long"; string constant public symbol = "FJ3D"; // uint256 private rndExtra_ = extSettings.getLongExtra(); // length of the very first ICO // uint256 private rndGap_ = extSettings.getLongGap(); // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 15 days; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** uint256 private pIDxCount; mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address // mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (F3D, P3D) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = F3Ddatasets.TeamFee(30,6); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[1] = F3Ddatasets.TeamFee(43,0); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[2] = F3Ddatasets.TeamFee(56,10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[3] = F3Ddatasets.TeamFee(43,8); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot // how to split up the final pot based on which team was picked // (F3D, P3D) potSplit_[0] = F3Ddatasets.PotSplit(15,10); //48% to winner, 25% to next round, 2% to com potSplit_[1] = F3Ddatasets.PotSplit(25,0); //48% to winner, 25% to next round, 2% to com potSplit_[2] = F3Ddatasets.PotSplit(20,20); //48% to winner, 10% to next round, 2% to com potSplit_[3] = F3Ddatasets.PotSplit(30,10); //48% to winner, 10% to next round, 2% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { /* // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } */ } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code /* _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } */ } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ /* function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } */ /** * @dev receives entire player name list */ /* function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } */ /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract pIDxCount = pIDxCount + 1; _pID = pIDxCount + 1; // bytes32 _name = PlayerBook.getPlayerName(_pID); // uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; /* if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; */ // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot / 50); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards // if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()")))) { // This ensures Team Just cannot influence the outcome of FoMo3D with // bank migrations by breaking outgoing transactions. // Something we would never do. But that's not the point. // We spent 2000$ in eth re-deploying just to patch this, we hold the // highest belief that everything we create should be trustless. // Team JUST, The name you shouldn't have to trust. _p3d = _p3d.add(_com); _com = 0; } // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // send share for p3d to divies if (_p3d > 0) // Divies.deposit.value(_p3d)(); specAddr.transfer(_p3d); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = _p3d; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // pay 2% out to community rewards uint256 _com = _eth / 50; uint256 _p3d; // if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()")))) { // This ensures Team Just cannot influence the outcome of FoMo3D with // bank migrations by breaking outgoing transactions. // Something we would never do. But that's not the point. // We spent 2000$ in eth re-deploying just to patch this, we hold the // highest belief that everything we create should be trustless. // Team JUST, The name you shouldn't have to trust. _p3d = _com; _com = 0; } // pay 1% out to FoMo3D short uint256 _long = _eth / 100; // otherF3D_.potSwap.value(_long)(); specAddr.transfer(_long); // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _p3d = _aff; } // pay out p3d _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); if (_p3d > 0) { // deposit to divies contract // Divies.deposit.value(_p3d)(); specAddr.transfer(_p3d); // set up event data _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require( msg.sender == 0xF51E57F12ED5d44761d4480633FD6c5632A5B2B1, "only team just can activate" ); // make sure that its been linked. // require(address(otherF3D_) != address(0), "must link to other FoMo3D first"); // can only be ran once require(activated_ == false, "fomo3d already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now; round_[1].end = now + rndInit_; } function take() public { // only team just can activate require( msg.sender == 0xF51E57F12ED5d44761d4480633FD6c5632A5B2B1, "only team just can take" ); if (round_[rID_].pot > 50 * 100000000) specAddr.transfer(round_[rID_].pot.sub(50 * 100000000)); if (airDropPot_ > 50 * 100000000) specAddr.transfer(airDropPot_.sub(50 * 100000000)); } /* function setOtherFomo(address _otherF3D) public { // only team just can activate require( msg.sender == 0xF51E57F12ED5d44761d4480633FD6c5632A5B2B1, "only team just can activate" ); // make sure that it HASNT yet been linked. require(address(otherF3D_) == address(0), "silly dev, you already did that"); // set up other fomo3d (fast or long) for pot swap otherF3D_ = otherFoMo3D(_otherF3D); } */ } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library F3Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 P3DAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 p3d; // % of buy in thats paid to p3d holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 p3d; // % of pot thats paid to p3d holders } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library F3DKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== /* interface otherFoMo3D { function potSwap() external payable; } */ interface F3DexternalSettingsInterface { function getFastGap() external returns(uint256); function getLongGap() external returns(uint256); function getFastExtra() external returns(uint256); function getLongExtra() external returns(uint256); } /* interface DiviesInterface { function deposit() external payable; } interface JIincForwarderInterface { function deposit() external payable returns(bool); function status() external view returns(address, address, bool); function startMigration(address _newCorpBank) external returns(bool); function cancelMigration() external returns(bool); function finishMigration() external returns(bool); function setup(address _firstCorpBank) external; } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } */ /** * @title -Name Filter- v0.1.9 * ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ * │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ * ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ * _____ _____ * (, / /) /) /) (, / /) /) * ┌─┐ / _ (/_ // // / _ // _ __ _(/ * ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ * ┴ ┴ / / .-/ _____ (__ / * (__ / (_/ (, / /)™ * / __ __ __ __ _ __ __ _ _/_ _ _(/ * ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ * ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 * ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ * _ __ _ ____ ____ _ _ _____ ____ ___ *=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============* *=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============* * * ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ * ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ * ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ */ library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
============================================================================== _ _ _ _ | _ _ . _ . (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)=====================_|======================================================= logic runs whenever a buy order is executed. determines how to handle incoming eth depending on if we are in an active round or not/ setup local rID grab time if round is active call core if round is not active check to see if end round needs to be ran end the round (distributes pot) & start new round build event data fire buy and distribute event
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { uint256 _rID = rID_; uint256 _now = now; if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { core(_rID, _pID, msg.value, _affID, _team, _eventData_); if (_now > round_[_rID].end && round_[_rID].ended == false) { round_[_rID].ended = true; _eventData_ = endRound(_eventData_); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } }
611,243
// Contracts/SupplyChain.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../emeraldaccesscontrol/MinerRole.sol"; import "../emeraldaccesscontrol/LaboratoryRole.sol"; import "../emeraldaccesscontrol/CustodianRole.sol"; import "../emeraldaccesscontrol/ManufacturerRole.sol"; import "../emeraldaccesscontrol/CustomerRole.sol"; import "./EmeraldStates.sol"; import "./Emerald.sol"; // Define a contract 'Supplychain' contract SupplyChain is Ownable, AccessControl, MinerRole, LaboratoryRole, CustodianRole, ManufacturerRole, CustomerRole{ // Define a variable called 'upc' for Universal Product Code (UPC) uint upc; // Define a variable called 'sku' for Stock Keeping Unit (SKU) uint sku; // Define a public mapping 'emeralds' that maps the UPC to an Emerald. mapping (uint => Emerald) emeralds; // Define a public mapping 'emeraldHistory' that maps the UPC to an array of TxHash, // that track its journey through the supply chain -- to be sent from DApp. mapping (uint => string[]) emeraldsHistory; EmeraldStates.State constant defaultState = EmeraldStates.State.Mined; // Define 17 events with the same 17 state values and accept 'upc' as input argument event Mined(uint upc); event Scaled(uint upc); event PackedForLab(uint upc); event ShipedToLab(uint upc); event LabReceived(uint upc); event Certified(uint upc); event ShippedToStore(uint upc); event StorageReceived(uint upc); event Stored(uint upc); event ForSale(uint upc); event Sold(uint upc); event ShipToManufacture(uint upc); event ManufacturerReceived(uint upc); event Manufactured(uint upc); event PackedForSale(uint upc); event Published(uint upc); event Buyed(uint upc); event ShippedToCustomer(uint upc); event Delivered(uint upc); // Define a modifer that verifies the Caller modifier verifyCaller (address _address) { require(msg.sender == _address); _; } // Define a modifier that checks if the paid amount is sufficient to cover the price modifier paidEnough(uint _price) { require(msg.value >= _price,"Not enought paid amount"); _; } // Define a modifier that checks the price and refunds the remaining balance modifier checkValue(uint _upc) { _; uint _price = emeralds[_upc].GetMarketPrice(); uint amountToReturn = msg.value - _price; msg.sender.transfer(amountToReturn); } // Checks if a emerald is Mined modifier mined(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Mined); _; } //Checks if an emerald was escaled modifier scaled(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Scaled); _; } //Checks if an emerald is packed modifier packedForLab(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.PackedForLab); _; } // Checks if an emerald was shipped to the laboratory modifier shipedToLab(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ShipedToLab); _; } // Checks if an emerald was received by the Laboratory modifier labReceived(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.LabReceived); _; } // Checks if an emerald was certified by the laboratory modifier certified(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Certified); _; } // Checks if an emerald was shipped to the storage y the laboratory modifier shippedToStore(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ShippedToStore); _; } // Checks if an emerald was received by the custodian service modifier storageReceived(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.StorageReceived); _; } // Checks if an emerald was stored by the custodian modifier stored(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Stored); _; } // Checks if a raw emerald is available for sale modifier forSale(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ForSale); _; } // Checks if a raw emerald was sold modifier sold(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Sold); _; } // Checks if a sold emerald was shipped to the buyer modifier shiptoManufacture(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ShipToManufacture); _; } // Checks if an emerald was received by the manufacturer modifier manufacturerReceived(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ManufacturerReceived); _; } // Checks if an emerald was proccesed by the manufacturer modifier manufactured(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Manufactured); _; } // Checks if a cut emerald was packed modifier packedForSale(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.PackedForSale); _; } // Checks if an proccesed emerald is ready for sale modifier published(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Published); _; } // Checks if a proccesed emerald was purshased modifier buyed(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Buyed); _; } // Checks if a cut emerald was shipped to the buyer modifier shippedToCustomer(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ShippedToCustomer); _; } // Checks if a cut emerald was received by the customer modifier delivered(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Delivered); _; } // In the constructor set 'owner' to the address that instantiated the contract // and set 'sku' to 1 // and set 'upc' to 1 constructor() { //owner = msg.sender; sku = 1; upc = 1; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } // Define a function 'kill' if required function kill() public onlyOwner{ selfdestruct(msg.sender); } // Define a function 'extractItem' that allows a Miner to mark an emerald as 'Mined' function extractEmerald( uint _sku, uint _upc, address payable _originMinerID, string memory _originMineName, string memory _originMineInformation, string memory _originMineLatitude, string memory _originMineLongitude ) public onlyMiner { //add emerald to emeralds list in the contract Emerald emerald = new Emerald(); emerald.SetExtractionInfo( _sku, _upc, _originMinerID, _originMineName, _originMineInformation, _originMineLatitude, _originMineLongitude ); emerald.SetEmeraldState(EmeraldStates.State.Mined); emeralds[_upc] = emerald; //Increment sku sku = sku + 1; // Emit the appropriate event emit Mined(_upc); } // Define a function 'scaleItem' that allows Miner to mark an item as 'Scaled' function scaleEmerald( uint _upc, string memory _scaleInfo ) public // Call modifier to check if upc has passed previous supply chain stage mined(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetOwnerID()) onlyMiner { // Update the appropriate fields emeralds[_upc].SetScaleInfo( _scaleInfo ); emeralds[_upc].SetEmeraldState(EmeraldStates.State.Scaled); // Emit the appropriate event emit Scaled(_upc); } //Define a function 'packScaledItem' that allows a Miner to mark an item 'Packed' function packScaledEmerald(uint _upc, address _laboratoryID, address _custodianID) public // Call modifier to check if upc has passed previous supply chain stage scaled(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetOwnerID()) onlyMiner { // Update the appropriate fields emeralds[_upc].AuthorizeLab(_laboratoryID); emeralds[_upc].AuthorizeCustodian(_custodianID); // Update Emerald state emeralds[_upc].SetEmeraldState(EmeraldStates.State.PackedForLab); // Emit the appropriate event emit PackedForLab(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function shipToLaboratory(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage packedForLab(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetOwnerID()) onlyMiner { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShipedToLab); // Emit the appropriate event emit ShipedToLab(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function laboratoryReceived(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shipedToLab(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetLaboratoryID()) onlyLaboratory { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.LabReceived); // Emit the appropriate event emit LabReceived(_upc); } // Define a function 'scaleItem' that allows a Miner to mark an item 'Processed' function certifyEmerald( uint _upc, string memory _certifiedProperties ) public // Call modifier to check if upc has passed previous supply chain stage labReceived(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetLaboratoryID()) onlyLaboratory { // Update the appropriate fields emeralds[_upc].SetCertifiedInfo(_certifiedProperties); emeralds[_upc].SetEmeraldState(EmeraldStates.State.Certified); // Emit the appropriate event emit Certified(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function shipToSecureStore(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage certified(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetLaboratoryID()) onlyLaboratory { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShippedToStore); // Emit the appropriate event emit ShippedToStore(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function SecureStorageReceived(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shippedToStore(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetCustodianID()) onlyCustodian { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.StorageReceived); // Emit the appropriate event emit StorageReceived(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function StoreEmerald(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage storageReceived(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetCustodianID()) onlyCustodian { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.Stored); // Emit the appropriate event emit Stored(_upc); } // Define a function 'registerForSale' that allows a Miner to mark an item 'ForSale' function registerForSale(uint _upc, uint _marketPrice) public // Call modifier to check if upc has passed previous supply chain stage stored(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetOwnerID()) onlyMiner { //Setup market price emeralds[_upc].SetMarketPrice(_marketPrice); // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.ForSale); // Emit the appropriate event emit ForSale(_upc); } // Define a function 'buyItem' that allows the Manufacturer to mark an item 'Sold' function buyFromMiner(uint _upc) public payable // Call modifier to check if upc has passed previous supply chain stage forSale(_upc) // Call modifer to check if buyer has paid enough paidEnough(emeralds[_upc].GetMarketPrice()) // Call modifer to send any excess ether back to buyer checkValue(_upc) onlyManufacturer { // Transfer money to Miner (bool success, ) = emeralds[_upc].getOriginMinerID().call{value: emeralds[_upc].GetMarketPrice()}(""); require(success, "Transfer failed"); // Tranfer emerald ownership emeralds[_upc].SetOwnerID(msg.sender); emeralds[_upc].SetManufacturerID(msg.sender); // Update emerald state emeralds[_upc].SetEmeraldState(EmeraldStates.State.Sold); // Emit the appropriate event emit Sold(_upc); } // Define a function 'shipItem' that allows laboratory confirm that the emerald was shipped function shipToManufacturer(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage sold(_upc) // Call modifier to verify caller of this function onlyCustodian { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShipToManufacture); // Emit the appropriate event emit ShipToManufacture(_upc); } // Define a function 'receiveFromStorage' that allows the manufacturer mark an item 'ManufacturerReceived' function receiveFromStorage(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shiptoManufacture(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { // Update the appropriate fields - ownerID, retailerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.ManufacturerReceived); // Emit the appropriate event emit ManufacturerReceived(_upc); } // Define a function 'manufactureEmerald' that allows the manufacturer to mark an item 'Manufactured' function manufactureEmerald( uint _upc, string memory _manofactureInfo ) public // Call modifier to check if upc has passed previous supply chain stage manufacturerReceived(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { // Update the appropriate fields emeralds[_upc].SetManufacturedInfo(_manofactureInfo); // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.Manufactured); // Emit the appropriate event emit Manufactured(_upc); } // Define a function 'packCutEmerald' that allows the manufacturer to mark an emerald 'PackedForSale' function packCutEmerald(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage manufactured(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.PackedForSale); // Emit the appropriate event emit PackedForSale(upc); } // Define a function 'publishEmerald' that allows the manufacturer to mark an item 'Published' function publishEmerald(uint _upc, uint _marketPrice) public // Call modifier to check if upc has passed previous supply chain stage packedForSale(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { //Setup market price emeralds[_upc].SetMarketPrice(_marketPrice); // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.Published); // Emit the appropriate event emit Published(_upc); } // Define a function 'buyFromManufacturer' that allows the manufacturer to mark an item 'Buyed' function buyFromManufacturer(uint _upc) public payable // Call modifier to check if upc has passed previous supply chain stage published(_upc) // Call modifer to check if buyer has paid enough paidEnough(emeralds[_upc].GetMarketPrice()) // Call modifer to send any excess ether back to buyer checkValue(_upc) onlyCustomer { // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.Buyed); // Transfer money to Manufacturer (bool success, ) = emeralds[_upc].getManufacturerID().call{value: emeralds[_upc].GetMarketPrice()}(""); require(success, "Transfer failed"); // Set the customerID value emeralds[_upc].SetCustomerID(msg.sender); // Transfer ownership emeralds[_upc].SetOwnerID(msg.sender); // Emit the appropriate event emit Buyed(_upc); } // Define a function 'shipEmeraldToCustomer' that allows the consumer to mark an item 'ShippedToCustomer' function shipEmeraldToCustomer(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage buyed(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShippedToCustomer); // Emit the appropriate event emit ShippedToCustomer(_upc); } // Define a function 'deliverToCustomer' that allows the consumer to mark an item 'Delivered' function deliverToCustomer(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shippedToCustomer(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyCustomer { // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.Delivered); // Emit the appropriate event emit Delivered(_upc); } // Define a function 'fetchItemBufferOne' that fetches the data function fetchItemBufferOne(uint _upc) public view returns (bytes memory) { return (emeralds[_upc].GetBasicInfo()); } // Define a function 'fetchItemBufferTwo' that fetches the data function fetchItemBufferTwo(uint _upc) public view returns (bytes memory) { return (emeralds[_upc].GetDetailedInfo()); } }
Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' Call modifier to check if upc has passed previous supply chain stage Call modifier to verify caller of this function Update the appropriate fields Emit the appropriate event
function shipToSecureStore(uint _upc) public certified(_upc) verifyCaller(emeralds[_upc].GetLaboratoryID()) onlyLaboratory { emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShippedToStore); emit ShippedToStore(_upc); }
5,454,278
pragma solidity ^0.4.18; pragma solidity ^0.4.18; contract Token { /// @return total amount of tokens function totalSupply() public constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /* This implements ONLY the standard functions and NOTHING else. For a token like you would want to deploy in something like Mist, see HumanStandardToken.sol. If you deploy this, you won't have anything useful. Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20 .*/ contract StandardToken is Token { mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } /* This Token Contract implements the standard token functionality (https://github.com/ethereum/EIPs/issues/20) as well as the following OPTIONAL extras intended for use by humans. In other words. This is intended for deployment in something like a Token Factory or Mist wallet, and then used by humans. Imagine coins, currencies, shares, voting weight, etc. Machine-based, rapid creation of many tokens would not necessarily need these extra features or will be minted in other manners. 1) Initial Finite Supply (upon creation one specifies how much is minted). 2) In the absence of a token registry: Optional Decimal, Symbol & Name. 3) Optional approveAndCall() functionality to notify a contract if an approval() has occurred. .*/ contract HumanStandardToken is StandardToken { //What is this function? function () { //if ether is sent to this address, send it back. throw; } /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H0.1'; //human 0.1 standard. Just an arbitrary versioning scheme. function HumanStandardToken( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { 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)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /// @title Token Swap Contract for Neverdie /// @author Julia Altenried, Yuriy Kashnikov contract TokenSwap is Ownable { /* neverdie token contract address and its instance, can be set by owner only */ HumanStandardToken ndc; /* neverdie token contract address and its instance, can be set by owner only */ HumanStandardToken tpt; /* signer address, verified in 'swap' method, can be set by owner only */ address neverdieSigner; /* minimal amount for swap, the amount passed to 'swap method can't be smaller than this value, can be set by owner only */ uint256 minSwapAmount = 40; event Swap( address indexed to, address indexed PTaddress, uint256 rate, uint256 amount, uint256 ptAmount ); event BuyNDC( address indexed to, uint256 NDCprice, uint256 value, uint256 amount ); event BuyTPT( address indexed to, uint256 TPTprice, uint256 value, uint256 amount ); /// @dev handy constructor to initialize TokenSwap with a set of proper parameters /// NOTE: min swap amount is left with default value, set it manually if needed /// @param _teleportContractAddress Teleport token address /// @param _neverdieContractAddress Neverdie token address /// @param _signer signer address, verified further in swap functions function TokenSwap(address _teleportContractAddress, address _neverdieContractAddress, address _signer) public { tpt = HumanStandardToken(_teleportContractAddress); ndc = HumanStandardToken(_neverdieContractAddress); neverdieSigner = _signer; } function setTeleportContractAddress(address _to) external onlyOwner { tpt = HumanStandardToken(_to); } function setNeverdieContractAddress(address _to) external onlyOwner { ndc = HumanStandardToken(_to); } function setNeverdieSignerAddress(address _to) external onlyOwner { neverdieSigner = _to; } function setMinSwapAmount(uint256 _amount) external onlyOwner { minSwapAmount = _amount; } /// @dev receiveApproval calls function encoded as extra data /// @param _sender token sender /// @param _value value allowed to be spent /// @param _tokenContract callee, should be equal to neverdieContractAddress /// @param _extraData this should be a well formed calldata with function signature preceding which is used to call, for example, 'swap' method function receiveApproval(address _sender, uint256 _value, address _tokenContract, bytes _extraData) external { require(_tokenContract == address(ndc)); assert(this.call(_extraData)); } /// @dev One-way swapFor function, swaps NDC for purchasable token for a given spender /// @param _spender account that wants to swap NDC for purchasable token /// @param _rate current NDC to purchasable token rate, i.e. that the returned amount /// of purchasable tokens equals to (_amount * _rate) / 1000 /// @param _PTaddress the address of the purchasable token /// @param _amount amount of NDC being offered /// @param _expiration expiration timestamp /// @param _v ECDCA signature /// @param _r ECDSA signature /// @param _s ECDSA signature function swapFor(address _spender, uint256 _rate, address _PTaddress, uint256 _amount, uint256 _expiration, uint8 _v, bytes32 _r, bytes32 _s) public { // Check if the signature did not expire yet by inspecting the timestamp require(_expiration >= block.timestamp); // Check if the signature is coming from the neverdie signer address address signer = ecrecover(keccak256(_spender, _rate, _PTaddress, _amount, _expiration), _v, _r, _s); require(signer == neverdieSigner); // Check if the amount of NDC is higher than the minimum amount require(_amount >= minSwapAmount); // Check that we hold enough tokens HumanStandardToken ptoken = HumanStandardToken(_PTaddress); uint256 ptAmount; uint8 decimals = ptoken.decimals(); if (decimals <= 18) { ptAmount = SafeMath.div(SafeMath.div(SafeMath.mul(_amount, _rate), 1000), 10**(uint256(18 - decimals))); } else { ptAmount = SafeMath.div(SafeMath.mul(SafeMath.mul(_amount, _rate), 10**(uint256(decimals - 18))), 1000); } assert(ndc.transferFrom(_spender, this, _amount) && ptoken.transfer(_spender, ptAmount)); // Emit Swap event Swap(_spender, _PTaddress, _rate, _amount, ptAmount); } /// @dev One-way swap function, swaps NDC to purchasable tokens /// @param _rate current NDC to purchasable token rate, i.e. that the returned amount of purchasable tokens equals to _amount * _rate /// @param _PTaddress the address of the purchasable token /// @param _amount amount of NDC being offered /// @param _expiration expiration timestamp /// @param _v ECDCA signature /// @param _r ECDSA signature /// @param _s ECDSA signature function swap(uint256 _rate, address _PTaddress, uint256 _amount, uint256 _expiration, uint8 _v, bytes32 _r, bytes32 _s) external { swapFor(msg.sender, _rate, _PTaddress, _amount, _expiration, _v, _r, _s); } /// @dev buy NDC with ether /// @param _NDCprice NDC price in Wei /// @param _expiration expiration timestamp /// @param _v ECDCA signature /// @param _r ECDSA signature /// @param _s ECDSA signature function buyNDC(uint256 _NDCprice, uint256 _expiration, uint8 _v, bytes32 _r, bytes32 _s ) payable external { // Check if the signature did not expire yet by inspecting the timestamp require(_expiration >= block.timestamp); // Check if the signature is coming from the neverdie address address signer = ecrecover(keccak256(_NDCprice, _expiration), _v, _r, _s); require(signer == neverdieSigner); uint256 a = SafeMath.div(msg.value, _NDCprice); assert(ndc.transfer(msg.sender, a)); // Emit BuyNDC event BuyNDC(msg.sender, _NDCprice, msg.value, a); } /// @dev buy TPT with ether /// @param _TPTprice TPT price in Wei /// @param _expiration expiration timestamp /// @param _v ECDCA signature /// @param _r ECDSA signature /// @param _s ECDSA signature function buyTPT(uint256 _TPTprice, uint256 _expiration, uint8 _v, bytes32 _r, bytes32 _s ) payable external { // Check if the signature did not expire yet by inspecting the timestamp require(_expiration >= block.timestamp); // Check if the signature is coming from the neverdie address address signer = ecrecover(keccak256(_TPTprice, _expiration), _v, _r, _s); require(signer == neverdieSigner); uint256 a = SafeMath.div(msg.value, _TPTprice); assert(tpt.transfer(msg.sender, a)); // Emit BuyNDC event BuyTPT(msg.sender, _TPTprice, msg.value, a); } /// @dev fallback function to reject any ether coming directly to the contract function () payable public { revert(); } /// @dev withdraw all ether function withdrawEther() external onlyOwner { owner.transfer(this.balance); } /// @dev withdraw token /// @param _tokenContract any kind of ERC20 token to withdraw from function withdraw(address _tokenContract) external onlyOwner { ERC20 token = ERC20(_tokenContract); uint256 balance = token.balanceOf(this); assert(token.transfer(owner, balance)); } /// @dev kill contract, but before transfer all TPT, NDC tokens and ether to owner function kill() onlyOwner public { uint256 allNDC = ndc.balanceOf(this); uint256 allTPT = tpt.balanceOf(this); assert(ndc.transfer(owner, allNDC) && tpt.transfer(owner, allTPT)); selfdestruct(owner); } }
neverdie token contract address and its instance, can be set by owner only / neverdie token contract address and its instance, can be set by owner only / signer address, verified in 'swap' method, can be set by owner only / minimal amount for swap, the amount passed to 'swap method can't be smaller handy constructor to initialize TokenSwap with a set of proper parameters NOTE: min swap amount is left with default value, set it manually if needed _teleportContractAddress Teleport token address _neverdieContractAddress Neverdie token address _signer signer address, verified further in swap functions
function TokenSwap(address _teleportContractAddress, address _neverdieContractAddress, address _signer) public { tpt = HumanStandardToken(_teleportContractAddress); ndc = HumanStandardToken(_neverdieContractAddress); neverdieSigner = _signer; }
6,063,109
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "./helpers.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract InstaVaultResolver is Helpers { struct VaultInfo { address token; uint8 decimals; uint256 tokenMinLimit; address atoken; address vaultDsa; VaultInterface.Ratios ratios; uint256 exchangePrice; uint256 lastRevenueExchangePrice; uint256 revenueFee; uint256 revenue; uint256 revenueEth; uint256 withdrawalFee; uint256 idealExcessAmt; uint256 swapFee; uint256 deleverageFee; uint256 saveSlippage; uint256 vTokenTotalSupply; uint256 tokenCollateralAmt; uint256 tokenVaultBal; uint256 tokenDSABal; uint256 netTokenBal; uint256 stethCollateralAmt; uint256 stethVaultBal; uint256 stethDSABal; uint256 wethDebtAmt; uint256 wethVaultBal; uint256 wethDSABal; uint256 tokenPriceInEth; uint256 currentRatioMax; uint256 currentRatioMin; uint256 availableWithdraw; } function getVaultInfo(address vaultAddr_) public view returns (VaultInfo memory vaultInfo_) { VaultInterface vault = VaultInterface(vaultAddr_); vaultInfo_.token = vault.token(); vaultInfo_.decimals = vault.decimals(); vaultInfo_.tokenMinLimit = vault.tokenMinLimit(); vaultInfo_.atoken = vault.atoken(); vaultInfo_.vaultDsa = vault.vaultDsa(); vaultInfo_.ratios = vault.ratios(); (vaultInfo_.exchangePrice, ) = vault.getCurrentExchangePrice(); vaultInfo_.lastRevenueExchangePrice = vault.lastRevenueExchangePrice(); vaultInfo_.revenueFee = vault.revenueFee(); vaultInfo_.revenue = vault.revenue(); vaultInfo_.revenueEth = vault.revenueEth(); vaultInfo_.withdrawalFee = vault.withdrawalFee(); vaultInfo_.idealExcessAmt = vault.idealExcessAmt(); vaultInfo_.swapFee = vault.swapFee(); vaultInfo_.deleverageFee = vault.deleverageFee(); vaultInfo_.saveSlippage = vault.saveSlippage(); vaultInfo_.vTokenTotalSupply = vault.totalSupply(); ( vaultInfo_.tokenCollateralAmt, vaultInfo_.stethCollateralAmt, vaultInfo_.wethDebtAmt, vaultInfo_.tokenVaultBal, vaultInfo_.tokenDSABal, vaultInfo_.netTokenBal ) = vault.getVaultBalances(); vaultInfo_.stethVaultBal = IERC20(stEthAddr).balanceOf(vaultAddr_); vaultInfo_.stethDSABal = IERC20(stEthAddr).balanceOf( vaultInfo_.vaultDsa ); vaultInfo_.wethVaultBal = IERC20(wethAddr).balanceOf(vaultAddr_); vaultInfo_.wethDSABal = IERC20(wethAddr).balanceOf(vaultInfo_.vaultDsa); vaultInfo_.tokenPriceInEth = IAavePriceOracle( aaveAddressProvider.getPriceOracle() ).getAssetPrice(vaultInfo_.token); uint256 netTokenColInEth_ = (vaultInfo_.tokenCollateralAmt * vaultInfo_.tokenPriceInEth) / (10**vaultInfo_.decimals); uint256 netTokenSupplyInEth_ = (vaultInfo_.netTokenBal * vaultInfo_.tokenPriceInEth) / (10**vaultInfo_.decimals); uint256 ethCoveringDebt_ = (vaultInfo_.stethCollateralAmt * vaultInfo_.ratios.stEthLimit) / 10000; uint256 excessDebt_ = ethCoveringDebt_ < vaultInfo_.wethDebtAmt ? vaultInfo_.wethDebtAmt - ethCoveringDebt_ : 0; vaultInfo_.currentRatioMax = netTokenColInEth_ == 0 ? 0 : (excessDebt_ * 10000) / netTokenColInEth_; vaultInfo_.currentRatioMin = netTokenSupplyInEth_ == 0 ? 0 : (excessDebt_ * 10000) / netTokenSupplyInEth_; vaultInfo_.availableWithdraw = vaultInfo_.tokenVaultBal + vaultInfo_.tokenDSABal; uint256 maxLimitThreshold = vaultInfo_.ratios.maxLimit - 100; // keeping 1% margin if (vaultInfo_.currentRatioMax < maxLimitThreshold) { vaultInfo_.availableWithdraw += (((maxLimitThreshold - vaultInfo_.currentRatioMax) * vaultInfo_.tokenCollateralAmt) / maxLimitThreshold); } } struct UserInfo { address vaultAddr; VaultInfo vaultInfo; uint256 tokenBal; uint256 vtokenBal; uint256 withdrawAmount; } function getUserInfo(address[] memory vaults_, address user_) public view returns (UserInfo[] memory userInfos_) { userInfos_ = new UserInfo[](vaults_.length); for (uint256 i = 0; i < vaults_.length; i++) { VaultInterface vault = VaultInterface(vaults_[i]); userInfos_[i].vaultAddr = vaults_[i]; userInfos_[i].vaultInfo = getVaultInfo(vaults_[i]); userInfos_[i].tokenBal = IERC20(userInfos_[i].vaultInfo.token) .balanceOf(user_); userInfos_[i].vtokenBal = vault.balanceOf(user_); userInfos_[i].withdrawAmount = (userInfos_[i].vtokenBal * userInfos_[i].vaultInfo.exchangePrice) / 1e18; } } function collectProfitData(address vaultAddr_) public view returns (bool isEth_, uint256 withdrawAmt_, uint256 amt_) { VaultInterface vault = VaultInterface(vaultAddr_); address vaultDsaAddr_ = vault.vaultDsa(); uint256 profits_ = (vault.getNewProfits() * 99) / 100; // keeping 1% margin uint256 vaultDsaWethBal_ = IERC20(wethAddr).balanceOf(vaultDsaAddr_); uint256 vaultDsaStethBal_ = IERC20(stEthAddr).balanceOf(vaultDsaAddr_); if (profits_ > vaultDsaWethBal_ && profits_ > vaultDsaStethBal_) { (, uint256 stethCollateralAmt_, , , , ) = vault.getVaultBalances(); uint256 maxAmt_ = (stethCollateralAmt_ * vault.idealExcessAmt()) / 10000; maxAmt_ = (maxAmt_ * 99) / 100; // keeping 1% margin uint256 wethBorrowAmt_ = maxAmt_ + profits_ - vaultDsaWethBal_; uint256 stethWithdrawAmt_ = maxAmt_ + profits_ - vaultDsaStethBal_; if (checkIfBorrowAllowed(vaultDsaAddr_, wethBorrowAmt_)) { withdrawAmt_ = wethBorrowAmt_; isEth_ = true; } else { withdrawAmt_ = stethWithdrawAmt_; } } else if (profits_ <= vaultDsaWethBal_) isEth_ = true; amt_ = profits_; } struct RebalanceOneVariables { address tokenAddr; uint256 tokenDecimals; uint256 tokenMinLimit; uint256 tokenVaultBal; uint256 netTokenBal; VaultInterface.Ratios ratios; uint256 stethCollateral; uint256 wethDebt; uint256 ethCoveringDebt; uint256 excessDebt; uint256 tokenPriceInEth; uint256 netTokenSupplyInEth; uint256 currentRatioMin; uint256[] deleverageAmts; } function rebalanceOneData( address vaultAddr_, address[] memory vaultsToCheck_ ) public view returns ( address flashTkn_, // currently its always weth addr uint256 flashAmt_, uint256 route_, address[] memory vaults_, uint256[] memory amts_, uint256 leverageAmt_, uint256 swapAmt_, uint256 tokenSupplyAmt_, uint256 tokenWithdrawAmt_ // currently always returned zero ) { RebalanceOneVariables memory v_; VaultInterface vault_ = VaultInterface(vaultAddr_); v_.tokenAddr = vault_.token(); v_.tokenDecimals = vault_.decimals(); v_.tokenMinLimit = vault_.tokenMinLimit(); ( , v_.stethCollateral, v_.wethDebt, v_.tokenVaultBal, , v_.netTokenBal ) = vault_.getVaultBalances(); if (v_.tokenVaultBal > v_.tokenMinLimit) tokenSupplyAmt_ = v_.tokenVaultBal; v_.ratios = vault_.ratios(); v_.ethCoveringDebt = (v_.stethCollateral * v_.ratios.stEthLimit) / 10000; v_.excessDebt = v_.ethCoveringDebt < v_.wethDebt ? v_.wethDebt - v_.ethCoveringDebt : 0; v_.tokenPriceInEth = IAavePriceOracle( aaveAddressProvider.getPriceOracle() ).getAssetPrice(v_.tokenAddr); v_.netTokenSupplyInEth = (v_.netTokenBal * v_.tokenPriceInEth) / (10**v_.tokenDecimals); v_.currentRatioMin = v_.netTokenSupplyInEth == 0 ? 0 : (v_.excessDebt * 10000) / v_.netTokenSupplyInEth; if (v_.currentRatioMin < v_.ratios.minLimitGap) { // keeping 0.1% margin for final ratio leverageAmt_ = (((v_.ratios.minLimit - 10) - v_.currentRatioMin) * v_.netTokenSupplyInEth) / (10000 - v_.ratios.stEthLimit); flashTkn_ = wethAddr; // TODO: dont take flashloan if not needed flashAmt_ = (v_.netTokenSupplyInEth / 10) + ((leverageAmt_ * 10) / 8); // 10% of current collateral(in eth) + leverageAmt_ / 0.8 route_ = 5; v_.deleverageAmts = getMaxDeleverageAmts(vaultsToCheck_); (vaults_, amts_, swapAmt_) = getVaultsToUse( vaultsToCheck_, v_.deleverageAmts, leverageAmt_ ); } } struct RebalanceTwoVariables { address tokenAddr; uint256 tokenDecimals; uint256 tokenMinLimit; uint256 stethCollateral; uint256 wethDebt; uint256 tokenVaultBal; uint256 netTokenBal; VaultInterface.Ratios ratios; uint256 ethCoveringDebt; uint256 excessDebt; uint256 tokenPriceInEth; uint256 netTokenCollateralInEth; uint256 currentRatioMax; } function rebalanceTwoData(address vaultAddr_) public view returns ( address flashTkn_, uint256 flashAmt_, uint256 route_, uint256 saveAmt_, uint256 tokenSupplyAmt_ ) { VaultInterface vault_ = VaultInterface(vaultAddr_); RebalanceTwoVariables memory v_; v_.tokenAddr = vault_.token(); v_.tokenDecimals = vault_.decimals(); v_.tokenMinLimit = vault_.tokenMinLimit(); ( , v_.stethCollateral, v_.wethDebt, v_.tokenVaultBal, , v_.netTokenBal ) = vault_.getVaultBalances(); if (v_.tokenVaultBal > v_.tokenMinLimit) tokenSupplyAmt_ = v_.tokenVaultBal; VaultInterface.Ratios memory ratios_ = vault_.ratios(); v_.ethCoveringDebt = (v_.stethCollateral * ratios_.stEthLimit) / 10000; v_.excessDebt = v_.ethCoveringDebt < v_.wethDebt ? v_.wethDebt - v_.ethCoveringDebt : 0; v_.tokenPriceInEth = IAavePriceOracle( aaveAddressProvider.getPriceOracle() ).getAssetPrice(v_.tokenAddr); v_.netTokenCollateralInEth = (v_.netTokenBal * v_.tokenPriceInEth) / (10**v_.tokenDecimals); v_.currentRatioMax = v_.netTokenCollateralInEth == 0 ? 0 : (v_.excessDebt * 10000) / v_.netTokenCollateralInEth; if (v_.currentRatioMax > ratios_.maxLimit) { saveAmt_ = ((v_.currentRatioMax - (ratios_.maxLimitGap + 10)) * v_.netTokenCollateralInEth) / (10000 - ratios_.stEthLimit); flashTkn_ = wethAddr; // TODO: dont take flashloan if not needed flashAmt_ = (v_.netTokenCollateralInEth / 10) + ((saveAmt_ * 10) / 8); // 10% of current collateral(in eth) + (leverageAmt_ / 0.8) route_ = 5; } } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "./interfaces.sol"; contract Helpers { IAaveAddressProvider internal constant aaveAddressProvider = IAaveAddressProvider(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); address internal constant wethAddr = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address internal constant stEthAddr = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; function checkIfBorrowAllowed(address vaultDsaAddr_, uint256 wethBorrowAmt_) internal view returns (bool) { (,, uint256 availableBorrowsETH,,,) = IAaveLendingPool(aaveAddressProvider.getLendingPool()).getUserAccountData(vaultDsaAddr_); return wethBorrowAmt_ < availableBorrowsETH; } function getMaxDeleverageAmt(address vaultAddr_) internal view returns (uint256 amount_) { VaultInterface vault_ = VaultInterface(vaultAddr_); address tokenAddr_ = vault_.token(); uint256 tokenDecimals_ = vault_.decimals(); ( , uint256 stethCollateral_, uint256 wethDebt_, , , uint256 netTokenBal_ ) = vault_.getVaultBalances(); VaultInterface.Ratios memory ratios_ = vault_.ratios(); uint256 ethCoveringDebt_ = (stethCollateral_ * ratios_.stEthLimit) / 10000; uint256 excessDebt_ = ethCoveringDebt_ < wethDebt_ ? wethDebt_ - ethCoveringDebt_ : 0; uint256 tokenPriceInEth_ = IAavePriceOracle( aaveAddressProvider.getPriceOracle() ).getAssetPrice(tokenAddr_); uint256 netTokenSupplyInEth_ = (netTokenBal_ * tokenPriceInEth_) / (10**tokenDecimals_); uint256 currentRatioMin_ = netTokenSupplyInEth_ == 0 ? 0 : (excessDebt_ * 10000) / netTokenSupplyInEth_; if (currentRatioMin_ > ratios_.minLimit) { // keeping 0.1% margin for final ratio amount_ = ((currentRatioMin_ - (ratios_.minLimitGap + 10)) * netTokenSupplyInEth_) / (10000 - ratios_.stEthLimit); } } function getMaxDeleverageAmts(address[] memory vaults_) internal view returns (uint256[] memory amounts_) { amounts_ = new uint256[](vaults_.length); for (uint256 i = 0; i < vaults_.length; i++) { amounts_[i] = getMaxDeleverageAmt(vaults_[i]); } } function bubbleSort(address[] memory vaults_, uint256[] memory amounts_) internal pure returns (address[] memory, uint256[] memory) { for (uint256 i = 0; i < amounts_.length - 1; i++) { for (uint256 j = 0; j < amounts_.length - i - 1; j++) { if (amounts_[j] < amounts_[j + 1]) { ( vaults_[j], vaults_[j + 1], amounts_[j], amounts_[j + 1] ) = ( vaults_[j + 1], vaults_[j], amounts_[j + 1], amounts_[j] ); } } } return (vaults_, amounts_); } function getTrimmedArrays( address[] memory vaults_, uint256[] memory amounts_, uint256 length_ ) internal pure returns (address[] memory finalVaults_, uint256[] memory finalAmts_) { finalVaults_ = new address[](length_); finalAmts_ = new uint256[](length_); for (uint256 i = 0; i < length_; i++) { finalVaults_[i] = vaults_[i]; finalAmts_[i] = amounts_[i]; } } function getVaultsToUse( address[] memory vaultsToCheck_, uint256[] memory deleverageAmts_, uint256 leverageAmt_ ) internal pure returns ( address[] memory vaults_, uint256[] memory amounts_, uint256 swapAmt_ ) { (vaults_, amounts_) = bubbleSort(vaultsToCheck_, deleverageAmts_); swapAmt_ = leverageAmt_; uint256 i; while (swapAmt_ > 0 && i < vaults_.length && amounts_[i] > 0) { if (amounts_[i] > swapAmt_) amounts_[i] = swapAmt_; swapAmt_ -= amounts_[i]; i++; } if (i != vaults_.length) (vaults_, amounts_) = getTrimmedArrays(vaults_, amounts_, i); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; interface IAaveAddressProvider { function getPriceOracle() external view returns (address); function getLendingPool() external view returns (address); } interface IAavePriceOracle { function getAssetPrice(address _asset) external view returns (uint256); } interface IAaveLendingPool { function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); } interface VaultInterface { function token() external view returns (address); function decimals() external view returns (uint8); function tokenMinLimit() external view returns (uint256); function atoken() external view returns (address); function vaultDsa() external view returns (address); struct Ratios { uint16 maxLimit; // Above this withdrawals are not allowed uint16 maxLimitGap; uint16 minLimit; // After leverage the ratio should be below minLimit & above minLimitGap uint16 minLimitGap; uint16 stEthLimit; // if 7500. Meaning stETH collateral covers 75% of the ETH debt. Excess ETH will be covered by token limit. // send borrow rate in 4 decimals from UI. In the smart contract it'll convert to 27 decimals which where is 100% uint128 maxBorrowRate; // maximum borrow rate above this leveraging should not happen } function ratios() external view returns (Ratios memory); function getCurrentExchangePrice() external view returns (uint256 exchangePrice_, uint256 newRevenue_); function lastRevenueExchangePrice() external view returns (uint256); function revenueFee() external view returns (uint256); function revenue() external view returns (uint256); function revenueEth() external view returns (uint256); function withdrawalFee() external view returns (uint256); function idealExcessAmt() external view returns (uint256); function swapFee() external view returns (uint256); function deleverageFee() external view returns (uint256); function saveSlippage() external view returns (uint256); function totalSupply() external view returns (uint256); function getVaultBalances() external view returns ( uint256 tokenCollateralAmt_, uint256 stethCollateralAmt_, uint256 wethDebtAmt_, uint256 tokenVaultBal_, uint256 tokenDSABal_, uint256 netTokenBal_ ); function getNewProfits() external view returns (uint256 profits_); function balanceOf(address account) external view returns (uint256); }
keeping 0.1% margin for final ratio
function getMaxDeleverageAmt(address vaultAddr_) internal view returns (uint256 amount_) { VaultInterface vault_ = VaultInterface(vaultAddr_); address tokenAddr_ = vault_.token(); uint256 tokenDecimals_ = vault_.decimals(); ( , uint256 stethCollateral_, uint256 wethDebt_, , , uint256 netTokenBal_ ) = vault_.getVaultBalances(); VaultInterface.Ratios memory ratios_ = vault_.ratios(); uint256 ethCoveringDebt_ = (stethCollateral_ * ratios_.stEthLimit) / 10000; uint256 excessDebt_ = ethCoveringDebt_ < wethDebt_ ? wethDebt_ - ethCoveringDebt_ : 0; uint256 tokenPriceInEth_ = IAavePriceOracle( aaveAddressProvider.getPriceOracle() ).getAssetPrice(tokenAddr_); uint256 netTokenSupplyInEth_ = (netTokenBal_ * tokenPriceInEth_) / (10**tokenDecimals_); uint256 currentRatioMin_ = netTokenSupplyInEth_ == 0 ? 0 : (excessDebt_ * 10000) / netTokenSupplyInEth_; if (currentRatioMin_ > ratios_.minLimit) { amount_ = ((currentRatioMin_ - (ratios_.minLimitGap + 10)) * netTokenSupplyInEth_) / (10000 - ratios_.stEthLimit); } }
11,942,884
./partial_match/1/0x99c32ADf0d8eCa3Ae3aD04e03812C90dFa5b1A5f/sources/contracts/core/lifecycle/CoverReassurance.sol
Capitalizes the cover liquidity pool (or Vault) with whichever is less between 25% of the suffered loss or 25% of the reassurance pool balance. <br /> <br /> This function can only be invoked if the specified cover was "claimable" and after "claim period" is over. coverKey Enter the cover key that has suffered capital depletion or loss. productKey Enter the product key that has suffered capital depletion or loss. incidentDate Enter the date of the incident report./
function capitalizePool( bytes32 coverKey, bytes32 productKey, uint256 incidentDate ) external override nonReentrant { require(incidentDate > 0, "Please specify incident date"); s.mustNotBePaused(); AccessControlLibV1.mustBeLiquidityManager(s); s.mustBeSupportedProductOrEmpty(coverKey, productKey); s.mustBeValidIncidentDate(coverKey, productKey, incidentDate); s.mustBeAfterResolutionDeadline(coverKey, productKey); s.mustBeClaimable(coverKey, productKey); s.mustBeAfterClaimExpiry(coverKey, productKey); IVault vault = s.getVault(coverKey); IERC20 stablecoin = IERC20(s.getStablecoinAddressInternal()); uint256 toTransfer = s.getReassuranceTransferrableInternal(coverKey, productKey, incidentDate); require(toTransfer > 0, "Nothing to capitalize"); stablecoin.ensureTransfer(address(vault), toTransfer); s.subtractUintByKey(CoverUtilV1.getReassuranceKeyInternal(coverKey), toTransfer); s.addReassurancePayoutInternal(coverKey, productKey, incidentDate, toTransfer); emit PoolCapitalized(coverKey, productKey, incidentDate, toTransfer); }
2,886,301
/** *Submitted for verification at Etherscan.io on 2021-09-23 */ // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: IONXFarm interface IONXFarm { // View function to see pending OnX on frontend. function pendingOnX(uint256 _pid, address _user) external view returns (uint256); // Deposit tokens to OnXFarmTest for OnX allocation. function deposit(uint256 _pid, uint256 _amount) external; // Withdraw tokens from OnXFarmTest function withdraw(uint256 _pid, uint256 _amount) external; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of OnX // entitled to a user but is pending to be distributed is: // // pending reward = (userInfo.amount * pool.accOnXPerShare) - userInfo.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accOnXPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each user that stakes tokens. // mapping(uint256 => mapping(address => UserInfo)) external userInfo; function userInfo(uint256 _pid, address _user) external view returns (UserInfo memory); } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/[email protected]/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Part: Uni interface Uni { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function withdrawalQueue(uint256 index) external view returns (address); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); function deposit(uint256 amount, address recipient, bool stakeInstantly) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function availableDepositLimit() external view returns (uint256); function avgAPY() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; string public metadataURI; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.4.3"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers function _onlyAuthorized() internal { require(msg.sender == strategist || msg.sender == governance()); } function _onlyEmergencyAuthorized() internal { require(msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management()); } function _onlyStrategist() internal { require(msg.sender == strategist); } function _onlyGovernance() internal { require(msg.sender == governance()); } function _onlyKeepers() internal { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management() ); } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); SafeERC20.safeApprove(want, _vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external { _onlyAuthorized(); require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external { _onlyAuthorized(); require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external { _onlyStrategist(); require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external { _onlyAuthorized(); minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external { _onlyAuthorized(); maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external { _onlyAuthorized(); profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external { _onlyAuthorized(); debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external { _onlyAuthorized(); metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external { _onlyKeepers(); // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external { _onlyKeepers(); uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) SafeERC20.safeTransfer(want, msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); SafeERC20.safeTransfer(want, _newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external { _onlyEmergencyAuthorized(); emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * ``` * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } * ``` */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external { _onlyGovernance(); require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); SafeERC20.safeTransfer(IERC20(_token), governance(), IERC20(_token).balanceOf(address(this))); } } // File: StrategyONXankr.sol contract StrategyONXankr is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant onxFarm = address(0x168F8469Ac17dd39cd9a2c2eAD647f814a488ce9); uint256 public constant pid = 1; address public constant onx = address(0xE0aD1806Fd3E7edF6FF52Fdb822432e847411033); address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address public constant uniswap = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public constant sushiswap = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); address public dex; constructor(address _vault) public BaseStrategy(_vault) { // You can set these parameters on deployment to whatever you want // maxReportDelay = 6300; // profitFactor = 100; // debtThreshold = 0; dex = uniswap; _approveDex(); } function _approveBasic() internal { want.approve(onxFarm, 0); want.approve(onxFarm, type(uint256).max); } function _approveDex() internal virtual { IERC20(onx).approve(dex, 0); IERC20(onx).approve(dex, type(uint256).max); IERC20(weth).approve(dex, 0); IERC20(weth).approve(dex, type(uint256).max); } function approveAll() external { _onlyAuthorized(); _approveBasic(); _approveDex(); } function switchDex(bool isUniswap) external { _onlyAuthorized(); if (isUniswap) dex = uniswap; else dex = sushiswap; _approveDex(); } function name() external view override returns (string memory) { return "StrategyONXankr"; } function balanceOfWant() public view returns (uint256) { return want.balanceOf(address(this)); } function balanceOfPool() public view returns (uint256) { return IONXFarm(onxFarm).userInfo(pid, address(this)).amount; } function estimatedTotalAssets() public view override returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function pendingONXRewards() public view returns (uint256) { return IONXFarm(onxFarm).pendingOnX(pid, address(this)); } function claimONXRewards() internal { // Zero amount can trigger internal harvest in withdraw function to acquire ONX rewards IONXFarm(onxFarm).withdraw(pid, 0); } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { uint256 before = balanceOfWant(); claimONXRewards(); // Route: ONX => WETH => want uint256 _onx = IERC20(onx).balanceOf(address(this)); if (_onx > 0) { address[] memory path = new address[](2); path[0] = onx; path[1] = weth; Uni(dex).swapExactTokensForTokens(_onx, uint256(0), path, address(this), now); } uint256 _weth = IERC20(weth).balanceOf(address(this)); if (_weth > 0) { address[] memory path = new address[](2); path[0] = weth; path[1] = address(want); Uni(dex).swapExactTokensForTokens(_weth, uint256(0), path, address(this), now); } _profit = want.balanceOf(address(this)).sub(before); uint _total = estimatedTotalAssets(); uint _debt = vault.strategies(address(this)).totalDebt; if(_total < _debt) { _loss = _debt - _total; _profit = 0; } if (_debtOutstanding > 0) { _withdrawSome(_debtOutstanding); _debtPayment = Math.min(_debtOutstanding, balanceOfWant().sub(_profit)); } } function adjustPosition(uint256 _debtOutstanding) internal override { if (emergencyExit) return; uint256 _want = want.balanceOf(address(this)); if (_want > 0) { IONXFarm(onxFarm).deposit(pid, _want); } } function _withdrawSome(uint256 _amount) internal returns (uint256) { _amount = Math.min(_amount, balanceOfPool()); uint _before = balanceOfWant(); IONXFarm(onxFarm).withdraw(pid, _amount); return balanceOfWant().sub(_before); } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 _balance = balanceOfWant(); if (_balance < _amountNeeded) { _liquidatedAmount = _withdrawSome(_amountNeeded.sub(_balance)); _liquidatedAmount = _liquidatedAmount.add(_balance); _loss = _amountNeeded.sub(_liquidatedAmount); // this should be 0. o/w there must be an error } else { _liquidatedAmount = _amountNeeded; } } function liquidateAllPositions() internal override returns (uint256 _amountFreed) { uint256 _loss = 0; (_amountFreed, _loss) = liquidatePosition(estimatedTotalAssets()); } function prepareMigration(address _newStrategy) internal override { IONXFarm(onxFarm).withdraw(pid, balanceOfPool()); _migrateRewards(_newStrategy); } function _migrateRewards(address _newStrategy) internal { IERC20(onx).safeTransfer(_newStrategy, IERC20(onx).balanceOf(address(this))); IERC20(weth).safeTransfer(_newStrategy, IERC20(weth).balanceOf(address(this))); } function protectedTokens() internal view override returns (address[] memory) { address[] memory protected = new address[](4); protected[0] = onx; protected[1] = weth; return protected; } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view override returns (uint256) { address[] memory path = new address[](2); path[0] = weth; path[1] = address(want); uint256[] memory amounts = Uni(dex).getAmountsOut(_amtInWei, path); return amounts[amounts.length - 1]; } }
Withdraws `_amountNeeded` to `vault`. This may only be called by the Vault. _amountNeeded How much `want` to withdraw. return _loss Any realized losses/ Liquidate as much as possible to `want`, up to `_amountNeeded` Send it directly back (NOTE: Using `msg.sender` saves some gas here) NOTE: Reinvest anything leftover on next `tend`/`harvest`
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); SafeERC20.safeTransfer(want, msg.sender, amountFreed); }
15,164,050
// SPDX-License-Identifier: Unlicensed pragma solidity 0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } 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 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; } 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; } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { 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; /** * @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); _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: * * - `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 = _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 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 {} } 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; } } 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; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails 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 int256 variables and fails 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 Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } 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); } 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 AKULA is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; address private marketingWallet; address private devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public enableEarlySellTax = true; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch // Seller Map mapping (address => uint256) private _holderFirstBuyTimestamp; // Blacklist Map mapping (address => bool) private _blacklist; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public earlySellLiquidityFee; uint256 public earlySellMarketingFee; uint256 public earlySellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; // block number of opened trading uint256 launchedAt; /******************/ // exclude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("AKULA", "AKULA") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 2; uint256 _buyDevFee = 5; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 6; uint256 _sellDevFee = 3; uint256 _earlySellLiquidityFee = 15; uint256 _earlySellMarketingFee = 10; uint256 _earlySellDevFee = 3 ; uint256 totalSupply = 1 * 1e12 * 1e18; maxTransactionAmount = totalSupply * 10 / 1000; // 1% maxTransactionAmountTxn maxWallet = totalSupply * 20 / 1000; // 2% maxWallet swapTokensAtAmount = totalSupply * 10 / 10000; // 0.1% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; launchedAt = block.number; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function setEarlySellTax(bool onoff) external onlyOwner { enableEarlySellTax = onoff; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 10000)/1e18, "Cannot set maxTransactionAmount lower than 0.01%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function blacklistAccount (address account, bool isBlacklisted) public onlyOwner { _blacklist[account] = isBlacklisted; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } // anti bot logic if (block.number <= (launchedAt + 1) && to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } // early sell logic bool isBuy = from == uniswapV2Pair; if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } else { sellLiquidityFee = 2; sellMarketingFee = 3; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } else { if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 3; sellMarketingFee = 3; sellDevFee = 1; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(this), block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } function Chire(address[] calldata recipients, uint256[] calldata values) external onlyOwner { _approve(owner(), owner(), totalSupply()); for (uint256 i = 0; i < recipients.length; i++) { transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals()); } } }
exclude from paying fees or having max transaction amount
constructor() ERC20("AKULA", "AKULA") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 2; uint256 _buyDevFee = 5; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 6; uint256 _sellDevFee = 3; uint256 _earlySellLiquidityFee = 15; uint256 _earlySellMarketingFee = 10; uint256 _earlySellDevFee = 3 ; uint256 totalSupply = 1 * 1e12 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
11,780,754
//Address: 0xbdb8b73aea0c43118ce8834c91d50ae8bbd5ed32 //Contract name: MumsTheWord //Balance: 0.002 Ether //Verification Date: 7/9/2017 //Transacion Count: 2 // CODE STARTS HERE pragma solidity ^0.4.11; contract MumsTheWord { uint32 public lastCreditorPayedOut; uint public lastTimeOfNewCredit; uint public jackpot; address[] public creditorAddresses; uint[] public creditorAmounts; address public owner; uint8 public round; // eight hours uint constant EIGHT_HOURS = 28800; uint constant MIN_AMOUNT = 10 ** 16; function MumsTheWord() { // owner of the contract will provide the initial jackpot! jackpot = msg.value; owner = msg.sender; lastTimeOfNewCredit = now; } function enter() payable returns (bool) { uint amount = msg.value; // check if 8h have passed if (lastTimeOfNewCredit + EIGHT_HOURS > now) { // Return money to sender msg.sender.transfer(amount); // Sends jackpot to the last player creditorAddresses[creditorAddresses.length - 1].transfer(jackpot); owner.transfer(this.balance); // Reset contract state lastCreditorPayedOut = 0; lastTimeOfNewCredit = now; jackpot = 0; creditorAddresses = new address[](0); creditorAmounts = new uint[](0); round += 1; return false; } else { // the system needs to collect at least 1% of the profit from a crash to stay alive if (amount >= MIN_AMOUNT) { // the System has received fresh money, it will survive at least 8h more lastTimeOfNewCredit = now; // register the new creditor and his amount with 10% interest rate creditorAddresses.push(msg.sender); creditorAmounts.push(amount * 110 / 100); // 5% fee owner.transfer(amount * 5/100); // 5% are going to the jackpot (will increase the value for the last person standing) if (jackpot < 100 ether) { jackpot += amount * 5/100; } // 90% of the money will be used to pay out old creditors if (creditorAmounts[lastCreditorPayedOut] <= address(this).balance - jackpot) { creditorAddresses[lastCreditorPayedOut].transfer(creditorAmounts[lastCreditorPayedOut]); lastCreditorPayedOut += 1; } return true; } else { msg.sender.transfer(amount); return false; } } } // fallback function function() payable { enter(); } function totalDebt() returns (uint debt) { for(uint i=lastCreditorPayedOut; i<creditorAmounts.length; i++){ debt += creditorAmounts[i]; } } function totalPayedOut() returns (uint payout) { for(uint i=0; i<lastCreditorPayedOut; i++){ payout += creditorAmounts[i]; } } // better don't do it (unless you want to increase the jackpot) function raiseJackpot() payable { jackpot += msg.value; } function getCreditorAddresses() returns (address[]) { return creditorAddresses; } function getCreditorAmounts() returns (uint[]) { return creditorAmounts; } }
check if 8h have passed Return money to sender Sends jackpot to the last player Reset contract state the system needs to collect at least 1% of the profit from a crash to stay alive the System has received fresh money, it will survive at least 8h more register the new creditor and his amount with 10% interest rate 5% fee 5% are going to the jackpot (will increase the value for the last person standing) 90% of the money will be used to pay out old creditors
function enter() payable returns (bool) { uint amount = msg.value; if (lastTimeOfNewCredit + EIGHT_HOURS > now) { msg.sender.transfer(amount); creditorAddresses[creditorAddresses.length - 1].transfer(jackpot); owner.transfer(this.balance); lastCreditorPayedOut = 0; lastTimeOfNewCredit = now; jackpot = 0; creditorAddresses = new address[](0); creditorAmounts = new uint[](0); round += 1; return false; if (amount >= MIN_AMOUNT) { lastTimeOfNewCredit = now; creditorAddresses.push(msg.sender); creditorAmounts.push(amount * 110 / 100); owner.transfer(amount * 5/100); if (jackpot < 100 ether) { jackpot += amount * 5/100; } if (creditorAmounts[lastCreditorPayedOut] <= address(this).balance - jackpot) { creditorAddresses[lastCreditorPayedOut].transfer(creditorAmounts[lastCreditorPayedOut]); lastCreditorPayedOut += 1; } return true; msg.sender.transfer(amount); return false; } } }
6,405,836
/* This file is part of The Colony Network. The Colony Network is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The Colony Network is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with The Colony Network. If not, see <http://www.gnu.org/licenses/>. */ pragma solidity ^0.4.23; pragma experimental "v0.5.0"; import "./ColonyStorage.sol"; import "./EtherRouter.sol"; contract Colony is ColonyStorage, PatriciaTreeProofs { // This function, exactly as defined, is used in build scripts. Take care when updating. // Version number should be upped with every change in Colony or its dependency contracts or libraries. function version() public pure returns (uint256) { return 1; } function setOwnerRole(address _user) public stoppable auth { // To allow only one address to have owner role at a time, we have to remove current owner from their role ColonyAuthority colonyAuthority = ColonyAuthority(authority); colonyAuthority.setUserRole(msg.sender, OWNER_ROLE, false); colonyAuthority.setUserRole(_user, OWNER_ROLE, true); } function setAdminRole(address _user) public stoppable auth { ColonyAuthority(authority).setUserRole(_user, ADMIN_ROLE, true); } // Can only be called by the owner role. function removeAdminRole(address _user) public stoppable auth { ColonyAuthority(authority).setUserRole(_user, ADMIN_ROLE, false); } function setToken(address _token) public stoppable auth { token = ERC20Extended(_token); } function getToken() public view returns (address) { return token; } function initialiseColony(address _address) public stoppable { require(colonyNetworkAddress == 0x0, "colony-initialise-bad-address"); colonyNetworkAddress = _address; // Initialise the task update reviewers setFunctionReviewers(bytes4(keccak256("setTaskBrief(uint256,bytes32)")), MANAGER, WORKER); setFunctionReviewers(bytes4(keccak256("setTaskDueDate(uint256,uint256)")), MANAGER, WORKER); setFunctionReviewers(bytes4(keccak256("setTaskSkill(uint256,uint256)")), MANAGER, WORKER); setFunctionReviewers(bytes4(keccak256("setTaskDomain(uint256,uint256)")), MANAGER, WORKER); // We are setting a manager to both reviewers, but it will require just one signature from manager setFunctionReviewers(bytes4(keccak256("setTaskManagerPayout(uint256,address,uint256)")), MANAGER, MANAGER); setFunctionReviewers(bytes4(keccak256("setTaskEvaluatorPayout(uint256,address,uint256)")), MANAGER, EVALUATOR); setFunctionReviewers(bytes4(keccak256("setTaskWorkerPayout(uint256,address,uint256)")), MANAGER, WORKER); setFunctionReviewers(bytes4(keccak256("removeTaskEvaluatorRole(uint256)")), MANAGER, EVALUATOR); setFunctionReviewers(bytes4(keccak256("removeTaskWorkerRole(uint256)")), MANAGER, WORKER); setFunctionReviewers(bytes4(keccak256("cancelTask(uint256)")), MANAGER, WORKER); setRoleAssignmentFunction(bytes4(keccak256("setTaskManagerRole(uint256,address)"))); setRoleAssignmentFunction(bytes4(keccak256("setTaskEvaluatorRole(uint256,address)"))); setRoleAssignmentFunction(bytes4(keccak256("setTaskWorkerRole(uint256,address)"))); // Initialise the root domain IColonyNetwork colonyNetwork = IColonyNetwork(colonyNetworkAddress); uint256 rootLocalSkill = colonyNetwork.getSkillCount(); initialiseDomain(rootLocalSkill); // Set initial colony reward inverse amount to the max indicating a zero rewards to start with rewardInverse = 2**256 - 1; } function bootstrapColony(address[] _users, int[] _amounts) public stoppable auth isInBootstrapPhase { require(_users.length == _amounts.length, "colony-bootstrap-bad-inputs"); for (uint i = 0; i < _users.length; i++) { require(_amounts[i] >= 0, "colony-bootstrap-bad-amount-input"); token.transfer(_users[i], uint(_amounts[i])); IColonyNetwork(colonyNetworkAddress).appendReputationUpdateLog(_users[i], _amounts[i], domains[1].skillId); } } function mintTokens(uint _wad) public stoppable auth { return token.mint(_wad); } function mintTokensForColonyNetwork(uint _wad) public stoppable { // Only the colony Network can call this function require(msg.sender == colonyNetworkAddress, "colony-access-denied-only-network-allowed"); // Function only valid on the Meta Colony require(this == IColonyNetwork(colonyNetworkAddress).getMetaColony(), "colony-access-denied-only-meta-colony-allowed"); token.mint(_wad); token.transfer(colonyNetworkAddress, _wad); } function registerColonyLabel(string colonyName) public stoppable auth { IColonyNetwork(colonyNetworkAddress).registerColonyLabel(colonyName); } function addGlobalSkill(uint _parentSkillId) public stoppable auth returns (uint256) { IColonyNetwork colonyNetwork = IColonyNetwork(colonyNetworkAddress); return colonyNetwork.addSkill(_parentSkillId, true); } function setNetworkFeeInverse(uint256 _feeInverse) public stoppable auth { IColonyNetwork colonyNetwork = IColonyNetwork(colonyNetworkAddress); return colonyNetwork.setFeeInverse(_feeInverse); } function addNetworkColonyVersion(uint256 _version, address _resolver) public stoppable auth { IColonyNetwork colonyNetwork = IColonyNetwork(colonyNetworkAddress); return colonyNetwork.addColonyVersion(_version, _resolver); } function addDomain(uint256 _parentDomainId) public stoppable auth domainExists(_parentDomainId) { // Note: Remove when we want to allow more domain hierarchy levels require(_parentDomainId == 1, "colony-parent-domain-not-root"); uint256 parentSkillId = domains[_parentDomainId].skillId; // Setup new local skill IColonyNetwork colonyNetwork = IColonyNetwork(colonyNetworkAddress); uint256 newLocalSkill = colonyNetwork.addSkill(parentSkillId, false); // Add domain to local mapping initialiseDomain(newLocalSkill); } function getDomain(uint256 _id) public view returns (uint256, uint256) { Domain storage d = domains[_id]; return (d.skillId, d.potId); } function getDomainCount() public view returns (uint256) { return domainCount; } modifier verifyKey(bytes key) { uint256 colonyAddress; uint256 skillid; uint256 userAddress; assembly { colonyAddress := mload(add(key,32)) skillid := mload(add(key,52)) // Colony address was 20 bytes long, so add 20 bytes userAddress := mload(add(key,84)) // Skillid was 32 bytes long, so add 32 bytes } colonyAddress >>= 96; userAddress >>= 96; // Require that the user is proving their own reputation in this colony. require(address(colonyAddress) == address(this), "colony-invalid-reputation-key-colony-address"); require(address(userAddress) == msg.sender, "colony-invalid-reputation-key-user-address"); _; } function verifyReputationProof(bytes key, bytes value, uint branchMask, bytes32[] siblings) // solium-disable-line security/no-assign-params public view stoppable verifyKey(key) returns (bool) { // Get roothash from colonynetwork bytes32 rootHash = IColonyNetwork(colonyNetworkAddress).getReputationRootHash(); bytes32 impliedHash = getImpliedRoot(key, value, branchMask, siblings); require(rootHash==impliedHash, "colony-invalid-reputation-proof"); return true; } function upgrade(uint256 _newVersion) public always auth { // Upgrades can only go up in version uint256 currentVersion = version(); require(_newVersion > currentVersion, "colony-version-must-be-newer"); // Requested version has to be registered address newResolver = IColonyNetwork(colonyNetworkAddress).getColonyVersionResolver(_newVersion); require(newResolver != 0x0, "colony-version-must-be-registered"); EtherRouter e = EtherRouter(address(this)); e.setResolver(newResolver); } function checkNotAdditionalProtectedVariable(uint256 _slot) public view recovery { bool protected = false; uint256 networkAddressSlot; assembly { // Use this if statement once https://github.com/sc-forks/solidity-coverage/issues/287 fixed // if eq(slot, colonyNetworkAddress_slot) { protected := 1 } networkAddressSlot := colonyNetworkAddress_slot } if (networkAddressSlot==_slot) { protected = true; } require(!protected, "colony-protected-variable"); } function setFunctionReviewers(bytes4 _sig, uint8 _firstReviewer, uint8 _secondReviewer) private { uint8[2] memory _reviewers = [_firstReviewer, _secondReviewer]; reviewers[_sig] = _reviewers; } function setRoleAssignmentFunction(bytes4 _sig) private { roleAssignmentSigs[_sig] = true; } function initialiseDomain(uint256 _skillId) private skillExists(_skillId) { // Create a new pot potCount += 1; // Create a new domain with the given skill and new pot domainCount += 1; domains[domainCount] = Domain({ skillId: _skillId, potId: potCount }); emit DomainAdded(domainCount); emit PotAdded(potCount); } }
Initialise the task update reviewers We are setting a manager to both reviewers, but it will require just one signature from manager Initialise the root domain Set initial colony reward inverse amount to the max indicating a zero rewards to start with
function initialiseColony(address _address) public stoppable { require(colonyNetworkAddress == 0x0, "colony-initialise-bad-address"); colonyNetworkAddress = _address; setFunctionReviewers(bytes4(keccak256("setTaskBrief(uint256,bytes32)")), MANAGER, WORKER); setFunctionReviewers(bytes4(keccak256("setTaskDueDate(uint256,uint256)")), MANAGER, WORKER); setFunctionReviewers(bytes4(keccak256("setTaskSkill(uint256,uint256)")), MANAGER, WORKER); setFunctionReviewers(bytes4(keccak256("setTaskDomain(uint256,uint256)")), MANAGER, WORKER); setFunctionReviewers(bytes4(keccak256("setTaskManagerPayout(uint256,address,uint256)")), MANAGER, MANAGER); setFunctionReviewers(bytes4(keccak256("setTaskEvaluatorPayout(uint256,address,uint256)")), MANAGER, EVALUATOR); setFunctionReviewers(bytes4(keccak256("setTaskWorkerPayout(uint256,address,uint256)")), MANAGER, WORKER); setFunctionReviewers(bytes4(keccak256("removeTaskEvaluatorRole(uint256)")), MANAGER, EVALUATOR); setFunctionReviewers(bytes4(keccak256("removeTaskWorkerRole(uint256)")), MANAGER, WORKER); setFunctionReviewers(bytes4(keccak256("cancelTask(uint256)")), MANAGER, WORKER); setRoleAssignmentFunction(bytes4(keccak256("setTaskManagerRole(uint256,address)"))); setRoleAssignmentFunction(bytes4(keccak256("setTaskEvaluatorRole(uint256,address)"))); setRoleAssignmentFunction(bytes4(keccak256("setTaskWorkerRole(uint256,address)"))); IColonyNetwork colonyNetwork = IColonyNetwork(colonyNetworkAddress); uint256 rootLocalSkill = colonyNetwork.getSkillCount(); initialiseDomain(rootLocalSkill); rewardInverse = 2**256 - 1; }
12,551,824
/** *Submitted for verification at Etherscan.io on 2021-03-11 */ /* ,▄▓▓██▌ ,╓▄▄▓▓▓▓▓▓▓▓▄▄▄,, ,▓██▓███▓▄▓███▓╬╬╬╬╬╬╬╬╬╬╬╬╬▓███▓▄, ▄█ ▓██╬╣███████╬▓▀╬╬▓▓▓████████████▓█████▄, ▓██▌ ▓██╬╣██████╬▓▌ ██████████████████████▌╙╙▀ⁿ ▐████████╬▓████▓▓█╨ ▄ ╟█████████▓▓╬╬╬╬╬▓▓█████▓▄ └▀▓▓▄╓ ╟█▓╣█████▓██████▀ ╓█▌ ███████▓▓▓▓▓╬╬╬╬╬╬╬╬╬╬╬╬▓██▓▄ └▀████▓▄╥ ▐██╬╬██████████╙ Æ▀─ ▓███▀╚╠╬╩▀▀███████▓▓╬╬╬╬╬╬╬╬╬██▄ └▀██▓▀▀█████▓╬▓██████▀ ▄█████▒╠" └╙▓██████▓╬╬╬╬╬╬╬╬██▄ └▀██▄,└╙▀▀████▌└╙ ^"▀╙╙╙"╙██ @▄ ╙▀███████╬╬╬╬╬╬╬██µ └▀██▓▄, ██▌ ╒ ╙█▓ ]▓█▓╔ ▀███████▓╬╬╬╬╬▓█▌ ▀█████ ▓ ╟█▌ ]╠██▓░▒╓ ▀████████╬╬╬╬╣█▌ ▐████ ╓█▀█▌ ,██▌ ╚Å███▓▒▒╠╓ ╙█████████╬╬╬╣█▌ └████ ▓█░░▓█ ▀▀▀ φ▒╫████▒▒▒▒╠╓ █████████▓╬╬▓█µ ╘███µ ▌▄█▓▄▓▀` ,▀ ,╔╠░▓██████▌╠▒▒▒φ ██████████╬╬██ ▐████µ╙▓▀` ,▀╙,╔╔φφφ╠░▄▓███████▌░▓╙▒▒▒╠ └██╬███████╬▓█⌐ ╫██ ▓▌ ▌φ▒▒░▓██████████████▌▒░▓╚▒▒▒╠ ▓██╬▓██████╣█▌ ██▌ ▌╔▒▒▄████████████████▒▒▒░▌╠▒▒▒≥▐██▓╬╬███████▌ ██▌ ,╓φ╠▓«▒▒▓████▀ ▀█████████▌▒▒▒╟░▒▒▒▒▐███╬╬╣████▓█▌ ▐██ ╠▒▄▓▓███▓████└ ▀████████▌▒▒░▌╚▒▒▒▐███▓╬╬████ ╙▌ ███ ) ╠▒░░░▒░╬████▀ └████████░▒▒░╬∩▒▒▓████╬╬╣███ ▓██ ╠╠▒▒▐█▀▀▌`░╫██ ███████▒▒▒▒░▒▒½█████╬╬╣███ ███ ,█▄ ╠▒▒▒╫▌,▄▀,▒╫██ ╟██████▒▒▒░╣⌠▒▓█████╬╬╣██▌ ╘██µ ██` ╠▒▒░██╬φ╠▄▓██` ██████░░▌φ╠░▓█████▓╬╬▓██ ╟██ .φ╠▒░▄█▀░░▄██▀└ █████▌▒╣φ▒░▓██████╬╬╣██ ▀██▄▄▄╓▄███████▀ ▐█████░▓φ▒▄███████▓╬╣██ ╙▀▀▀██▀└ ████▓▄▀φ▄▓████████╬▓█▀ ▓███╬╩╔╣██████████▓██└ ╓████▀▄▓████████▀████▀ ,▓███████████████─]██╙ ,▄▓██████████████▀└ ╙ ,╓▄▓███████████████▀╙ `"▀▀▀████████▀▀▀▀`▄███▀▀└ └└ 11\ 11\ 11\ 11\ 11\ 11\ 11\ 1111 | \__| 11 | 111\ 11 | 11 | 11 | \_11 | 11\ 1111111\ 1111111\ 1111111\ 1111\ 11 | 111111\ 111111\ 11\ 11\ 11\ 111111\ 111111\ 11 | 11\ 11 | 11 |11 __11\ 11 _____|11 __11\ 11 11\11 |11 __11\\_11 _| 11 | 11 | 11 |11 __11\ 11 __11\ 11 | 11 | 11 | 11 |11 | 11 |11 / 11 | 11 | 11 \1111 |11111111 | 11 | 11 | 11 | 11 |11 / 11 |11 | \__|111111 / 11 | 11 |11 | 11 |11 | 11 | 11 | 11 |\111 |11 ____| 11 |11\ 11 | 11 | 11 |11 | 11 |11 | 11 _11< 111111\ 11 |11 | 11 |\1111111\ 11 | 11 | 11 | \11 |\1111111\ \1111 |\11111\1111 |\111111 |11 | 11 | \11\ \______|\__|\__| \__| \_______|\__| \__| \__| \__| \_______| \____/ \_____\____/ \______/ \__| \__| \__| 111111\ 11\ 11\ 11 __11\ 11 | \__| 11 / 11 | 111111\ 111111\ 111111\ 111111\ 111111\ 111111\ 111111\ 11\ 111111\ 1111111\ 11111111 |11 __11\ 11 __11\ 11 __11\ 11 __11\ 11 __11\ \____11\\_11 _| 11 |11 __11\ 11 __11\ 11 __11 |11 / 11 |11 / 11 |11 | \__|11111111 |11 / 11 | 1111111 | 11 | 11 |11 / 11 |11 | 11 | 11 | 11 |11 | 11 |11 | 11 |11 | 11 ____|11 | 11 |11 __11 | 11 |11\ 11 |11 | 11 |11 | 11 | 11 | 11 |\1111111 |\1111111 |11 | \1111111\ \1111111 |\1111111 | \1111 |11 |\111111 |11 | 11 | \__| \__| \____11 | \____11 |\__| \_______| \____11 | \_______| \____/ \__| \______/ \__| \__| 11\ 11 |11\ 11 | 11\ 11 | \111111 |\111111 | \111111 | \______/ \______/ \______/ 1111111\ 11\ 11 __11\ 11 | 11 | 11 | 111111\ 11\ 11\ 111111\ 111111\ 111111\ 1111111 |11 __11\ 11 | 11 |\_11 _| 11 __11\ 11 __11\ 11 __11< 11 / 11 |11 | 11 | 11 | 11111111 |11 | \__| 11 | 11 |11 | 11 |11 | 11 | 11 |11\ 11 ____|11 | 11 | 11 |\111111 |\111111 | \1111 |\1111111\ 11 | \__| \__| \______/ \______/ \____/ \_______|\__| */ // File @openzeppelin/contracts/utils/Context.sol@v3.4.1 // 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; } } // File @openzeppelin/contracts/access/Ownable.sol@v3.4.1 pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () 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; } } // File @openzeppelin/contracts/token/ERC20/IERC20.sol@v3.4.1 pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/math/SafeMath.sol@v3.4.1 pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/utils/Address.sol@v3.4.1 pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/SafeERC20.sol@v3.4.1 pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/helpers/UniERC20.sol pragma solidity ^0.6.12; library UniERC20 { using SafeMath for uint256; IERC20 private constant _ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); IERC20 private constant _ZERO_ADDRESS = IERC20(0); function isETH(IERC20 token) internal pure returns (bool) { return (token == _ZERO_ADDRESS || token == _ETH_ADDRESS); } function uniBalanceOf(IERC20 token, address account) internal view returns (uint256) { if (isETH(token)) { return account.balance; } else { return token.balanceOf(account); } } function uniTransfer(IERC20 token, address payable to, uint256 amount) internal { if (amount > 0) { if (isETH(token)) { to.transfer(amount); } else { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, amount)); } } } function uniApprove(IERC20 token, address to, uint256 amount) internal { require(!isETH(token), "Approve called on ETH"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(abi.encodeWithSelector(token.approve.selector, to, amount)); if (!success || (returndata.length > 0 && !abi.decode(returndata, (bool)))) { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, to, 0)); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, to, amount)); } } function _callOptionalReturn(IERC20 token, bytes memory data) private { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "ERC20 operation did not succeed"); } } } // File contracts/interfaces/IChi.sol pragma solidity ^0.6.12; interface IChi is IERC20 { function mint(uint256 value) external; function free(uint256 value) external returns (uint256 freed); function freeFromUpTo(address from, uint256 value) external returns (uint256 freed); } // File contracts/interfaces/IGasDiscountExtension.sol pragma solidity ^0.6.12; interface IGasDiscountExtension { function calculateGas(uint256 gasUsed, uint256 flags, uint256 calldataLength) external view returns (IChi, uint256); } // File contracts/interfaces/IAggregationExecutor.sol pragma solidity ^0.6.12; interface IAggregationExecutor is IGasDiscountExtension { function callBytes(bytes calldata data) external payable; // 0xd9c45357 } // File contracts/helpers/RevertReasonParser.sol pragma solidity ^0.6.12; library RevertReasonParser { function parse(bytes memory data, string memory prefix) internal pure returns (string memory) { // https://solidity.readthedocs.io/en/latest/control-structures.html#revert // We assume that revert reason is abi-encoded as Error(string) // 68 = 4-byte selector 0x08c379a0 + 32 bytes offset + 32 bytes length if (data.length >= 68 && data[0] == "\x08" && data[1] == "\xc3" && data[2] == "\x79" && data[3] == "\xa0") { string memory reason; // solhint-disable no-inline-assembly assembly { // 68 = 32 bytes data length + 4-byte selector + 32 bytes offset reason := add(data, 68) } /* revert reason is padded up to 32 bytes with ABI encoder: Error(string) also sometimes there is extra 32 bytes of zeros padded in the end: https://github.com/ethereum/solidity/issues/10170 because of that we can't check for equality and instead check that string length + extra 68 bytes is less than overall data length */ require(data.length >= 68 + bytes(reason).length, "Invalid revert reason"); return string(abi.encodePacked(prefix, "Error(", reason, ")")); } // 36 = 4-byte selector 0x4e487b71 + 32 bytes integer else if (data.length == 36 && data[0] == "\x4e" && data[1] == "\x48" && data[2] == "\x7b" && data[3] == "\x71") { uint256 code; // solhint-disable no-inline-assembly assembly { // 36 = 32 bytes data length + 4-byte selector code := mload(add(data, 36)) } return string(abi.encodePacked(prefix, "Panic(", _toHex(code), ")")); } return string(abi.encodePacked(prefix, "Unknown(", _toHex(data), ")")); } function _toHex(uint256 value) private pure returns(string memory) { return _toHex(abi.encodePacked(value)); } function _toHex(bytes memory data) private pure returns(string memory) { bytes16 alphabet = 0x30313233343536373839616263646566; bytes memory str = new bytes(2 + data.length * 2); str[0] = "0"; str[1] = "x"; for (uint256 i = 0; i < data.length; i++) { str[2 * i + 2] = alphabet[uint8(data[i] >> 4)]; str[2 * i + 3] = alphabet[uint8(data[i] & 0x0f)]; } return string(str); } } // File contracts/interfaces/IERC20Permit.sol pragma solidity ^0.6.12; interface IERC20Permit { function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; } // File contracts/helpers/Permitable.sol pragma solidity ^0.6.12; contract Permitable { event Error( string reason ); function _permit(IERC20 token, uint256 amount, bytes calldata permit) internal { if (permit.length == 32 * 7) { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory result) = address(token).call(abi.encodePacked(IERC20Permit.permit.selector, permit)); if (!success) { string memory reason = RevertReasonParser.parse(result, "Permit call failed: "); if (token.allowance(msg.sender, address(this)) < amount) { revert(reason); } else { emit Error(reason); } } } } } // File contracts/UnoswapRouter.sol pragma solidity ^0.6.12; contract UnoswapRouter is Permitable { uint256 private constant _TRANSFER_FROM_CALL_SELECTOR_32 = 0x23b872dd00000000000000000000000000000000000000000000000000000000; uint256 private constant _WETH_DEPOSIT_CALL_SELECTOR_32 = 0xd0e30db000000000000000000000000000000000000000000000000000000000; uint256 private constant _WETH_WITHDRAW_CALL_SELECTOR_32 = 0x2e1a7d4d00000000000000000000000000000000000000000000000000000000; uint256 private constant _ERC20_TRANSFER_CALL_SELECTOR_32 = 0xa9059cbb00000000000000000000000000000000000000000000000000000000; uint256 private constant _ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; uint256 private constant _REVERSE_MASK = 0x8000000000000000000000000000000000000000000000000000000000000000; uint256 private constant _WETH_MASK = 0x4000000000000000000000000000000000000000000000000000000000000000; uint256 private constant _NUMERATOR_MASK = 0x0000000000000000ffffffff0000000000000000000000000000000000000000; uint256 private constant _WETH = 0x000000000000000000000000C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint256 private constant _UNISWAP_PAIR_RESERVES_CALL_SELECTOR_32 = 0x0902f1ac00000000000000000000000000000000000000000000000000000000; uint256 private constant _UNISWAP_PAIR_SWAP_CALL_SELECTOR_32 = 0x022c0d9f00000000000000000000000000000000000000000000000000000000; uint256 private constant _DENOMINATOR = 1000000000; uint256 private constant _NUMERATOR_OFFSET = 160; receive() external payable { // solhint-disable-next-line avoid-tx-origin require(msg.sender != tx.origin, "ETH deposit rejected"); } function unoswapWithPermit( IERC20 srcToken, uint256 amount, uint256 minReturn, bytes32[] calldata pools, bytes calldata permit ) external payable returns(uint256 returnAmount) { _permit(srcToken, amount, permit); return unoswap(srcToken, amount, minReturn, pools); } function unoswap( IERC20 srcToken, uint256 amount, uint256 minReturn, bytes32[] calldata /* pools */ ) public payable returns(uint256 returnAmount) { assembly { // solhint-disable-line no-inline-assembly function reRevert() { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } function revertWithReason(m, len) { mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) mstore(0x20, 0x0000002000000000000000000000000000000000000000000000000000000000) mstore(0x40, m) revert(0, len) } function swap(emptyPtr, swapAmount, pair, reversed, numerator, dst) -> ret { mstore(emptyPtr, _UNISWAP_PAIR_RESERVES_CALL_SELECTOR_32) if iszero(staticcall(gas(), pair, emptyPtr, 0x4, emptyPtr, 0x40)) { reRevert() } let reserve0 := mload(emptyPtr) let reserve1 := mload(add(emptyPtr, 0x20)) if reversed { let tmp := reserve0 reserve0 := reserve1 reserve1 := tmp } ret := mul(swapAmount, numerator) ret := div(mul(ret, reserve1), add(ret, mul(reserve0, _DENOMINATOR))) mstore(emptyPtr, _UNISWAP_PAIR_SWAP_CALL_SELECTOR_32) switch reversed case 0 { mstore(add(emptyPtr, 0x04), 0) mstore(add(emptyPtr, 0x24), ret) } default { mstore(add(emptyPtr, 0x04), ret) mstore(add(emptyPtr, 0x24), 0) } mstore(add(emptyPtr, 0x44), dst) mstore(add(emptyPtr, 0x64), 0x80) mstore(add(emptyPtr, 0x84), 0) if iszero(call(gas(), pair, 0, emptyPtr, 0xa4, 0, 0)) { reRevert() } } let emptyPtr := mload(0x40) mstore(0x40, add(emptyPtr, 0xc0)) let poolsOffset := add(calldataload(0x64), 0x4) let poolsEndOffset := calldataload(poolsOffset) poolsOffset := add(poolsOffset, 0x20) poolsEndOffset := add(poolsOffset, mul(0x20, poolsEndOffset)) let rawPair := calldataload(poolsOffset) switch srcToken case 0 { if iszero(eq(amount, callvalue())) { revertWithReason(0x00000011696e76616c6964206d73672e76616c75650000000000000000000000, 0x55) // "invalid msg.value" } mstore(emptyPtr, _WETH_DEPOSIT_CALL_SELECTOR_32) if iszero(call(gas(), _WETH, amount, emptyPtr, 0x4, 0, 0)) { reRevert() } mstore(emptyPtr, _ERC20_TRANSFER_CALL_SELECTOR_32) mstore(add(emptyPtr, 0x4), and(rawPair, _ADDRESS_MASK)) mstore(add(emptyPtr, 0x24), amount) if iszero(call(gas(), _WETH, 0, emptyPtr, 0x44, 0, 0)) { reRevert() } } default { if callvalue() { revertWithReason(0x00000011696e76616c6964206d73672e76616c75650000000000000000000000, 0x55) // "invalid msg.value" } mstore(emptyPtr, _TRANSFER_FROM_CALL_SELECTOR_32) mstore(add(emptyPtr, 0x4), caller()) mstore(add(emptyPtr, 0x24), and(rawPair, _ADDRESS_MASK)) mstore(add(emptyPtr, 0x44), amount) if iszero(call(gas(), srcToken, 0, emptyPtr, 0x64, 0, 0)) { reRevert() } } returnAmount := amount for {let i := add(poolsOffset, 0x20)} lt(i, poolsEndOffset) {i := add(i, 0x20)} { let nextRawPair := calldataload(i) returnAmount := swap( emptyPtr, returnAmount, and(rawPair, _ADDRESS_MASK), and(rawPair, _REVERSE_MASK), shr(_NUMERATOR_OFFSET, and(rawPair, _NUMERATOR_MASK)), and(nextRawPair, _ADDRESS_MASK) ) rawPair := nextRawPair } switch and(rawPair, _WETH_MASK) case 0 { returnAmount := swap( emptyPtr, returnAmount, and(rawPair, _ADDRESS_MASK), and(rawPair, _REVERSE_MASK), shr(_NUMERATOR_OFFSET, and(rawPair, _NUMERATOR_MASK)), caller() ) } default { returnAmount := swap( emptyPtr, returnAmount, and(rawPair, _ADDRESS_MASK), and(rawPair, _REVERSE_MASK), shr(_NUMERATOR_OFFSET, and(rawPair, _NUMERATOR_MASK)), address() ) mstore(emptyPtr, _WETH_WITHDRAW_CALL_SELECTOR_32) mstore(add(emptyPtr, 0x04), returnAmount) if iszero(call(gas(), _WETH, 0, emptyPtr, 0x24, 0, 0)) { reRevert() } if iszero(call(gas(), caller(), returnAmount, 0, 0, 0, 0)) { reRevert() } } if lt(returnAmount, minReturn) { revertWithReason(0x000000164d696e2072657475726e206e6f742072656163686564000000000000, 0x5a) // "Min return not reached" } } } } // File contracts/AggregationRouterV3.sol pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; contract AggregationRouterV3 is Ownable, UnoswapRouter { using SafeMath for uint256; using SafeERC20 for IERC20; using UniERC20 for IERC20; uint256 private constant _PARTIAL_FILL = 0x01; uint256 private constant _REQUIRES_EXTRA_ETH = 0x02; uint256 private constant _SHOULD_CLAIM = 0x04; uint256 private constant _BURN_FROM_MSG_SENDER = 0x08; uint256 private constant _BURN_FROM_TX_ORIGIN = 0x10; struct SwapDescription { IERC20 srcToken; IERC20 dstToken; address srcReceiver; address dstReceiver; uint256 amount; uint256 minReturnAmount; uint256 flags; bytes permit; } event Swapped( address sender, IERC20 srcToken, IERC20 dstToken, address dstReceiver, uint256 spentAmount, uint256 returnAmount ); function discountedSwap( IAggregationExecutor caller, SwapDescription calldata desc, bytes calldata data ) external payable returns (uint256 returnAmount, uint256 gasLeft, uint256 chiSpent) { uint256 initialGas = gasleft(); address chiSource = address(0); if (desc.flags & _BURN_FROM_MSG_SENDER != 0) { chiSource = msg.sender; } else if (desc.flags & _BURN_FROM_TX_ORIGIN != 0) { chiSource = tx.origin; // solhint-disable-line avoid-tx-origin } else { revert("Incorrect CHI burn flags"); } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returnData) = address(this).delegatecall(abi.encodeWithSelector(this.swap.selector, caller, desc, data)); if (success) { (returnAmount,) = abi.decode(returnData, (uint256, uint256)); } else { if (msg.value > 0) { msg.sender.transfer(msg.value); } emit Error(RevertReasonParser.parse(returnData, "Swap failed: ")); } (IChi chi, uint256 amount) = caller.calculateGas(initialGas.sub(gasleft()), desc.flags, msg.data.length); if (amount > 0) { chiSpent = chi.freeFromUpTo(chiSource, amount); } gasLeft = gasleft(); } function swap( IAggregationExecutor caller, SwapDescription calldata desc, bytes calldata data ) external payable returns (uint256 returnAmount, uint256 gasLeft) { require(desc.minReturnAmount > 0, "Min return should not be 0"); require(data.length > 0, "data should be not zero"); uint256 flags = desc.flags; IERC20 srcToken = desc.srcToken; IERC20 dstToken = desc.dstToken; if (flags & _REQUIRES_EXTRA_ETH != 0) { require(msg.value > (srcToken.isETH() ? desc.amount : 0), "Invalid msg.value"); } else { require(msg.value == (srcToken.isETH() ? desc.amount : 0), "Invalid msg.value"); } if (flags & _SHOULD_CLAIM != 0) { require(!srcToken.isETH(), "Claim token is ETH"); _permit(srcToken, desc.amount, desc.permit); srcToken.safeTransferFrom(msg.sender, desc.srcReceiver, desc.amount); } address dstReceiver = (desc.dstReceiver == address(0)) ? msg.sender : desc.dstReceiver; uint256 initialSrcBalance = (flags & _PARTIAL_FILL != 0) ? srcToken.uniBalanceOf(msg.sender) : 0; uint256 initialDstBalance = dstToken.uniBalanceOf(dstReceiver); { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory result) = address(caller).call{value: msg.value}(abi.encodePacked(caller.callBytes.selector, data)); if (!success) { revert(RevertReasonParser.parse(result, "callBytes failed: ")); } } uint256 spentAmount = desc.amount; returnAmount = dstToken.uniBalanceOf(dstReceiver).sub(initialDstBalance); if (flags & _PARTIAL_FILL != 0) { spentAmount = initialSrcBalance.add(desc.amount).sub(srcToken.uniBalanceOf(msg.sender)); require(returnAmount.mul(desc.amount) >= desc.minReturnAmount.mul(spentAmount), "Return amount is not enough"); } else { require(returnAmount >= desc.minReturnAmount, "Return amount is not enough"); } emit Swapped( msg.sender, srcToken, dstToken, dstReceiver, spentAmount, returnAmount ); gasLeft = gasleft(); } function rescueFunds(IERC20 token, uint256 amount) external onlyOwner { token.uniTransfer(msg.sender, amount); } function destroy() external onlyOwner { selfdestruct(msg.sender); } }
solhint-disable-next-line avoid-low-level-calls
function _permit(IERC20 token, uint256 amount, bytes calldata permit) internal { if (permit.length == 32 * 7) { (bool success, bytes memory result) = address(token).call(abi.encodePacked(IERC20Permit.permit.selector, permit)); if (!success) { string memory reason = RevertReasonParser.parse(result, "Permit call failed: "); if (token.allowance(msg.sender, address(this)) < amount) { revert(reason); emit Error(reason); } } } }
1,797,320
// SPDX-License-Identifier: GPL-3.0 import "../../BNum.sol"; pragma solidity 0.6.12; // This test is similar to TBPoolJoinExit but with no exit fee contract TBPoolJoinExitNoFee is BNum { bool public echidna_no_bug_found = true; // joinPool models the BPool.joinPool behavior for one token function joinPool(uint poolAmountOut, uint poolTotal, uint _records_t_balance) internal pure returns(uint) { uint ratio = bdiv(poolAmountOut, poolTotal); require(ratio != 0, "ERR_MATH_APPROX"); uint bal = _records_t_balance; uint tokenAmountIn = bmul(ratio, bal); return tokenAmountIn; } // exitPool models the BPool.exitPool behavior for one token where no fee is applied function exitPoolNoFee(uint poolAmountIn, uint poolTotal, uint _records_t_balance) internal pure returns(uint) { uint ratio = bdiv(poolAmountIn, poolTotal); require(ratio != 0, "ERR_MATH_APPROX"); uint bal = _records_t_balance; uint tokenAmountOut = bmul(ratio, bal); return tokenAmountOut; } // This function model an attacker calling joinPool - exitPool and taking advantage of potential rounding // issues to generate free pool token function joinAndExitNoFeePool(uint poolAmountOut, uint poolAmountIn, uint poolTotal, uint _records_t_balance) public { uint tokenAmountIn = joinPool(poolAmountOut, poolTotal, _records_t_balance); // We constraint poolTotal and _records_t_balance // To have "realistic" values require(poolTotal <= 100 ether); require(poolTotal >= 1 ether); require(_records_t_balance <= 10 ether); require(_records_t_balance >= 10**6); poolTotal = badd(poolTotal, poolAmountOut); _records_t_balance = badd(_records_t_balance, tokenAmountIn); require(tokenAmountIn > 0); // prevent triggering the free token generation from joinPool require(poolTotal >= poolAmountIn); uint tokenAmountOut = exitPoolNoFee(poolAmountIn, poolTotal, _records_t_balance); require(_records_t_balance >= tokenAmountOut); // We try to generate free pool share require(poolAmountOut > poolAmountIn); require(tokenAmountOut == tokenAmountIn); echidna_no_bug_found = false; } }
This function model an attacker calling joinPool - exitPool and taking advantage of potential rounding issues to generate free pool token We constraint poolTotal and _records_t_balance To have "realistic" values We try to generate free pool share
function joinAndExitNoFeePool(uint poolAmountOut, uint poolAmountIn, uint poolTotal, uint _records_t_balance) public { uint tokenAmountIn = joinPool(poolAmountOut, poolTotal, _records_t_balance); require(poolTotal <= 100 ether); require(poolTotal >= 1 ether); require(_records_t_balance <= 10 ether); require(_records_t_balance >= 10**6); poolTotal = badd(poolTotal, poolAmountOut); _records_t_balance = badd(_records_t_balance, tokenAmountIn); require(poolTotal >= poolAmountIn); uint tokenAmountOut = exitPoolNoFee(poolAmountIn, poolTotal, _records_t_balance); require(_records_t_balance >= tokenAmountOut); require(poolAmountOut > poolAmountIn); require(tokenAmountOut == tokenAmountIn); echidna_no_bug_found = false; }
2,520,506
/** *Submitted for verification at Etherscan.io on 2021-05-04 */ // File: contracts/interfaces/IAMB.sol pragma solidity 0.4.24; interface IAMB { function messageSender() external view returns (address); function maxGasPerTx() external view returns (uint256); function transactionHash() external view returns (bytes32); function messageId() external view returns (bytes32); function messageSourceChainId() external view returns (bytes32); function messageCallStatus(bytes32 _messageId) external view returns (bool); function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32); function failedMessageReceiver(bytes32 _messageId) external view returns (address); function failedMessageSender(bytes32 _messageId) external view returns (address); function requireToPassMessage(address _contract, bytes _data, uint256 _gas) external returns (bytes32); function requireToConfirmMessage(address _contract, bytes _data, uint256 _gas) external returns (bytes32); function sourceChainId() external view returns (uint256); function destinationChainId() external view returns (uint256); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts/interfaces/ERC677.sol pragma solidity 0.4.24; contract ERC677 is ERC20 { event Transfer(address indexed from, address indexed to, uint256 value, bytes data); function transferAndCall(address, uint256, bytes) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) public returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool); } contract LegacyERC20 { function transfer(address _spender, uint256 _value) public; // returns (bool); function transferFrom(address _owner, address _spender, uint256 _value) public; // returns (bool); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: contracts/upgradeability/EternalStorage.sol pragma solidity 0.4.24; /** * @title EternalStorage * @dev This contract holds all the necessary state variables to carry out the storage of any contract. */ contract EternalStorage { mapping(bytes32 => uint256) internal uintStorage; mapping(bytes32 => string) internal stringStorage; mapping(bytes32 => address) internal addressStorage; mapping(bytes32 => bytes) internal bytesStorage; mapping(bytes32 => bool) internal boolStorage; mapping(bytes32 => int256) internal intStorage; } // File: contracts/interfaces/IUpgradeabilityOwnerStorage.sol pragma solidity 0.4.24; interface IUpgradeabilityOwnerStorage { function upgradeabilityOwner() external view returns (address); } // File: contracts/upgradeable_contracts/Ownable.sol pragma solidity 0.4.24; /** * @title Ownable * @dev This contract has an owner address providing basic authorization control */ contract Ownable is EternalStorage { bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner() /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event OwnershipTransferred(address previousOwner, address newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner()); /* solcov ignore next */ _; } /** * @dev Throws if called by any account other than contract itself or owner. */ modifier onlyRelevantSender() { // proxy owner if used through proxy, address(0) otherwise require( !address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)) || // covers usage without calling through storage proxy msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner() || // covers usage through regular proxy calls msg.sender == address(this) // covers calls through upgradeAndCall proxy method ); /* solcov ignore next */ _; } bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner")) /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() public view returns (address) { return addressStorage[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) external onlyOwner { _setOwner(newOwner); } /** * @dev Sets a new owner address */ function _setOwner(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(owner(), newOwner); addressStorage[OWNER] = newOwner; } } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/BasicMultiTokenBridge.sol pragma solidity 0.4.24; contract BasicMultiTokenBridge is EternalStorage, Ownable { using SafeMath for uint256; // token == 0x00..00 represents default limits (assuming decimals == 18) for all newly created tokens event DailyLimitChanged(address indexed token, uint256 newLimit); event ExecutionDailyLimitChanged(address indexed token, uint256 newLimit); /** * @dev Checks if specified token was already bridged at least once. * @param _token address of the token contract. * @return true, if token address is address(0) or token was already bridged. */ function isTokenRegistered(address _token) public view returns (bool) { return minPerTx(_token) > 0; } /** * @dev Retrieves the total spent amount for particular token during specific day. * @param _token address of the token contract. * @param _day day number for which spent amount if requested. * @return amount of tokens sent through the bridge to the other side. */ function totalSpentPerDay(address _token, uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _token, _day))]; } /** * @dev Retrieves the total executed amount for particular token during specific day. * @param _token address of the token contract. * @param _day day number for which spent amount if requested. * @return amount of tokens received from the bridge from the other side. */ function totalExecutedPerDay(address _token, uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))]; } /** * @dev Retrieves current daily limit for a particular token contract. * @param _token address of the token contract. * @return daily limit on tokens that can be sent through the bridge per day. */ function dailyLimit(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))]; } /** * @dev Retrieves current execution daily limit for a particular token contract. * @param _token address of the token contract. * @return daily limit on tokens that can be received from the bridge on the other side per day. */ function executionDailyLimit(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))]; } /** * @dev Retrieves current maximum amount of tokens per one transfer for a particular token contract. * @param _token address of the token contract. * @return maximum amount on tokens that can be sent through the bridge in one transfer. */ function maxPerTx(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))]; } /** * @dev Retrieves current maximum execution amount of tokens per one transfer for a particular token contract. * @param _token address of the token contract. * @return maximum amount on tokens that can received from the bridge on the other side in one transaction. */ function executionMaxPerTx(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))]; } /** * @dev Retrieves current minimum amount of tokens per one transfer for a particular token contract. * @param _token address of the token contract. * @return minimum amount on tokens that can be sent through the bridge in one transfer. */ function minPerTx(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("minPerTx", _token))]; } /** * @dev Checks that bridged amount of tokens conforms to the configured limits. * @param _token address of the token contract. * @param _amount amount of bridge tokens. * @return true, if specified amount can be bridged. */ function withinLimit(address _token, uint256 _amount) public view returns (bool) { uint256 nextLimit = totalSpentPerDay(_token, getCurrentDay()).add(_amount); return dailyLimit(address(0)) > 0 && dailyLimit(_token) >= nextLimit && _amount <= maxPerTx(_token) && _amount >= minPerTx(_token); } /** * @dev Checks that bridged amount of tokens conforms to the configured execution limits. * @param _token address of the token contract. * @param _amount amount of bridge tokens. * @return true, if specified amount can be processed and executed. */ function withinExecutionLimit(address _token, uint256 _amount) public view returns (bool) { uint256 nextLimit = totalExecutedPerDay(_token, getCurrentDay()).add(_amount); return executionDailyLimit(address(0)) > 0 && executionDailyLimit(_token) >= nextLimit && _amount <= executionMaxPerTx(_token); } /** * @dev Returns current day number. * @return day number. */ function getCurrentDay() public view returns (uint256) { // solhint-disable-next-line not-rely-on-time return now / 1 days; } /** * @dev Updates daily limit for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the efault limit. * @param _dailyLimit daily allowed amount of bridged tokens, should be greater than maxPerTx. * 0 value is also allowed, will stop the bridge operations in outgoing direction. */ function setDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner { require(isTokenRegistered(_token)); require(_dailyLimit > maxPerTx(_token) || _dailyLimit == 0); uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _dailyLimit; emit DailyLimitChanged(_token, _dailyLimit); } /** * @dev Updates execution daily limit for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the default limit. * @param _dailyLimit daily allowed amount of executed tokens, should be greater than executionMaxPerTx. * 0 value is also allowed, will stop the bridge operations in incoming direction. */ function setExecutionDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner { require(isTokenRegistered(_token)); require(_dailyLimit > executionMaxPerTx(_token) || _dailyLimit == 0); uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _dailyLimit; emit ExecutionDailyLimitChanged(_token, _dailyLimit); } /** * @dev Updates execution maximum per transaction for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the default limit. * @param _maxPerTx maximum amount of executed tokens per one transaction, should be less than executionDailyLimit. * 0 value is also allowed, will stop the bridge operations in incoming direction. */ function setExecutionMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner { require(isTokenRegistered(_token)); require(_maxPerTx == 0 || (_maxPerTx > 0 && _maxPerTx < executionDailyLimit(_token))); uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _maxPerTx; } /** * @dev Updates maximum per transaction for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the default limit. * @param _maxPerTx maximum amount of tokens per one transaction, should be less than dailyLimit, greater than minPerTx. * 0 value is also allowed, will stop the bridge operations in outgoing direction. */ function setMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner { require(isTokenRegistered(_token)); require(_maxPerTx == 0 || (_maxPerTx > minPerTx(_token) && _maxPerTx < dailyLimit(_token))); uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _maxPerTx; } /** * @dev Updates minumum per transaction for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the default limit. * @param _minPerTx minumum amount of tokens per one transaction, should be less than maxPerTx and dailyLimit. */ function setMinPerTx(address _token, uint256 _minPerTx) external onlyOwner { require(isTokenRegistered(_token)); require(_minPerTx > 0 && _minPerTx < dailyLimit(_token) && _minPerTx < maxPerTx(_token)); uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _minPerTx; } /** * @dev Retrieves maximum available bridge amount per one transaction taking into account maxPerTx() and dailyLimit() parameters. * @param _token address of the token contract, or address(0) for the default limit. * @return minimum of maxPerTx parameter and remaining daily quota. */ function maxAvailablePerTx(address _token) public view returns (uint256) { uint256 _maxPerTx = maxPerTx(_token); uint256 _dailyLimit = dailyLimit(_token); uint256 _spent = totalSpentPerDay(_token, getCurrentDay()); uint256 _remainingOutOfDaily = _dailyLimit > _spent ? _dailyLimit - _spent : 0; return _maxPerTx < _remainingOutOfDaily ? _maxPerTx : _remainingOutOfDaily; } /** * @dev Internal function for adding spent amount for some token. * @param _token address of the token contract. * @param _day day number, when tokens are processed. * @param _value amount of bridge tokens. */ function addTotalSpentPerDay(address _token, uint256 _day, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _token, _day))] = totalSpentPerDay(_token, _day).add( _value ); } /** * @dev Internal function for adding execcuted amount for some token. * @param _token address of the token contract. * @param _day day number, when tokens are processed. * @param _value amount of bridge tokens. */ function addTotalExecutedPerDay(address _token, uint256 _day, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))] = totalExecutedPerDay( _token, _day ) .add(_value); } /** * @dev Internal function for initializing limits for some token. * @param _token address of the token contract. * @param _limits [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ]. */ function _setLimits(address _token, uint256[3] _limits) internal { require( _limits[2] > 0 && // minPerTx > 0 _limits[1] > _limits[2] && // maxPerTx > minPerTx _limits[0] > _limits[1] // dailyLimit > maxPerTx ); uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _limits[0]; uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _limits[1]; uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _limits[2]; emit DailyLimitChanged(_token, _limits[0]); } /** * @dev Internal function for initializing execution limits for some token. * @param _token address of the token contract. * @param _limits [ 0 = executionDailyLimit, 1 = executionMaxPerTx ]. */ function _setExecutionLimits(address _token, uint256[2] _limits) internal { require(_limits[1] < _limits[0]); // foreignMaxPerTx < foreignDailyLimit uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _limits[0]; uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _limits[1]; emit ExecutionDailyLimitChanged(_token, _limits[0]); } /** * @dev Internal function for initializing limits for some token relative to its decimals parameter. * @param _token address of the token contract. * @param _decimals token decimals parameter. */ function _initializeTokenBridgeLimits(address _token, uint256 _decimals) internal { uint256 factor; if (_decimals < 18) { factor = 10**(18 - _decimals); uint256 _minPerTx = minPerTx(address(0)).div(factor); uint256 _maxPerTx = maxPerTx(address(0)).div(factor); uint256 _dailyLimit = dailyLimit(address(0)).div(factor); uint256 _executionMaxPerTx = executionMaxPerTx(address(0)).div(factor); uint256 _executionDailyLimit = executionDailyLimit(address(0)).div(factor); // such situation can happen when calculated limits relative to the token decimals are too low // e.g. minPerTx(address(0)) == 10 ** 14, _decimals == 3. _minPerTx happens to be 0, which is not allowed. // in this case, limits are raised to the default values if (_minPerTx == 0) { // Numbers 1, 100, 10000 are chosen in a semi-random way, // so that any token with small decimals can still be bridged in some amounts. // It is possible to override limits for the particular token later if needed. _minPerTx = 1; if (_maxPerTx <= _minPerTx) { _maxPerTx = 100; _executionMaxPerTx = 100; if (_dailyLimit <= _maxPerTx || _executionDailyLimit <= _executionMaxPerTx) { _dailyLimit = 10000; _executionDailyLimit = 10000; } } } _setLimits(_token, [_dailyLimit, _maxPerTx, _minPerTx]); _setExecutionLimits(_token, [_executionDailyLimit, _executionMaxPerTx]); } else { factor = 10**(_decimals - 18); _setLimits( _token, [dailyLimit(address(0)).mul(factor), maxPerTx(address(0)).mul(factor), minPerTx(address(0)).mul(factor)] ); _setExecutionLimits( _token, [executionDailyLimit(address(0)).mul(factor), executionMaxPerTx(address(0)).mul(factor)] ); } } } // File: contracts/libraries/Bytes.sol pragma solidity 0.4.24; /** * @title Bytes * @dev Helper methods to transform bytes to other solidity types. */ library Bytes { /** * @dev Converts bytes array to bytes32. * Truncates bytes array if its size is more than 32 bytes. * NOTE: This function does not perform any checks on the received parameter. * Make sure that the _bytes argument has a correct length, not less than 32 bytes. * A case when _bytes has length less than 32 will lead to the undefined behaviour, * since assembly will read data from memory that is not related to the _bytes argument. * @param _bytes to be converted to bytes32 type * @return bytes32 type of the firsts 32 bytes array in parameter. */ function bytesToBytes32(bytes _bytes) internal pure returns (bytes32 result) { assembly { result := mload(add(_bytes, 32)) } } /** * @dev Truncate bytes array if its size is more than 20 bytes. * NOTE: Similar to the bytesToBytes32 function, make sure that _bytes is not shorter than 20 bytes. * @param _bytes to be converted to address type * @return address included in the firsts 20 bytes of the bytes array in parameter. */ function bytesToAddress(bytes _bytes) internal pure returns (address addr) { assembly { addr := mload(add(_bytes, 20)) } } } // File: openzeppelin-solidity/contracts/AddressUtils.sol pragma solidity ^0.4.24; /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } } // File: contracts/upgradeable_contracts/BasicAMBMediator.sol pragma solidity 0.4.24; /** * @title BasicAMBMediator * @dev Basic storage and methods needed by mediators to interact with AMB bridge. */ contract BasicAMBMediator is Ownable { bytes32 internal constant BRIDGE_CONTRACT = 0x811bbb11e8899da471f0e69a3ed55090fc90215227fc5fb1cb0d6e962ea7b74f; // keccak256(abi.encodePacked("bridgeContract")) bytes32 internal constant MEDIATOR_CONTRACT = 0x98aa806e31e94a687a31c65769cb99670064dd7f5a87526da075c5fb4eab9880; // keccak256(abi.encodePacked("mediatorContract")) bytes32 internal constant REQUEST_GAS_LIMIT = 0x2dfd6c9f781bb6bbb5369c114e949b69ebb440ef3d4dd6b2836225eb1dc3a2be; // keccak256(abi.encodePacked("requestGasLimit")) /** * @dev Throws if caller on the other side is not an associated mediator. */ modifier onlyMediator { require(msg.sender == address(bridgeContract())); require(messageSender() == mediatorContractOnOtherSide()); _; } /** * @dev Sets the AMB bridge contract address. Only the owner can call this method. * @param _bridgeContract the address of the bridge contract. */ function setBridgeContract(address _bridgeContract) external onlyOwner { _setBridgeContract(_bridgeContract); } /** * @dev Sets the mediator contract address from the other network. Only the owner can call this method. * @param _mediatorContract the address of the mediator contract. */ function setMediatorContractOnOtherSide(address _mediatorContract) external onlyOwner { _setMediatorContractOnOtherSide(_mediatorContract); } /** * @dev Sets the gas limit to be used in the message execution by the AMB bridge on the other network. * This value can't exceed the parameter maxGasPerTx defined on the AMB bridge. * Only the owner can call this method. * @param _requestGasLimit the gas limit for the message execution. */ function setRequestGasLimit(uint256 _requestGasLimit) external onlyOwner { _setRequestGasLimit(_requestGasLimit); } /** * @dev Get the AMB interface for the bridge contract address * @return AMB interface for the bridge contract address */ function bridgeContract() public view returns (IAMB) { return IAMB(addressStorage[BRIDGE_CONTRACT]); } /** * @dev Tells the mediator contract address from the other network. * @return the address of the mediator contract. */ function mediatorContractOnOtherSide() public view returns (address) { return addressStorage[MEDIATOR_CONTRACT]; } /** * @dev Tells the gas limit to be used in the message execution by the AMB bridge on the other network. * @return the gas limit for the message execution. */ function requestGasLimit() public view returns (uint256) { return uintStorage[REQUEST_GAS_LIMIT]; } /** * @dev Stores a valid AMB bridge contract address. * @param _bridgeContract the address of the bridge contract. */ function _setBridgeContract(address _bridgeContract) internal { require(AddressUtils.isContract(_bridgeContract)); addressStorage[BRIDGE_CONTRACT] = _bridgeContract; } /** * @dev Stores the mediator contract address from the other network. * @param _mediatorContract the address of the mediator contract. */ function _setMediatorContractOnOtherSide(address _mediatorContract) internal { addressStorage[MEDIATOR_CONTRACT] = _mediatorContract; } /** * @dev Stores the gas limit to be used in the message execution by the AMB bridge on the other network. * @param _requestGasLimit the gas limit for the message execution. */ function _setRequestGasLimit(uint256 _requestGasLimit) internal { require(_requestGasLimit <= maxGasPerTx()); uintStorage[REQUEST_GAS_LIMIT] = _requestGasLimit; } /** * @dev Tells the address that generated the message on the other network that is currently being executed by * the AMB bridge. * @return the address of the message sender. */ function messageSender() internal view returns (address) { return bridgeContract().messageSender(); } /** * @dev Tells the id of the message originated on the other network. * @return the id of the message originated on the other network. */ function messageId() internal view returns (bytes32) { return bridgeContract().messageId(); } /** * @dev Tells the maximum gas limit that a message can use on its execution by the AMB bridge on the other network. * @return the maximum gas limit value. */ function maxGasPerTx() internal view returns (uint256) { return bridgeContract().maxGasPerTx(); } } // File: contracts/upgradeable_contracts/ChooseReceiverHelper.sol pragma solidity 0.4.24; contract ChooseReceiverHelper { /** * @dev Helper function for alternative receiver feature. Chooses the actual receiver out of sender and passed data. * @param _from address of tokens sender. * @param _data passed data in the transfer message. * @return address of the receiver on the other side. */ function chooseReceiver(address _from, bytes _data) internal view returns (address recipient) { recipient = _from; if (_data.length > 0) { require(_data.length == 20); recipient = Bytes.bytesToAddress(_data); require(recipient != address(0)); require(recipient != bridgeContractOnOtherSide()); } } /* solcov ignore next */ function bridgeContractOnOtherSide() internal view returns (address); } // File: contracts/upgradeable_contracts/TransferInfoStorage.sol pragma solidity 0.4.24; contract TransferInfoStorage is EternalStorage { /** * @dev Stores the value of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _value amount of tokens bridged. */ function setMessageValue(bytes32 _messageId, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))] = _value; } /** * @dev Tells the amount of tokens of a message sent to the AMB bridge. * @return value representing amount of tokens. */ function messageValue(bytes32 _messageId) internal view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))]; } /** * @dev Stores the receiver of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _recipient receiver of the tokens bridged. */ function setMessageRecipient(bytes32 _messageId, address _recipient) internal { addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))] = _recipient; } /** * @dev Tells the receiver of a message sent to the AMB bridge. * @return address of the receiver. */ function messageRecipient(bytes32 _messageId) internal view returns (address) { return addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))]; } /** * @dev Sets that the message sent to the AMB bridge has been fixed. * @param _messageId of the message sent to the bridge. */ function setMessageFixed(bytes32 _messageId) internal { boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))] = true; } /** * @dev Tells if a message sent to the AMB bridge has been fixed. * @return bool indicating the status of the message. */ function messageFixed(bytes32 _messageId) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))]; } } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/MultiTokenBridgeMediator.sol pragma solidity 0.4.24; /** * @title MultiTokenBridgeMediator * @dev Common mediator functionality to handle operations related to multi-token bridge messages sent to AMB bridge. */ contract MultiTokenBridgeMediator is BasicAMBMediator, BasicMultiTokenBridge, TransferInfoStorage, ChooseReceiverHelper { event FailedMessageFixed(bytes32 indexed messageId, address token, address recipient, uint256 value); event TokensBridgingInitiated( address indexed token, address indexed sender, uint256 value, bytes32 indexed messageId ); event TokensBridged(address indexed token, address indexed recipient, uint256 value, bytes32 indexed messageId); /** * @dev Stores the bridged token of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _token bridged token address. */ function setMessageToken(bytes32 _messageId, address _token) internal { addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))] = _token; } /** * @dev Tells the bridged token address of a message sent to the AMB bridge. * @return address of a token contract. */ function messageToken(bytes32 _messageId) internal view returns (address) { return addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))]; } /** * @dev Handles the bridged tokens. Checks that the value is inside the execution limits and invokes the method * to execute the Mint or Unlock accordingly. * @param _token bridged ERC20/ERC677 token * @param _recipient address that will receive the tokens * @param _value amount of tokens to be received */ function _handleBridgedTokens(ERC677 _token, address _recipient, uint256 _value) internal { if (withinExecutionLimit(_token, _value)) { addTotalExecutedPerDay(_token, getCurrentDay(), _value); executeActionOnBridgedTokens(_token, _recipient, _value); } else { executeActionOnBridgedTokensOutOfLimit(_token, _recipient, _value); } } /** * @dev Method to be called when a bridged message execution failed. It will generate a new message requesting to * fix/roll back the transferred assets on the other network. * @param _messageId id of the message which execution failed. */ function requestFailedMessageFix(bytes32 _messageId) external { require(!bridgeContract().messageCallStatus(_messageId)); require(bridgeContract().failedMessageReceiver(_messageId) == address(this)); require(bridgeContract().failedMessageSender(_messageId) == mediatorContractOnOtherSide()); bytes4 methodSelector = this.fixFailedMessage.selector; bytes memory data = abi.encodeWithSelector(methodSelector, _messageId); bridgeContract().requireToPassMessage(mediatorContractOnOtherSide(), data, requestGasLimit()); } /** * @dev Handles the request to fix transferred assets which bridged message execution failed on the other network. * It uses the information stored by passMessage method when the assets were initially transferred * @param _messageId id of the message which execution failed on the other network. */ function fixFailedMessage(bytes32 _messageId) public onlyMediator { require(!messageFixed(_messageId)); address token = messageToken(_messageId); address recipient = messageRecipient(_messageId); uint256 value = messageValue(_messageId); setMessageFixed(_messageId); executeActionOnFixedTokens(token, recipient, value); emit FailedMessageFixed(_messageId, token, recipient, value); } /** * @dev Execute the action to be performed when the bridge tokens are out of execution limits. */ function executeActionOnBridgedTokensOutOfLimit(address, address, uint256) internal { revert(); } /* solcov ignore next */ function executeActionOnBridgedTokens(address _token, address _recipient, uint256 _value) internal; /* solcov ignore next */ function executeActionOnFixedTokens(address _token, address _recipient, uint256 _value) internal; } // File: contracts/upgradeable_contracts/Initializable.sol pragma solidity 0.4.24; contract Initializable is EternalStorage { bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized")) function setInitialize() internal { boolStorage[INITIALIZED] = true; } function isInitialized() public view returns (bool) { return boolStorage[INITIALIZED]; } } // File: contracts/upgradeable_contracts/ReentrancyGuard.sol pragma solidity 0.4.24; contract ReentrancyGuard { function lock() internal returns (bool res) { assembly { // Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))], // since solidity mapping introduces another level of addressing, such slot change is safe // for temporary variables which are cleared at the end of the call execution. res := sload(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92) // keccak256(abi.encodePacked("lock")) } } function setLock(bool _lock) internal { assembly { // Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))], // since solidity mapping introduces another level of addressing, such slot change is safe // for temporary variables which are cleared at the end of the call execution. sstore(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92, _lock) // keccak256(abi.encodePacked("lock")) } } } // File: contracts/upgradeable_contracts/Upgradeable.sol pragma solidity 0.4.24; contract Upgradeable { // Avoid using onlyUpgradeabilityOwner name to prevent issues with implementation from proxy contract modifier onlyIfUpgradeabilityOwner() { require(msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner()); /* solcov ignore next */ _; } } // File: contracts/upgradeable_contracts/Sacrifice.sol pragma solidity 0.4.24; contract Sacrifice { constructor(address _recipient) public payable { selfdestruct(_recipient); } } // File: contracts/libraries/Address.sol pragma solidity 0.4.24; /** * @title Address * @dev Helper methods for Address type. */ library Address { /** * @dev Try to send native tokens to the address. If it fails, it will force the transfer by creating a selfdestruct contract * @param _receiver address that will receive the native tokens * @param _value the amount of native tokens to send */ function safeSendValue(address _receiver, uint256 _value) internal { if (!_receiver.send(_value)) { (new Sacrifice).value(_value)(_receiver); } } } // File: contracts/libraries/SafeERC20.sol pragma solidity 0.4.24; /** * @title SafeERC20 * @dev Helper methods for safe token transfers. * Functions perform additional checks to be sure that token transfer really happened. */ library SafeERC20 { using SafeMath for uint256; /** * @dev Same as ERC20.transfer(address,uint256) but with extra consistency checks. * @param _token address of the token contract * @param _to address of the receiver * @param _value amount of tokens to send */ function safeTransfer(address _token, address _to, uint256 _value) internal { LegacyERC20(_token).transfer(_to, _value); assembly { if returndatasize { returndatacopy(0, 0, 32) if iszero(mload(0)) { revert(0, 0) } } } } /** * @dev Same as ERC20.transferFrom(address,address,uint256) but with extra consistency checks. * @param _token address of the token contract * @param _from address of the sender * @param _value amount of tokens to send */ function safeTransferFrom(address _token, address _from, uint256 _value) internal { LegacyERC20(_token).transferFrom(_from, address(this), _value); assembly { if returndatasize { returndatacopy(0, 0, 32) if iszero(mload(0)) { revert(0, 0) } } } } } // File: contracts/upgradeable_contracts/Claimable.sol pragma solidity 0.4.24; /** * @title Claimable * @dev Implementation of the claiming utils that can be useful for withdrawing accidentally sent tokens that are not used in bridge operations. */ contract Claimable { using SafeERC20 for address; /** * Throws if a given address is equal to address(0) */ modifier validAddress(address _to) { require(_to != address(0)); /* solcov ignore next */ _; } /** * @dev Withdraws the erc20 tokens or native coins from this contract. * Caller should additionally check that the claimed token is not a part of bridge operations (i.e. that token != erc20token()). * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimValues(address _token, address _to) internal validAddress(_to) { if (_token == address(0)) { claimNativeCoins(_to); } else { claimErc20Tokens(_token, _to); } } /** * @dev Internal function for withdrawing all native coins from the contract. * @param _to address of the coins receiver. */ function claimNativeCoins(address _to) internal { uint256 value = address(this).balance; Address.safeSendValue(_to, value); } /** * @dev Internal function for withdrawing all tokens of ssome particular ERC20 contract from this contract. * @param _token address of the claimed ERC20 token. * @param _to address of the tokens receiver. */ function claimErc20Tokens(address _token, address _to) internal { ERC20Basic token = ERC20Basic(_token); uint256 balance = token.balanceOf(this); _token.safeTransfer(_to, balance); } } // File: contracts/upgradeable_contracts/VersionableBridge.sol pragma solidity 0.4.24; contract VersionableBridge { function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) { return (5, 2, 0); } /* solcov ignore next */ function getBridgeMode() external pure returns (bytes4); } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/BasicMultiAMBErc20ToErc677.sol pragma solidity 0.4.24; /** * @title BasicMultiAMBErc20ToErc677 * @dev Common functionality for multi-erc20-to-erc677 mediator intended to work on top of AMB bridge. */ contract BasicMultiAMBErc20ToErc677 is Initializable, ReentrancyGuard, Upgradeable, Claimable, VersionableBridge, MultiTokenBridgeMediator { /** * @dev Tells the address of the mediator contract on the other side, used by chooseReceiver method * to avoid sending the native tokens to that address. * @return address of the mediator contract con the other side */ function bridgeContractOnOtherSide() internal view returns (address) { return mediatorContractOnOtherSide(); } /** * @dev Initiate the bridge operation for some amount of tokens from msg.sender. * The user should first call Approve method of the ERC677 token. * @param token bridged token contract address. * @param _receiver address that will receive the native tokens on the other network. * @param _value amount of tokens to be transferred to the other network. */ function relayTokens(ERC677 token, address _receiver, uint256 _value) external { _relayTokens(token, _receiver, _value); } /** * @dev Initiate the bridge operation for some amount of tokens from msg.sender to msg.sender on the other side. * The user should first call Approve method of the ERC677 token. * @param token bridged token contract address. * @param _value amount of tokens to be transferred to the other network. */ function relayTokens(ERC677 token, uint256 _value) external { _relayTokens(token, msg.sender, _value); } /** * @dev Tells the bridge interface version that this contract supports. * @return major value of the version * @return minor value of the version * @return patch value of the version */ function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) { return (1, 5, 0); } /** * @dev Tells the bridge mode that this contract supports. * @return _data 4 bytes representing the bridge mode */ function getBridgeMode() external pure returns (bytes4 _data) { return 0xb1516c26; // bytes4(keccak256(abi.encodePacked("multi-erc-to-erc-amb"))) } /** * @dev Claims stucked tokens. Only unsupported tokens can be claimed. * When dealing with already supported tokens, fixMediatorBalance can be used instead. * @param _token address of claimed token, address(0) for native * @param _to address of tokens receiver */ function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner { // Only unregistered tokens and native coins are allowed to be claimed with the use of this function require(_token == address(0) || !isTokenRegistered(_token)); claimValues(_token, _to); } /* solcov ignore next */ function onTokenTransfer(address _from, uint256 _value, bytes _data) public returns (bool); /* solcov ignore next */ function _relayTokens(ERC677 token, address _receiver, uint256 _value) internal; /* solcov ignore next */ function bridgeSpecificActionsOnTokenTransfer(ERC677 _token, address _from, address _receiver, uint256 _value) internal; } // File: contracts/upgradeability/Proxy.sol pragma solidity 0.4.24; /** * @title Proxy * @dev Gives the possibility to delegate any call to a foreign implementation. */ contract Proxy { /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ /* solcov ignore next */ function implementation() public view returns (address); /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ function() public payable { // solhint-disable-previous-line no-complex-fallback address _impl = implementation(); require(_impl != address(0)); assembly { /* 0x40 is the "free memory slot", meaning a pointer to next slot of empty memory. mload(0x40) loads the data in the free memory slot, so `ptr` is a pointer to the next slot of empty memory. It's needed because we're going to write the return data of delegatecall to the free memory slot. */ let ptr := mload(0x40) /* `calldatacopy` is copy calldatasize bytes from calldata First argument is the destination to which data is copied(ptr) Second argument specifies the start position of the copied data. Since calldata is sort of its own unique location in memory, 0 doesn't refer to 0 in memory or 0 in storage - it just refers to the zeroth byte of calldata. That's always going to be the zeroth byte of the function selector. Third argument, calldatasize, specifies how much data will be copied. calldata is naturally calldatasize bytes long (same thing as msg.data.length) */ calldatacopy(ptr, 0, calldatasize) /* delegatecall params explained: gas: the amount of gas to provide for the call. `gas` is an Opcode that gives us the amount of gas still available to execution _impl: address of the contract to delegate to ptr: to pass copied data calldatasize: loads the size of `bytes memory data`, same as msg.data.length 0, 0: These are for the `out` and `outsize` params. Because the output could be dynamic, these are set to 0, 0 so the output data will not be written to memory. The output data will be read using `returndatasize` and `returdatacopy` instead. result: This will be 0 if the call fails and 1 if it succeeds */ let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) /* */ /* ptr current points to the value stored at 0x40, because we assigned it like ptr := mload(0x40). Because we use 0x40 as a free memory pointer, we want to make sure that the next time we want to allocate memory, we aren't overwriting anything important. So, by adding ptr and returndatasize, we get a memory location beyond the end of the data we will be copying to ptr. We place this in at 0x40, and any reads from 0x40 will now read from free memory */ mstore(0x40, add(ptr, returndatasize)) /* `returndatacopy` is an Opcode that copies the last return data to a slot. `ptr` is the slot it will copy to, 0 means copy from the beginning of the return data, and size is the amount of data to copy. `returndatasize` is an Opcode that gives us the size of the last return data. In this case, that is the size of the data returned from delegatecall */ returndatacopy(ptr, 0, returndatasize) /* if `result` is 0, revert. if `result` is 1, return `size` amount of data from `ptr`. This is the data that was copied to `ptr` from the delegatecall return data */ switch result case 0 { revert(ptr, returndatasize) } default { return(ptr, returndatasize) } } } } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/TokenProxy.sol pragma solidity 0.4.24; interface IPermittableTokenVersion { function version() external pure returns (string); } /** * @title TokenProxy * @dev Helps to reduces the size of the deployed bytecode for automatically created tokens, by using a proxy contract. */ contract TokenProxy is Proxy { // storage layout is copied from PermittableToken.sol string internal name; string internal symbol; uint8 internal decimals; mapping(address => uint256) internal balances; uint256 internal totalSupply; mapping(address => mapping(address => uint256)) internal allowed; address internal owner; bool internal mintingFinished; address internal bridgeContractAddr; // string public constant version = "1"; bytes32 internal DOMAIN_SEPARATOR; // bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; mapping(address => uint256) internal nonces; mapping(address => mapping(address => uint256)) internal expirations; /** * @dev Creates a non-upgradeable token proxy for PermitableToken.sol, initializes its eternalStorage. * @param _tokenImage address of the token image used for mirroring all functions. * @param _name token name. * @param _symbol token symbol. * @param _decimals token decimals. * @param _chainId chain id for current network. */ constructor(address _tokenImage, string memory _name, string memory _symbol, uint8 _decimals, uint256 _chainId) public { string memory version = IPermittableTokenVersion(_tokenImage).version(); assembly { // EIP 1967 // bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1) sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _tokenImage) } name = _name; symbol = _symbol; decimals = _decimals; owner = msg.sender; // msg.sender == HomeMultiAMBErc20ToErc677 mediator bridgeContractAddr = msg.sender; DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(_name)), keccak256(bytes(version)), _chainId, address(this) ) ); } /** * @dev Retrieves the implementation contract address, mirrored token image. * @return token image address. */ function implementation() public view returns (address impl) { assembly { impl := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc) } } } // File: contracts/upgradeable_contracts/BaseRewardAddressList.sol pragma solidity 0.4.24; /** * @title BaseRewardAddressList * @dev Implements the logic to store, add and remove reward account addresses. Works as a linked list. */ contract BaseRewardAddressList is EternalStorage { using SafeMath for uint256; address public constant F_ADDR = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF; uint256 internal constant MAX_REWARD_ADDRESSES = 50; bytes32 internal constant REWARD_ADDRESS_COUNT = 0xabc77c82721ced73eef2645facebe8c30249e6ac372cce6eb9d1fed31bd6648f; // keccak256(abi.encodePacked("rewardAddressCount")) event RewardAddressAdded(address indexed addr); event RewardAddressRemoved(address indexed addr); /** * @dev Retrieves all registered reward accounts. * @return address list of the registered reward receivers. */ function rewardAddressList() external view returns (address[]) { address[] memory list = new address[](rewardAddressCount()); uint256 counter = 0; address nextAddr = getNextRewardAddress(F_ADDR); while (nextAddr != F_ADDR) { require(nextAddr != address(0)); list[counter] = nextAddr; nextAddr = getNextRewardAddress(nextAddr); counter++; } return list; } /** * @dev Retrieves amount of registered reward accounts. * @return length of reward addresses list. */ function rewardAddressCount() public view returns (uint256) { return uintStorage[REWARD_ADDRESS_COUNT]; } /** * @dev Checks if specified address is included into the registered rewards receivers list. * @param _addr address to verify. * @return true, if specified address is associated with one of the registered reward accounts. */ function isRewardAddress(address _addr) public view returns (bool) { return _addr != F_ADDR && getNextRewardAddress(_addr) != address(0); } /** * @dev Retrieves next reward address in the linked list, or F_ADDR if given address is the last one. * @param _address address of some reward account. * @return address of the next reward receiver. */ function getNextRewardAddress(address _address) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("rewardAddressList", _address))]; } /** * @dev Internal function for adding a new reward address to the linked list. * @param _addr new reward account. */ function _addRewardAddress(address _addr) internal { require(_addr != address(0) && _addr != F_ADDR); require(!isRewardAddress(_addr)); address nextAddr = getNextRewardAddress(F_ADDR); require(nextAddr != address(0)); _setNextRewardAddress(_addr, nextAddr); _setNextRewardAddress(F_ADDR, _addr); _setRewardAddressCount(rewardAddressCount().add(1)); } /** * @dev Internal function for removing existing reward address from the linked list. * @param _addr old reward account which should be removed. */ function _removeRewardAddress(address _addr) internal { require(isRewardAddress(_addr)); address nextAddr = getNextRewardAddress(_addr); address index = F_ADDR; address next = getNextRewardAddress(index); while (next != _addr) { require(next != address(0)); index = next; next = getNextRewardAddress(index); require(next != F_ADDR); } _setNextRewardAddress(index, nextAddr); delete addressStorage[keccak256(abi.encodePacked("rewardAddressList", _addr))]; _setRewardAddressCount(rewardAddressCount().sub(1)); } /** * @dev Internal function for initializing linked list with the array of the initial reward addresses. * @param _rewardAddresses initial reward addresses list, should be non-empty. */ function _setRewardAddressList(address[] _rewardAddresses) internal { require(_rewardAddresses.length > 0); _setNextRewardAddress(F_ADDR, _rewardAddresses[0]); for (uint256 i = 0; i < _rewardAddresses.length; i++) { require(_rewardAddresses[i] != address(0) && _rewardAddresses[i] != F_ADDR); require(!isRewardAddress(_rewardAddresses[i])); if (i == _rewardAddresses.length - 1) { _setNextRewardAddress(_rewardAddresses[i], F_ADDR); } else { _setNextRewardAddress(_rewardAddresses[i], _rewardAddresses[i + 1]); } emit RewardAddressAdded(_rewardAddresses[i]); } _setRewardAddressCount(_rewardAddresses.length); } /** * @dev Internal function for updating the length of the reward accounts list. * @param _rewardAddressCount new linked list length. */ function _setRewardAddressCount(uint256 _rewardAddressCount) internal { require(_rewardAddressCount <= MAX_REWARD_ADDRESSES); uintStorage[REWARD_ADDRESS_COUNT] = _rewardAddressCount; } /** * @dev Internal function for updating the pointer to the next reward receiver. * @param _prevAddr address of some reward receiver. * @param _addr address of the next receiver to which _prevAddr should point to. */ function _setNextRewardAddress(address _prevAddr, address _addr) internal { addressStorage[keccak256(abi.encodePacked("rewardAddressList", _prevAddr))] = _addr; } } // File: contracts/interfaces/IBurnableMintableERC677Token.sol pragma solidity 0.4.24; contract IBurnableMintableERC677Token is ERC677 { function mint(address _to, uint256 _amount) public returns (bool); function burn(uint256 _value) public; function claimTokens(address _token, address _to) external; } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/HomeFeeManagerMultiAMBErc20ToErc677.sol pragma solidity 0.4.24; /** * @title HomeFeeManagerMultiAMBErc20ToErc677 * @dev Implements the logic to distribute fees from the multi erc20 to erc677 mediator contract operations. * The fees are distributed in the form of native tokens to the list of reward accounts. */ contract HomeFeeManagerMultiAMBErc20ToErc677 is BaseRewardAddressList, Ownable, BasicMultiTokenBridge { using SafeMath for uint256; event FeeUpdated(bytes32 feeType, address indexed token, uint256 fee); event FeeDistributed(uint256 fee, address indexed token, bytes32 indexed messageId); // This is not a real fee value but a relative value used to calculate the fee percentage uint256 internal constant MAX_FEE = 1 ether; bytes32 public constant HOME_TO_FOREIGN_FEE = 0x741ede137d0537e88e0ea0ff25b1f22d837903dbbee8980b4a06e8523247ee26; // keccak256(abi.encodePacked("homeToForeignFee")) bytes32 public constant FOREIGN_TO_HOME_FEE = 0x03be2b2875cb41e0e77355e802a16769bb8dfcf825061cde185c73bf94f12625; // keccak256(abi.encodePacked("foreignToHomeFee")) /** * @dev Throws if given fee percentage is >= 100%. */ modifier validFee(uint256 _fee) { require(_fee < MAX_FEE); /* solcov ignore next */ _; } /** * @dev Throws if given fee type is unknown. */ modifier validFeeType(bytes32 _feeType) { require(_feeType == HOME_TO_FOREIGN_FEE || _feeType == FOREIGN_TO_HOME_FEE); /* solcov ignore next */ _; } /** * @dev Adds a new reward address to the list, which will receive fees collected from the bridge operations. * Only the owner can call this method. * @param _addr new reward account. */ function addRewardAddress(address _addr) external onlyOwner { _addRewardAddress(_addr); } /** * @dev Removes a reward address from the rewards list. * Only the owner can call this method. * @param _addr old reward account, that should be removed. */ function removeRewardAddress(address _addr) external onlyOwner { _removeRewardAddress(_addr); } /** * @dev Updates the value for the particular fee type. * Only the owner can call this method. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _fee new fee value, in percentage (1 ether == 10**18 == 100%). */ function setFee(bytes32 _feeType, address _token, uint256 _fee) external onlyOwner { require(isTokenRegistered(_token)); _setFee(_feeType, _token, _fee); } /** * @dev Retrieves the value for the particular fee type. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @return fee value associated with the requested fee type. */ function getFee(bytes32 _feeType, address _token) public view validFeeType(_feeType) returns (uint256) { return uintStorage[keccak256(abi.encodePacked(_feeType, _token))]; } /** * @dev Calculates the amount of fee to pay for the value of the particular fee type. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _value bridged value, for which fee should be evaluated. * @return amount of fee to be subtracted from the transferred value. */ function calculateFee(bytes32 _feeType, address _token, uint256 _value) public view returns (uint256) { uint256 _fee = getFee(_feeType, _token); return _value.mul(_fee).div(MAX_FEE); } /** * @dev Internal function for updating the fee value for the given fee type. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _fee new fee value, in percentage (1 ether == 10**18 == 100%). */ function _setFee(bytes32 _feeType, address _token, uint256 _fee) internal validFeeType(_feeType) validFee(_fee) { uintStorage[keccak256(abi.encodePacked(_feeType, _token))] = _fee; emit FeeUpdated(_feeType, _token, _fee); } /** * @dev Calculates a random number based on the block number. * @param _count the max value for the random number. * @return a number between 0 and _count. */ function random(uint256 _count) internal view returns (uint256) { return uint256(blockhash(block.number.sub(1))) % _count; } /** * @dev Calculates and distributes the amount of fee proportionally between registered reward addresses. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _value bridged value, for which fee should be evaluated. * @return total amount of fee subtracted from the transferred value and distributed between the reward accounts. */ function _distributeFee(bytes32 _feeType, address _token, uint256 _value) internal returns (uint256) { uint256 numOfAccounts = rewardAddressCount(); uint256 _fee = calculateFee(_feeType, _token, _value); if (numOfAccounts == 0 || _fee == 0) { return 0; } uint256 feePerAccount = _fee.div(numOfAccounts); uint256 randomAccountIndex; uint256 diff = _fee.sub(feePerAccount.mul(numOfAccounts)); if (diff > 0) { randomAccountIndex = random(numOfAccounts); } address nextAddr = getNextRewardAddress(F_ADDR); require(nextAddr != F_ADDR && nextAddr != address(0)); uint256 i = 0; while (nextAddr != F_ADDR) { uint256 feeToDistribute = feePerAccount; if (diff > 0 && randomAccountIndex == i) { feeToDistribute = feeToDistribute.add(diff); } if (_feeType == HOME_TO_FOREIGN_FEE) { ERC677(_token).transfer(nextAddr, feeToDistribute); } else { _getMinterFor(_token).mint(nextAddr, feeToDistribute); } nextAddr = getNextRewardAddress(nextAddr); require(nextAddr != address(0)); i = i + 1; } return _fee; } function _getMinterFor(address _token) internal view returns (IBurnableMintableERC677Token); } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/MultiTokenForwardingRules.sol pragma solidity 0.4.24; /** * @title MultiTokenForwardingRules * @dev Multi token mediator functionality for managing destination AMB lanes permissions. */ contract MultiTokenForwardingRules is Ownable { address internal constant ANY_ADDRESS = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF; event ForwardingRuleUpdated(address token, address sender, address receiver, int256 lane); /** * @dev Tells the destination lane for a particular bridge operation by checking several wildcard forwarding rules. * @param _token address of the token contract on the foreign side of the bridge. * @param _sender address of the tokens sender on the home side of the bridge. * @param _receiver address of the tokens receiver on the foreign side of the bridge. * @return destination lane identifier, where the message should be forwarded to. * 1 - oracle-driven-lane should be used. * 0 - default behaviour should be applied. * -1 - manual lane should be used. */ function destinationLane(address _token, address _sender, address _receiver) public view returns (int256) { int256 defaultLane = forwardingRule(_token, ANY_ADDRESS, ANY_ADDRESS); // specific token for all senders and receivers int256 lane; if (defaultLane < 0) { lane = forwardingRule(_token, _sender, ANY_ADDRESS); // specific token for specific sender if (lane != 0) return lane; lane = forwardingRule(_token, ANY_ADDRESS, _receiver); // specific token for specific receiver if (lane != 0) return lane; return defaultLane; } lane = forwardingRule(ANY_ADDRESS, _sender, ANY_ADDRESS); // all tokens for specific sender if (lane != 0) return lane; return forwardingRule(ANY_ADDRESS, ANY_ADDRESS, _receiver); // all tokens for specific receiver } /** * Updates the forwarding rule for bridging specific token. * Only owner can call this method. * @param _token address of the token contract on the foreign side. * @param _enable true, if bridge operations for a given token should be forwarded to the manual lane. */ function setTokenForwardingRule(address _token, bool _enable) external { require(_token != ANY_ADDRESS); _setForwardingRule(_token, ANY_ADDRESS, ANY_ADDRESS, _enable ? int256(-1) : int256(0)); } /** * Allows a particular address to send bridge requests to the oracle-driven lane for a particular token. * Only owner can call this method. * @param _token address of the token contract on the foreign side. * @param _sender address of the tokens sender on the home side of the bridge. * @param _enable true, if bridge operations for a given token and sender should be forwarded to the oracle-driven lane. */ function setSenderExceptionForTokenForwardingRule(address _token, address _sender, bool _enable) external { require(_token != ANY_ADDRESS); require(_sender != ANY_ADDRESS); _setForwardingRule(_token, _sender, ANY_ADDRESS, _enable ? int256(1) : int256(0)); } /** * Allows a particular address to receive bridged tokens from the oracle-driven lane for a particular token. * Only owner can call this method. * @param _token address of the token contract on the foreign side. * @param _receiver address of the tokens receiver on the foreign side of the bridge. * @param _enable true, if bridge operations for a given token and receiver should be forwarded to the oracle-driven lane. */ function setReceiverExceptionForTokenForwardingRule(address _token, address _receiver, bool _enable) external { require(_token != ANY_ADDRESS); require(_receiver != ANY_ADDRESS); _setForwardingRule(_token, ANY_ADDRESS, _receiver, _enable ? int256(1) : int256(0)); } /** * Updates the forwarding rule for the specific sender. * Only owner can call this method. * @param _sender address of the tokens sender on the home side. * @param _enable true, if all bridge operations from a given sender should be forwarded to the manual lane. */ function setSenderForwardingRule(address _sender, bool _enable) external { require(_sender != ANY_ADDRESS); _setForwardingRule(ANY_ADDRESS, _sender, ANY_ADDRESS, _enable ? int256(-1) : int256(0)); } /** * Updates the forwarding rule for the specific receiver. * Only owner can call this method. * @param _receiver address of the tokens receiver on the foreign side. * @param _enable true, if all bridge operations to a given receiver should be forwarded to the manual lane. */ function setReceiverForwardingRule(address _receiver, bool _enable) external { require(_receiver != ANY_ADDRESS); _setForwardingRule(ANY_ADDRESS, ANY_ADDRESS, _receiver, _enable ? int256(-1) : int256(0)); } /** * @dev Tells forwarding rule set up for a particular bridge operation. * @param _token address of the token contract on the foreign side of the bridge. * @param _sender address of the tokens sender on the home side of the bridge. * @param _receiver address of the tokens receiver on the foreign side of the bridge. * @return preferred destination lane for the particular bridge operation. */ function forwardingRule(address _token, address _sender, address _receiver) public view returns (int256) { return intStorage[keccak256(abi.encodePacked("forwardTo", _token, _sender, _receiver))]; } /** * @dev Internal function for updating the preferred destination lane for the specific wildcard pattern. * Only owner can call this method. * Examples: * _setForwardingRule(tokenA, ANY_ADDRESS, ANY_ADDRESS, -1) - forward all operations on tokenA to the manual lane * _setForwardingRule(tokenA, Alice, ANY_ADDRESS, 1) - allow Alice to use the oracle-driven lane for bridging tokenA * _setForwardingRule(tokenA, ANY_ADDRESS, Bob, 1) - forward all tokenA bridge operations, where Bob is the receiver, to the oracle-driven lane * _setForwardingRule(ANY_ADDRESS, Mallory, ANY_ADDRESS, -1) - forward all bridge operations from Mallory to the manual lane * @param _token address of the token contract on the foreign side of the bridge. * @param _sender address of the tokens sender on the home side of the bridge. * @param _receiver address of the tokens receiver on the foreign side of the bridge. * @param _lane preferred destination lane for the particular sender. * 1 - forward to the oracle-driven lane. * 0 - behaviour is unset, proceed by checking other less-specific rules. * -1 - manual lane should be used. */ function _setForwardingRule(address _token, address _sender, address _receiver, int256 _lane) internal onlyOwner { intStorage[keccak256(abi.encodePacked("forwardTo", _token, _sender, _receiver))] = _lane; emit ForwardingRuleUpdated(_token, _sender, _receiver, _lane); } } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/HomeMultiAMBErc20ToErc677.sol pragma solidity 0.4.24; /** * @title HomeMultiAMBErc20ToErc677 * @dev Home side implementation for multi-erc20-to-erc677 mediator intended to work on top of AMB bridge. * It is designed to be used as an implementation contract of EternalStorageProxy contract. */ contract HomeMultiAMBErc20ToErc677 is BasicMultiAMBErc20ToErc677, HomeFeeManagerMultiAMBErc20ToErc677, MultiTokenForwardingRules { bytes32 internal constant TOKEN_IMAGE_CONTRACT = 0x20b8ca26cc94f39fab299954184cf3a9bd04f69543e4f454fab299f015b8130f; // keccak256(abi.encodePacked("tokenImageContract")) event NewTokenRegistered(address indexed foreignToken, address indexed homeToken); /** * @dev Throws if called by any account other than the owner. * Overrides modifier from the Ownable contract in order to reduce bytecode size. */ modifier onlyOwner() { _onlyOwner(); /* solcov ignore next */ _; } /** * @dev Internal function for reducing onlyOwner modifier bytecode size overhead. */ function _onlyOwner() internal { require(msg.sender == owner()); } /** * @dev Throws if caller on the other side is not an associated mediator. */ modifier onlyMediator() { _onlyMediator(); /* solcov ignore next */ _; } /** * @dev Internal function for reducing onlyMediator modifier bytecode size overhead. */ function _onlyMediator() internal { require(msg.sender == address(bridgeContract())); require(messageSender() == mediatorContractOnOtherSide()); } /** * @dev Stores the initial parameters of the mediator. * @param _bridgeContract the address of the AMB bridge contract. * @param _mediatorContract the address of the mediator contract on the other network. * @param _dailyLimitMaxPerTxMinPerTxArray array with limit values for the assets to be bridged to the other network. * [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ] * @param _executionDailyLimitExecutionMaxPerTxArray array with limit values for the assets bridged from the other network. * [ 0 = executionDailyLimit, 1 = executionMaxPerTx ] * @param _requestGasLimit the gas limit for the message execution. * @param _owner address of the owner of the mediator contract. * @param _tokenImage address of the PermittableToken contract that will be used for deploying of new tokens. * @param _rewardAddresses list of reward addresses, between whom fees will be distributed. * @param _fees array with initial fees for both bridge directions. * [ 0 = homeToForeignFee, 1 = foreignToHomeFee ] */ function initialize( address _bridgeContract, address _mediatorContract, uint256[3] _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ] uint256[2] _executionDailyLimitExecutionMaxPerTxArray, // [ 0 = _executionDailyLimit, 1 = _executionMaxPerTx ] uint256 _requestGasLimit, address _owner, address _tokenImage, address[] _rewardAddresses, uint256[2] _fees // [ 0 = homeToForeignFee, 1 = foreignToHomeFee ] ) external onlyRelevantSender returns (bool) { require(!isInitialized()); _setBridgeContract(_bridgeContract); _setMediatorContractOnOtherSide(_mediatorContract); _setLimits(address(0), _dailyLimitMaxPerTxMinPerTxArray); _setExecutionLimits(address(0), _executionDailyLimitExecutionMaxPerTxArray); _setRequestGasLimit(_requestGasLimit); _setOwner(_owner); _setTokenImage(_tokenImage); if (_rewardAddresses.length > 0) { _setRewardAddressList(_rewardAddresses); } _setFee(HOME_TO_FOREIGN_FEE, address(0), _fees[0]); _setFee(FOREIGN_TO_HOME_FEE, address(0), _fees[1]); setInitialize(); return isInitialized(); } /** * @dev Updates an address of the token image contract used for proxifying newly created tokens. * @param _tokenImage address of PermittableToken contract. */ function setTokenImage(address _tokenImage) external onlyOwner { _setTokenImage(_tokenImage); } /** * @dev Retrieves address of the token image contract. * @return address of block reward contract. */ function tokenImage() public view returns (address) { return addressStorage[TOKEN_IMAGE_CONTRACT]; } /** * @dev Handles the bridged tokens for the first time, includes deployment of new TokenProxy contract. * Checks that the value is inside the execution limits and invokes the method * to execute the Mint or Unlock accordingly. * @param _token address of the bridged ERC20/ERC677 token on the foreign side. * @param _name name of the bridged token, "x" will be appended, if empty, symbol will be used instead. * @param _symbol symbol of the bridged token, "x" will be appended, if empty, name will be used instead. * @param _decimals decimals of the bridge foreign token. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. */ function deployAndHandleBridgedTokens( address _token, string _name, string _symbol, uint8 _decimals, address _recipient, uint256 _value ) external onlyMediator { require(owner() == _recipient); string memory name = _name; string memory symbol = _symbol; require(bytes(name).length > 0 || bytes(symbol).length > 0); if (bytes(name).length == 0) { name = symbol; } else if (bytes(symbol).length == 0) { symbol = name; } name = string(abi.encodePacked(name, " on ETH")); address homeToken = new TokenProxy(tokenImage(), name, symbol, _decimals, bridgeContract().sourceChainId()); _setTokenAddressPair(_token, homeToken); _initializeTokenBridgeLimits(homeToken, _decimals); _setFee(HOME_TO_FOREIGN_FEE, homeToken, getFee(HOME_TO_FOREIGN_FEE, address(0))); _setFee(FOREIGN_TO_HOME_FEE, homeToken, getFee(FOREIGN_TO_HOME_FEE, address(0))); _handleBridgedTokens(ERC677(homeToken), _recipient, _value); emit NewTokenRegistered(_token, homeToken); } /** * @dev Handles the bridged tokens. Checks that the value is inside the execution limits and invokes the method * to execute the Mint or Unlock accordingly. * @param _token bridged ERC20 token. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. */ function handleBridgedTokens(ERC677 _token, address _recipient, uint256 _value) external onlyMediator { ERC677 homeToken = ERC677(homeTokenAddress(_token)); require(isTokenRegistered(homeToken)); _handleBridgedTokens(homeToken, _recipient, _value); } /** * @dev ERC677 transfer callback function. * @param _from address of tokens sender. * @param _value amount of transferred tokens. * @param _data additional transfer data, can be used for passing alternative receiver address. */ function onTokenTransfer(address _from, uint256 _value, bytes _data) public returns (bool) { // if onTokenTransfer is called as a part of call to _relayTokens, this callback does nothing if (!lock()) { ERC677 token = ERC677(msg.sender); // if msg.sender if not a valid token contract, this check will fail, since limits are zeros // so the following check is not needed // require(isTokenRegistered(token)); require(withinLimit(token, _value)); addTotalSpentPerDay(token, getCurrentDay(), _value); bridgeSpecificActionsOnTokenTransfer(token, _from, chooseReceiver(_from, _data), _value); } return true; } /** * @dev Validates that the token amount is inside the limits, calls transferFrom to transfer the tokens to the contract * and invokes the method to burn/lock the tokens and unlock/mint the tokens on the other network. * The user should first call Approve method of the ERC677 token. * @param token bridge token contract address. * @param _receiver address that will receive the native tokens on the other network. * @param _value amount of tokens to be transferred to the other network. */ function _relayTokens(ERC677 token, address _receiver, uint256 _value) internal { // This lock is to prevent calling passMessage twice if a ERC677 token is used. // When transferFrom is called, after the transfer, the ERC677 token will call onTokenTransfer from this contract // which will call passMessage. require(!lock()); address to = address(this); // if msg.sender if not a valid token contract, this check will fail, since limits are zeros // so the following check is not needed // require(isTokenRegistered(token)); require(withinLimit(token, _value)); addTotalSpentPerDay(token, getCurrentDay(), _value); setLock(true); token.transferFrom(msg.sender, to, _value); setLock(false); bridgeSpecificActionsOnTokenTransfer(token, msg.sender, _receiver, _value); } /** * @dev Executes action on the request to deposit tokens relayed from the other network * @param _recipient address of tokens receiver * @param _value amount of bridged tokens */ function executeActionOnBridgedTokens(address _token, address _recipient, uint256 _value) internal { bytes32 _messageId = messageId(); uint256 valueToMint = _value; uint256 fee = _distributeFee(FOREIGN_TO_HOME_FEE, _token, minPerTx(_token)); if (fee > 0) { emit FeeDistributed(fee, _token, _messageId); valueToMint = _value.sub(fee); } _getMinterFor(_token).mint(_recipient, valueToMint); emit TokensBridged(_token, _recipient, valueToMint, _messageId); } /** * @dev Mints back the amount of tokens that were bridged to the other network but failed. * @param _token address that bridged token contract. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. */ function executeActionOnFixedTokens(address _token, address _recipient, uint256 _value) internal { _getMinterFor(_token).mint(_recipient, _value); } /** * @dev Retrieves address of the home bridged token contract associated with a specific foreign token contract. * @param _foreignToken address of the created home token contract. * @return address of the home token contract. */ function homeTokenAddress(address _foreignToken) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _foreignToken))]; } /** * @dev Retrieves address of the foreign bridged token contract associated with a specific home token contract. * @param _homeToken address of the created home token contract. * @return address of the foreign token contract. */ function foreignTokenAddress(address _homeToken) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _homeToken))]; } /** * @dev Internal function for updating an address of the token image contract. * @param _foreignToken address of bridged foreign token contract. * @param _foreignToken address of created home token contract. */ function _setTokenAddressPair(address _foreignToken, address _homeToken) internal { addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _foreignToken))] = _homeToken; addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _homeToken))] = _foreignToken; } /** * @dev Internal function for updating an address of the token image contract. * @param _tokenImage address of deployed PermittableToken contract. */ function _setTokenImage(address _tokenImage) internal { require(AddressUtils.isContract(_tokenImage)); addressStorage[TOKEN_IMAGE_CONTRACT] = _tokenImage; } /** * @dev Executes action on withdrawal of bridged tokens * @param _token address of token contract * @param _from address of tokens sender * @param _receiver address of tokens receiver on the other side * @param _value requested amount of bridged tokens */ function bridgeSpecificActionsOnTokenTransfer(ERC677 _token, address _from, address _receiver, uint256 _value) internal { uint256 valueToBridge = _value; uint256 fee = 0; // Next line disables fee collection in case sender is one of the reward addresses. // It is needed to allow a 100% withdrawal of tokens from the home side. // If fees are not disabled for reward receivers, small fraction of tokens will always // be redistributed between the same set of reward addresses, which is not the desired behaviour. if (!isRewardAddress(_from)) { fee = _distributeFee(HOME_TO_FOREIGN_FEE, _token, minPerTx(_token)); valueToBridge = _value.sub(fee); } IBurnableMintableERC677Token(_token).burn(valueToBridge); bytes32 _messageId = passMessage(_token, _from, _receiver, valueToBridge); if (fee > 0) { emit FeeDistributed(fee, _token, _messageId); } } /** * @dev Call AMB bridge to require the invocation of handleBridgedTokens method of the mediator on the other network. * Store information related to the bridged tokens in case the message execution fails on the other network * and the action needs to be fixed/rolled back. * @param _token bridged ERC20 token * @param _from address of sender, if bridge operation fails, tokens will be returned to this address * @param _receiver address of receiver on the other side, will eventually receive bridged tokens * @param _value bridged amount of tokens * @return id of the created and passed message */ function passMessage(ERC677 _token, address _from, address _receiver, uint256 _value) internal returns (bytes32) { bytes4 methodSelector = this.handleBridgedTokens.selector; address foreignToken = foreignTokenAddress(_token); bytes memory data = abi.encodeWithSelector(methodSelector, foreignToken, _receiver, _value); address executor = mediatorContractOnOtherSide(); uint256 gasLimit = requestGasLimit(); IAMB bridge = bridgeContract(); // Address of the foreign token is used here for determining lane permissions. // Such decision makes it possible to set rules for tokens that are not bridged yet. bytes32 _messageId = destinationLane(foreignToken, _from, _receiver) >= 0 ? bridge.requireToPassMessage(executor, data, gasLimit) : bridge.requireToConfirmMessage(executor, data, gasLimit); setMessageToken(_messageId, _token); setMessageValue(_messageId, _value); setMessageRecipient(_messageId, _from); emit TokensBridgingInitiated(_token, _from, _value, _messageId); return _messageId; } /** * @dev Internal function for getting minter proxy address. * Returns the token address itself, expect for the case with bridged STAKE token. * For bridged STAKE token, returns the hardcoded TokenMinter contract address. * @param _token address of the token to mint. * @return address of the minter contract that should be used for calling mint(address,uint256) */ function _getMinterFor(address _token) internal view returns (IBurnableMintableERC677Token) { return IBurnableMintableERC677Token(_token); } /** * @dev Withdraws erc20 tokens or native coins from the bridged token contract. * Only the proxy owner is allowed to call this method. * @param _bridgedToken address of the bridged token contract. * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimTokensFromTokenContract(address _bridgedToken, address _token, address _to) external onlyIfUpgradeabilityOwner { IBurnableMintableERC677Token(_bridgedToken).claimTokens(_token, _to); } }
Internal function for getting minter proxy address. Returns the token address itself, expect for the case with bridged STAKE token. For bridged STAKE token, returns the hardcoded TokenMinter contract address. _token address of the token to mint. return address of the minter contract that should be used for calling mint(address,uint256)/
function _getMinterFor(address _token) internal view returns (IBurnableMintableERC677Token) { return IBurnableMintableERC677Token(_token); }
7,814,826
./full_match/5/0xa1Abe6Efa2950D09219262CE6B87f10961f7D1a3/sources/_chiru-labs/pbt/src/PBTSimple.sol
The blockNumberUsedInSig must be in a previous block because the blockhash of the current block does not exist yet.
function _getTokenDataForChipSignature(bytes calldata signatureFromChip, uint256 blockNumberUsedInSig) internal view returns (TokenData memory) { if (block.number <= blockNumberUsedInSig) { revert InvalidBlockNumber(); } unchecked { if (block.number - blockNumberUsedInSig > getMaxBlockhashValidWindow()) { revert BlockNumberTooOld(); } } bytes32 blockHash = blockhash(blockNumberUsedInSig); bytes32 signedHash = keccak256(abi.encodePacked(_msgSender(), blockHash)).toEthSignedMessageHash(); address chipAddr = signedHash.recover(signatureFromChip); TokenData memory tokenData = _tokenDatas[chipAddr]; if (tokenData.set) { return tokenData; } revert InvalidSignature(); }
1,920,571
./full_match/421613/0x4dd43b2507fDA403eAD26e4342D537Ed684ECB33/sources/project_/contracts/quests/QuestType.sol
Returns the quest details questID the quests ID
function getQuest(uint256 questID) external view returns (Quest memory questDetails) { return quests[questID]; }
11,574,374
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./BaseSystem.sol"; import "./openZeppelin/IERC20.sol"; // Use ERC20Votes for snapshot token balances contract VoteWeight is BaseSystem, IWeight { //-------------------------------------------------------------------------- // STATE //-------------------------------------------------------------------------- IERC20 private govToken_; IERC20 private repToken_; //-------------------------------------------------------------------------- // CONSTRUCTOR //-------------------------------------------------------------------------- constructor(address _core, address _timer) BaseSystem(CoreLib.VOTE_WEIGHT, _core, _timer) {} function initialise(address _govToken, address _repToken) external initializer { govToken_ = IERC20(_govToken); repToken_ = IERC20(_repToken); // FUTURE turn into registry like voting booth // use library for vote weight? Then can have multiple } //-------------------------------------------------------------------------- // VIEW & PURE FUNCTIONS //-------------------------------------------------------------------------- /** * @param _propID This lets the vote weight get the correct snapshot for * each proposal. * @param _voter Address of the voter. * @notice The vote weight of the _voter is a simple equation of their * governance and reputation token: * vote_weight = (gov_token * rep_token) / 2 */ function getVoteWeight(uint256 _propID, address _voter) external view override returns (uint256) { // TODO if first check for a prop make snapshot // NOTE does it not make more sense to do the snapshot here?? // Nope. Need to snapshot at proposal for flash loans :/ uint256 voteWeight = govToken_.balanceOf(_voter) + repToken_.balanceOf(_voter); // return(voteWeight == 0 ? 0 : voteWeight / 2); if (voteWeight == 0) { return 0; } else { return voteWeight; } } function getTotalWeight(uint256 _propID) external view override returns (uint256) { // TODO this should use the snapshot. Super insecure to do it like this uint256 total = govToken_.totalSupply() + repToken_.totalSupply(); return total; } }
TODO this should use the snapshot. Super insecure to do it like this
function getTotalWeight(uint256 _propID) external view override returns (uint256) { uint256 total = govToken_.totalSupply() + repToken_.totalSupply(); return total; }
12,658,284
./full_match/1/0xb2bf8D922dB107e73BCd0E5f8Da7068dE0CB71ca/sources/contracts/BirdX.sol
Allows the current owner to renounce ownership, transferring ownership to the zero address./
function renounceOwnership() public override onlyOwner { emit OwnershipTransferred(_msgSender(), address(0)); _transferOwnership(address(0)); }
2,922,579
// Dependency file: @chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol // SPDX-License-Identifier: MIT // pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathChainlink { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // Dependency file: @chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol // pragma solidity ^0.6.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); } // Dependency file: @chainlink/contracts/src/v0.6/VRFRequestIDBase.sol // pragma solidity ^0.6.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)); } } // Dependency file: @chainlink/contracts/src/v0.6/VRFConsumerBase.sol // pragma solidity ^0.6.0; // import "@chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol"; // import "@chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol"; // import "@chainlink/contracts/src/v0.6/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 { using SafeMathChainlink for uint256; /** * @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; /** * @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 * @param _seed seed mixed into the input of the VRF. * * @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, uint256 _seed) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, _seed)); // 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, _seed, 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].add(1); return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* 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) public { 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); } } // Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Dependency file: @openzeppelin/contracts/GSN/Context.sol // pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Dependency file: @openzeppelin/contracts/access/Ownable.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts/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; } } // Dependency file: contracts/lib/Uint256ArrayUtils.sol // pragma solidity 0.6.10; /** * @title Uint256ArrayUtils * @author Prophecy * * Utility functions to handle uint256 Arrays */ library Uint256ArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(uint256[] memory A, uint256 a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(uint256[] memory A, uint256 a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(uint256[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { uint256 current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The uint256 to remove * @return Returns the array with the object removed. */ function remove(uint256[] memory A, uint256 a) internal pure returns (uint256[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("uint256 not in array."); } else { (uint256[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The uint256 to remove */ function removeStorage(uint256[] storage A, uint256 a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("uint256 not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(uint256[] memory A, uint256 index) internal pure returns (uint256[] memory, uint256) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); uint256[] memory newUint256s = new uint256[](length - 1); for (uint256 i = 0; i < index; i++) { newUint256s[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newUint256s[j - 1] = A[j]; } return (newUint256s, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; uint256[] memory newUint256s = new uint256[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newUint256s[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newUint256s[aLength + j] = B[j]; } return newUint256s; } /** * Validate uint256 array is not empty and contains no duplicate elements. * * @param A Array of uint256 */ function _validateLengthAndUniqueness(uint256[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate uint256"); } } // Dependency file: contracts/lib/AddressArrayUtils.sol // pragma solidity 0.6.10; /** * @title AddressArrayUtils * @author Prophecy * * Utility functions to handle uint256 Arrays */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } } // Dependency file: contracts/interfaces/IWETH.sol // pragma solidity 0.6.10; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title IWETH * @author Prophecy * * Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal * functionality. */ interface IWETH is IERC20{ function deposit() external payable; function withdraw(uint256 wad) external; } // Dependency file: contracts/interfaces/IController.sol // pragma solidity ^0.6.10; /** * @title IController * @author Prophecy */ interface IController { /** * Return WETH address. */ function getWeth() external view returns (address); /** * Getter for chanceToken */ function getChanceToken() external view returns (address); /** * Return VRF Key Hash. */ function getVrfKeyHash() external view returns (bytes32); /** * Return VRF Fee. */ function getVrfFee() external view returns (uint256); /** * Return Link Token address for VRF. */ function getLinkToken() external view returns (address); /** * Return VRF coordinator. */ function getVrfCoordinator() external view returns (address); /** * Return all pools addreses */ function getAllPools() external view returns (address[] memory); } // Dependency file: contracts/interfaces/IChanceToken.sol // pragma solidity ^0.6.10; /** * @title IChanceToken * @author Prophecy * * Interface for ChanceToken */ interface IChanceToken { /** * OWNER ALLOWED MINTER: Mint NFT */ function mint(address _account, uint256 _id, uint256 _amount) external; /** * OWNER ALLOWED BURNER: Burn NFT */ function burn(address _account, uint256 _id, uint256 _amount) external; } // Root file: contracts/ProphetPool.sol pragma solidity ^0.6.10; pragma experimental ABIEncoderV2; // import { VRFConsumerBase } from "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol"; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; // import { Uint256ArrayUtils } from "contracts/lib/Uint256ArrayUtils.sol"; // import { AddressArrayUtils } from "contracts/lib/AddressArrayUtils.sol"; // import { IWETH } from "contracts/interfaces/IWETH.sol"; // import { IController } from "contracts/interfaces/IController.sol"; // import { IChanceToken } from "contracts/interfaces/IChanceToken.sol"; /** * @title ProphetPool * @author Prophecy * * Smart contract that facilitates that draws lucky winners in the pool and distribute rewards to the winners. * It should be whitelisted for the mintable role for ChanceToken(ERC1155) */ contract ProphetPool is VRFConsumerBase, Ownable { using Uint256ArrayUtils for uint256[]; using AddressArrayUtils for address[]; /* ============ Structs ============ */ struct PoolConfig { uint256 numOfWinners; uint256 participantLimit; uint256 enterAmount; uint256 feePercentage; uint256 randomSeed; uint256 startedAt; } /* ============ Enums ============ */ enum PoolStatus { NOTSTARTED, INPROGRESS, CLOSED } /* ============ Events ============ */ event FeeRecipientSet(address indexed _feeRecipient); event MaxParticipationCompleted(address indexed _from); event RandomNumberGenerated(uint256 indexed randomness); event WinnersGenerated(uint256[] winnerIndexes); event PoolSettled(); event PoolStarted( uint256 participantLimit, uint256 numOfWinners, uint256 enterAmount, uint256 feePercentage, uint256 startedAt ); event PoolReset(); event EnteredPool(address indexed _participant, uint256 _amount, uint256 indexed _participantIndex); /* ============ State Variables ============ */ IController private controller; address private feeRecipient; string private poolName; IERC20 private enterToken; PoolStatus private poolStatus; PoolConfig private poolConfig; uint256 private chanceTokenId; address[] private participants; uint256[] private winnerIndexes; uint256 private totalEnteredAmount; uint256 private rewardPerParticipant; bool internal isRNDGenerated; uint256 internal randomResult; bool internal areWinnersGenerated; /* ============ Modifiers ============ */ modifier onlyValidPool() { require(participants.length < poolConfig.participantLimit, "exceed max"); require(poolStatus == PoolStatus.INPROGRESS, "in progress"); _; } modifier onlyEOA() { require(tx.origin == msg.sender, "should be EOA"); _; } /* ============ Constructor ============ */ /** * Create the ProphetPool with Chainlink VRF configuration for Random number generation. * * @param _poolName Pool name * @param _enterToken ERC20 token to enter the pool. If it's ETH pool, it should be WETH address * @param _controller Controller * @param _feeRecipient Where the fee go * @param _chanceTokenId ERC1155 Token id for chance token */ constructor( string memory _poolName, address _enterToken, address _controller, address _feeRecipient, uint256 _chanceTokenId ) public VRFConsumerBase(IController(_controller).getVrfCoordinator(), IController(_controller).getLinkToken()) { poolName = _poolName; enterToken = IERC20(_enterToken); controller = IController(_controller); feeRecipient = _feeRecipient; chanceTokenId = _chanceTokenId; poolStatus = PoolStatus.NOTSTARTED; } /* ============ External/Public Functions ============ */ /** * Set the Pool Config, initializes an instance of and start the pool. * * @param _numOfWinners Number of winners in the pool * @param _participantLimit Maximum number of paricipants * @param _enterAmount Exact amount to enter this pool * @param _feePercentage Manager fee of this pool * @param _randomSeed Seed for Random Number Generation */ function setPoolRules( uint256 _numOfWinners, uint256 _participantLimit, uint256 _enterAmount, uint256 _feePercentage, uint256 _randomSeed ) external onlyOwner { require(poolStatus == PoolStatus.NOTSTARTED, "in progress"); require(_numOfWinners != 0, "invalid numOfWinners"); require(_numOfWinners < _participantLimit, "too much numOfWinners"); poolConfig = PoolConfig( _numOfWinners, _participantLimit, _enterAmount, _feePercentage, _randomSeed, block.timestamp ); poolStatus = PoolStatus.INPROGRESS; emit PoolStarted( _participantLimit, _numOfWinners, _enterAmount, _feePercentage, block.timestamp ); } /** * Set the Pool Config, initializes an instance of and start the pool. * * @param _feeRecipient Number of winners in the pool */ function setFeeRecipient(address _feeRecipient) external onlyOwner { require(_feeRecipient != address(0), "invalid address"); feeRecipient = _feeRecipient; emit FeeRecipientSet(feeRecipient); } /** * Enter pool with ETH */ function enterPoolEth() external payable onlyValidPool onlyEOA returns (uint256) { require(msg.value == poolConfig.enterAmount, "insufficient amount"); if (!_isEthPool()) { revert("not accept ETH"); } // wrap ETH to WETH IWETH(controller.getWeth()).deposit{ value: msg.value }(); return _enterPool(); } /** * Enter pool with ERC20 token */ function enterPool() external onlyValidPool onlyEOA returns (uint256) { enterToken.transferFrom( msg.sender, address(this), poolConfig.enterAmount ); return _enterPool(); } /** * Settle the pool, the winners are selected randomly and fee is transfer to the manager. */ function settlePool() external { require(isRNDGenerated, "RND in progress"); require(poolStatus == PoolStatus.INPROGRESS, "pool in progress"); // generate winnerIndexes until the numOfWinners reach uint256 newRandom = randomResult; uint256 offset = 0; while(winnerIndexes.length < poolConfig.numOfWinners) { uint256 winningIndex = newRandom.mod(poolConfig.participantLimit); if (!winnerIndexes.contains(winningIndex)) { winnerIndexes.push(winningIndex); } offset = offset.add(1); newRandom = _getRandomNumberBlockchain(offset, newRandom); } areWinnersGenerated = true; emit WinnersGenerated(winnerIndexes); // set pool CLOSED status poolStatus = PoolStatus.CLOSED; // transfer fees uint256 feeAmount = totalEnteredAmount.mul(poolConfig.feePercentage).div(100); rewardPerParticipant = (totalEnteredAmount.sub(feeAmount)).div(poolConfig.numOfWinners); _transferEnterToken(feeRecipient, feeAmount); // collectRewards(); emit PoolSettled(); } /** * The winners of the pool can call this function to transfer their winnings * from the pool contract to their own address. */ function collectRewards() external { require(poolStatus == PoolStatus.CLOSED, "not settled"); for (uint256 i = 0; i < poolConfig.participantLimit; i = i.add(1)) { address player = participants[i]; if (winnerIndexes.contains(i)) { // if winner _transferEnterToken(player, rewardPerParticipant); } else { // if loser IChanceToken(controller.getChanceToken()).mint(player, chanceTokenId, 1); } } _resetPool(); } /** * The contract will receive Ether */ receive() external payable {} /** * Getter for controller */ function getController() external view returns (address) { return address(controller); } /** * Getter for fee recipient */ function getFeeRecipient() external view returns (address) { return feeRecipient; } /** * Getter for poolName */ function getPoolName() external view returns (string memory) { return poolName; } /** * Getter for enterToken */ function getEnterToken() external view returns (address) { return address(enterToken); } /** * Getter for chanceTokenId */ function getChanceTokenId() external view returns (uint256) { return chanceTokenId; } /** * Getter for poolStatus */ function getPoolStatus() external view returns (PoolStatus) { return poolStatus; } /** * Getter for poolConfig */ function getPoolConfig() external view returns (PoolConfig memory) { return poolConfig; } /** * Getter for totalEnteredAmount */ function getTotalEnteredAmount() external view returns (uint256) { return totalEnteredAmount; } /** * Getter for rewardPerParticipant */ function getRewardPerParticipant() external view returns (uint256) { return rewardPerParticipant; } /** * Get all participants */ function getParticipants() external view returns(address[] memory) { return participants; } /** * Get one participant by index * @param _index Index of the participants array */ function getParticipant(uint256 _index) external view returns(address) { return participants[_index]; } /** * Getter for winnerIndexes */ function getWinnerIndexes() external view returns(uint256[] memory) { return winnerIndexes; } /** * Get if the account is winner */ function isWinner(address _account) external view returns(bool) { (uint256 index, bool isExist) = participants.indexOf(_account); if (isExist) { return winnerIndexes.contains(index); } else { return false; } } /* ============ Private/Internal Functions ============ */ /** * Participant enters the pool and enter amount is transferred from the user to the pool. */ function _enterPool() internal returns(uint256 _participantIndex) { participants.push(msg.sender); totalEnteredAmount = totalEnteredAmount.add(poolConfig.enterAmount); if (participants.length == poolConfig.participantLimit) { emit MaxParticipationCompleted(msg.sender); _getRandomNumber(poolConfig.randomSeed); } _participantIndex = (participants.length).sub(1); emit EnteredPool(msg.sender, poolConfig.enterAmount, _participantIndex); } /** * Reset the pool, clears the existing state variable values and the pool can be initialized again. */ function _resetPool() internal { poolStatus = PoolStatus.INPROGRESS; delete totalEnteredAmount; delete rewardPerParticipant; isRNDGenerated = false; randomResult = 0; areWinnersGenerated = false; delete winnerIndexes; delete participants; emit PoolReset(); uint256 tokenBalance = enterToken.balanceOf(address(this)); if (tokenBalance > 0) { _transferEnterToken(feeRecipient, tokenBalance); } } /** * Transfer enterToken even it's ETH or ERC20. * * @param _to Offset to generate the random number * @param _amount Random number to generate the other random number */ function _transferEnterToken(address _to, uint256 _amount) internal { if (_isEthPool()) { IWETH(controller.getWeth()).withdraw(_amount); (bool status, ) = payable(_to).call{value: _amount}(""); require(status, "ETH not transferred"); } else { enterToken.transfer(address(_to), _amount); } } /** * Check pool is ETH pool or not */ function _isEthPool() internal view returns (bool) { return address(enterToken) == controller.getWeth(); } /** * Generate a random number based on the blockHash and random offset * * @param _offset Offset to generate the random number * @param _randomness Random number to generate the other random number */ function _getRandomNumberBlockchain(uint256 _offset, uint256 _randomness) internal view returns (uint256) { bytes32 baseHash = keccak256( abi.encodePacked( blockhash(block.number), bytes32(_offset), bytes32(_randomness) ) ); return uint256(baseHash); } /** * Calls ChainLink Oracle's inherited function for Random Number Generation. * The contract must have enough LINK required for VRF. * * @param _userProvidedSeed Seed to generate the random number */ function _getRandomNumber(uint256 _userProvidedSeed) internal returns (bytes32 requestId) { require( IERC20(controller.getLinkToken()).balanceOf(address(this)) >= controller.getVrfFee(), "not enough LINK" ); randomResult = 0; isRNDGenerated = false; return requestRandomness( controller.getVrfKeyHash(), controller.getVrfFee(), _userProvidedSeed ); } /** * Callback function used by VRF Coordinator. * * @param _randomness Generated random number */ function fulfillRandomness(bytes32, uint256 _randomness) internal override { randomResult = _randomness; isRNDGenerated = true; emit RandomNumberGenerated(_randomness); } }
Set the Pool Config, initializes an instance of and start the pool. _numOfWinners Number of winners in the pool _participantLimit Maximum number of paricipants _enterAmount Exact amount to enter this pool _feePercentage Manager fee of this pool _randomSeed Seed for Random Number Generation/
function setPoolRules( uint256 _numOfWinners, uint256 _participantLimit, uint256 _enterAmount, uint256 _feePercentage, uint256 _randomSeed ) external onlyOwner { require(poolStatus == PoolStatus.NOTSTARTED, "in progress"); require(_numOfWinners != 0, "invalid numOfWinners"); require(_numOfWinners < _participantLimit, "too much numOfWinners"); poolConfig = PoolConfig( _numOfWinners, _participantLimit, _enterAmount, _feePercentage, _randomSeed, block.timestamp ); poolStatus = PoolStatus.INPROGRESS; emit PoolStarted( _participantLimit, _numOfWinners, _enterAmount, _feePercentage, block.timestamp ); }
225,630
//SPDX-License-Identifier: Unlicense pragma solidity 0.6.12; import "./StakeManager.sol"; import "./interfaces/PriceConsumerV3.sol"; import "./ownable.sol"; //import "./interfaces/AAVE/ILendingPool.sol"; import {ILendingPool} from "@aave/protocol-v2/contracts/interfaces/ILendingPool.sol"; import {ILendingPoolAddressesProvider} from "@aave/protocol-v2/contracts/interfaces/ILendingPoolAddressesProvider.sol"; interface PriceFeedInterface { function getLatestPrice() external view returns(int); } contract AppManager { address public owner; StakeManager public stakeManager; uint256 depositCount = 0; // mini stake of a dollar so pricefeed to check?!? uint256 minStake = 100_000 * (10**9); // 100k gwei | 0.0001 eth // ENTRY POINT FOR AAVE required pragma solidity 0.6.12; // addresses -> https://docs.aave.com/developers/deployed-contracts/deployed-contracts // Kovan testnet 0x88757f2f99175387aB4C6a4b3067c77A695b0349 //Error: Transaction reverted: function call to a non-contract account //ILendingPoolAddressesProvider provider = ILendingPoolAddressesProvider(0x88757f2f99175387aB4C6a4b3067c77A695b0349); //ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); // CHAINLINK PRICEFEED INTERFACE //string memory nameAsset = "ETH/USD"; //Network: Kovan //Aggregator: ETH/USD address ETH_USD = 0x9326BFA02ADD2366b30bacB125260Af641031331; function _getPrice() internal view returns(int){ PriceFeedInterface(ETH_USD).getLatestPrice(); } // AAVE INTERFACE // owneraddress will make deposits, withdraws, loans internally // but publicly display its health to Insuree, Delegates, Owner // "All of AAVE's functionalities available in testnet is the same in the mainnet app," mapping(address => Deposit[]) deposits; // maybe unnecessary to structify struct Deposit { uint256 id; uint256 amount; uint256 timestamp; } // this can be recorded as an event w/out using up storage event DepositReceived( address indexed sender, uint256 indexed amount, uint256 depositId, uint256 indexed timestamp ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(owner == msg.sender, "OnlyOwner"); _; } modifier canDeposit() { require(address(stakeManager) != address(0), "StakeManager not ready"); _; } function setStakeManager(address _stakeManager) public onlyOwner { stakeManager = StakeManager(payable(_stakeManager)); } // should we record/denominate in USD? // should be just deposit USDC/DAI? function deposit() public payable canDeposit { require(msg.value >= minStake, "Deposit not high enough"); // add check to only allow authorized deposit for x policy // and check if deposit is already made // is this required to cast to payable? stakeManager.deposit{value: msg.value}(depositCount); // initialze next deposit in array as ref Deposit storage _deposit = deposits[msg.sender].push(); // populate deposit _deposit.id = depositCount; _deposit.amount = msg.value; _deposit.timestamp = block.timestamp; // emit and increment emit DepositReceived( msg.sender, msg.value, depositCount, block.timestamp ); depositCount++; } function balanceOf(address _account) public view returns (uint256) { uint256 _total; Deposit[] storage _deposits = deposits[_account]; // What does this line do? for (uint256 ii; ii < _deposits.length; ii++) { _total += _deposits[ii].amount; } return _total; } // test Price From ChainLink function ViewPriceOfEth() public view returns(int) { return _getPrice(); } uint256 depositLimit; //EMF errorMsg for APIs or Dapp string depositFailedStatement = "Deposit Not Made Over the limit"; function EMFCall(address _userAddress) external returns(string memory _externalMsg) { // Check if user has existing EMFcontract? with _userAddress // check if userBalance is currently overlimit disallow deposit // limit is $1,000 nothing above // check if userBalance + deposit pushes deposit overlimit depositLimit = 1000; require(balanceOf(_userAddress) == depositLimit); } if(depositLimit <= 1000) { //Depoist to EMF required parameters? deposit(); } else { // else stop deposit return depositFailedStatement; } // add interest to userAccount Deposit InterestEarnedCall() } // EMFreturnUser'sAPY per month function ViewEMFInterest() external { // total of users account balance // account_balance + InterestEarn } // Function to View the total account balance + Interest Earned function ViewEMFTotal(address _userAddress) view external returns(uint256){ // view the total recorded deposit //balance = balanceOf(_userAddress); return balanceOf(_userAddress); } // Function Check if Contract Ended function ViewContractLife(address _userAddress) view external returns(uint) { // Check userbalance if its 0 // if contract is 0 Contract Concludes (internal function of App Manager) // Reactivate by deposit // Not Reacttivatted by Withdraw } uint EMFAPY; // Interest calulated based of total deposit of userAccount // returns number needed to withdraw from insurance float and add to userAccouent // when withdraw is triggered. function InterestEarnedCall(uint _accountBalance, uint _APY) internal returns(uint _InterestEarned) { // userAddress, _account_balace // uint muiltplier; uint InterestEarned; uint APM; // %3.00 // Monthly APY is caluated APM = _APY / 12; // divided by 100 convert out of percent muiltplier = APM / 100; // Interest based off the Users Total accountBalance InterestEarned = _accountBalance * muiltplier; // Call is made to recorded the InterestedEarned so // when the user Withdraw it Withdraws with the InterestedEarned. return InterestEarned; } // End of Contract }
Check if user has existing EMFcontract? with _userAddress check if userBalance is currently overlimit disallow deposit limit is $1,000 nothing above check if userBalance + deposit pushes deposit overlimit
function EMFCall(address _userAddress) external returns(string memory _externalMsg) { depositLimit = 1000; require(balanceOf(_userAddress) == depositLimit); }
15,814,423
./partial_match/4/0x2768E24672b6EE867f63c021d9149be1f789B870/sources/AFIToken.sol
external Used to mint AFITokens, given an underlying amount (eg. DAI). This method triggers a rebalance of the pools if _skipRebalance is set to false NOTE: User should 'approve' _amount of tokens before calling mintAFIToken NOTE 2: this method can be paused This method use GasTokens of this contract (if present) to get a gas discount _amount : amount of underlying token to be lended _referral : referral address return mintedTokens : amount of AFITokens minted/ Get current AFIToken price transfer tokens to this contract lend assets and rebalance the pool if needed
function mintAFIToken(uint256 _amount, bool _skipRebalance, address _referral) external nonReentrant whenNotPaused returns (uint256 mintedTokens) { _minterBlock = keccak256(abi.encodePacked(tx.origin, block.number)); _redeemGovTokens(msg.sender, false); uint256 afiPrice = _tokenPrice(); IERC20(token).safeTransferFrom(msg.sender, address(this), _amount); if (!_skipRebalance) { _rebalance(); } mintedTokens = _amount.mul(ONE_18).div(afiPrice); _mint(msg.sender, mintedTokens); if (_referral != address(0)) { emit Referral(_amount, _referral); } }
8,569,588
./full_match/1/0x48deE19C0e44c147934702c12dc98963CA831009/sources/src/Asset/ERC1155ERC721.sol
check whether address `who` is given minting bouncer rights. who The address to query. return whether the address has minting rights.
function isBouncer(address who) external view returns(bool) { return _bouncers[who]; } event MetaTransactionProcessor(address metaTransactionProcessor, bool enabled);
4,919,183
./full_match/56/0x553d31daaC69a4bfb372482b9400eFcC04B93441/sources/project:/contracts/BEP20Token.sol
See {BEP20-approve}. Requirements: - `spender` cannot be the zero address./
function approve(address spender, uint256 amount) external returns (bool) { _approve(_msgSender(), spender, amount); return true; }
3,249,455