file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./partial_match/4/0xd5fB49a8f0156CE350A10403c453926a886746A6/sources/BActions.sol
Absorb any tokens that have been sent to this contract into the pool
function gulp(address token) external _logs_ _lock_ { require(_records[token].bound, "ERR_NOT_BOUND"); _records[token].balance = IERC20(token).balanceOf(address(this)); }
8,612,241
/** * ________ __ __ __ __ _______ __ __ __ __ * | \| \ | \ | \ | \ | \ | \ | \ | \ | \ * | $$$$$$$$ \$$ _______ ____| $$ _| $$_ | $$____ ______ | $$$$$$$\ ______ | $$____ | $$____ \$$ _| $$_ * | $$__ | \| \ / $$ | $$ \ | $$ \ / \ | $$__| $$ | \ | $$ \ | $$ \ | \| $$ \ * | $$ \ | $$| $$$$$$$\| $$$$$$$ \$$$$$$ | $$$$$$$\| $$$$$$\ | $$ $$ \$$$$$$\| $$$$$$$\| $$$$$$$\| $$ \$$$$$$ * | $$$$$ | $$| $$ | $$| $$ | $$ | $$ __ | $$ | $$| $$ $$ | $$$$$$$\ / $$| $$ | $$| $$ | $$| $$ | $$ __ * | $$ | $$| $$ | $$| $$__| $$ | $$| \| $$ | $$| $$$$$$$$ | $$ | $$| $$$$$$$| $$__/ $$| $$__/ $$| $$ | $$| \ * | $$ | $$| $$ | $$ \$$ $$ \$$ $$| $$ | $$ \$$ \ | $$ | $$ \$$ $$| $$ $$| $$ $$| $$ \$$ $$ * \$$ \$$ \$$ \$$ \$$$$$$$ \$$$$ \$$ \$$ \$$$$$$$ \$$ \$$ \$$$$$$$ \$$$$$$$ \$$$$$$$ \$$ \$$$$ * * * ╔═╗┌─┐┌─┐┬┌─┐┬┌─┐┬ ┌─────────────────────────┐ ╦ ╦┌─┐┌┐ ╔═╗┬┌┬┐┌─┐ * ║ ║├┤ ├┤ ││ │├─┤│ │https://findtherabbit.me │ ║║║├┤ ├┴┐╚═╗│ │ ├┤ * ╚═╝└ └ ┴└─┘┴┴ ┴┴─┘ └─┬─────────────────────┬─┘ ╚╩╝└─┘└─┘╚═╝┴ ┴ └─┘ */ // File: contracts/lib/SafeMath.sol pragma solidity 0.5.4; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: contracts/Messages.sol pragma solidity 0.5.4; /** * EIP712 Ethereum typed structured data hashing and signing */ contract Messages { struct AcceptGame { uint256 bet; bool isHost; address opponentAddress; bytes32 hashOfMySecret; bytes32 hashOfOpponentSecret; } struct SecretData { bytes32 salt; uint8 secret; } /** * Domain separator encoding per EIP 712. * keccak256( * "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)" * ) */ bytes32 public constant EIP712_DOMAIN_TYPEHASH = 0xd87cd6ef79d4e2b95e15ce8abf732db51ec771f1ca2edccf22a46c729ac56472; /** * AcceptGame struct type encoding per EIP 712 * keccak256( * "AcceptGame(uint256 bet,bool isHost,address opponentAddress,bytes32 hashOfMySecret,bytes32 hashOfOpponentSecret)" * ) */ bytes32 private constant ACCEPTGAME_TYPEHASH = 0x5ceee84403c984fbd9fb4ebf11b09c4f28f87290116c8b7f24a3e2a89d26588f; /** * Domain separator per EIP 712 */ bytes32 public DOMAIN_SEPARATOR; /** * @notice Calculates acceptGameHash according to EIP 712. * @param _acceptGame AcceptGame instance to hash. * @return bytes32 EIP 712 hash of _acceptGame. */ function _hash(AcceptGame memory _acceptGame) internal pure returns (bytes32) { return keccak256(abi.encode( ACCEPTGAME_TYPEHASH, _acceptGame.bet, _acceptGame.isHost, _acceptGame.opponentAddress, _acceptGame.hashOfMySecret, _acceptGame.hashOfOpponentSecret )); } /** * @notice Calculates secretHash according to EIP 712. * @param _salt Salt of the gamer. * @param _secret Secret of the gamer. */ function _hashOfSecret(bytes32 _salt, uint8 _secret) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_salt, _secret)); } /** * @return the recovered address from the signature */ function _recoverAddress( bytes32 messageHash, bytes memory signature ) internal view returns (address) { bytes32 r; bytes32 s; bytes1 v; // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := mload(add(signature, 0x60)) } bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, messageHash )); return ecrecover(digest, uint8(v), r, s); } /** * @return the address of the gamer signing the AcceptGameMessage */ function _getSignerAddress( uint256 _value, bool _isHost, address _opponentAddress, bytes32 _hashOfMySecret, bytes32 _hashOfOpponentSecret, bytes memory signature ) internal view returns (address playerAddress) { AcceptGame memory message = AcceptGame({ bet: _value, isHost: _isHost, opponentAddress: _opponentAddress, hashOfMySecret: _hashOfMySecret, hashOfOpponentSecret: _hashOfOpponentSecret }); bytes32 messageHash = _hash(message); playerAddress = _recoverAddress(messageHash, signature); } } // File: contracts/Ownable.sol pragma solidity 0.5.4; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "not owner"); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/Claimable.sol pragma solidity 0.5.4; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner, "not pending owner"); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(_owner, pendingOwner); _owner = pendingOwner; pendingOwner = address(0); } } // File: contracts/lib/ERC20Basic.sol pragma solidity 0.5.4; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); } // File: contracts/FindTheRabbit.sol pragma solidity 0.5.4; /** * @title FindTheRabbit * @dev Base game contract */ contract FindTheRabbit is Messages, Claimable { using SafeMath for uint256; enum GameState { Invalid, // Default value for a non-created game HostBetted, // A player, who initiated an offchain game and made a bet JoinBetted, // A player, who joined the game and made a bet Filled, // Both players made bets DisputeOpenedByHost, // Dispute is opened by the initiating player DisputeOpenedByJoin, // Dispute is opened by the joining player DisputeWonOnTimeoutByHost, // Dispute is closed on timeout and the prize was taken by the initiating player DisputeWonOnTimeoutByJoin, // Dispute is closed on timeout and the prize was taken by the joining player CanceledByHost, // The joining player has not made a bet and the game is closed by the initiating player CanceledByJoin, // The initiating player has not made a bet and the game is closed by the joining player WonByHost, // The initiating has won the game WonByJoin // The joining player has won the game } //Event is triggered after both players have placed their bets event GameCreated( address indexed host, address indexed join, uint256 indexed bet, bytes32 gameId, GameState state ); //Event is triggered after the first bet has been placed event GameOpened(bytes32 gameId, address indexed player); //Event is triggered after the game has been closed event GameCanceled(bytes32 gameId, address indexed player, address indexed opponent); /** * @dev Event triggered after after opening a dispute * @param gameId 32 byte game identifier * @param disputeOpener is a player who opened a dispute * @param defendant is a player against whom a dispute is opened */ event DisputeOpened(bytes32 gameId, address indexed disputeOpener, address indexed defendant); //Event is triggered after a dispute is resolved by the function resolveDispute() event DisputeResolved(bytes32 gameId, address indexed player); //Event is triggered after a dispute is closed after the amount of time specified in disputeTimer event DisputeClosedOnTimeout(bytes32 gameId, address indexed player); //Event is triggered after sending the winning to the winner event WinnerReward(address indexed winner, uint256 amount); //Event is triggered after the jackpot is sent to the winner event JackpotReward(bytes32 gameId, address player, uint256 amount); //Event is triggered after changing the gameId that claims the jackpot event CurrentJackpotGame(bytes32 gameId); //Event is triggered after sending the reward to the referrer event ReferredReward(address referrer, uint256 amount); // Emitted when calimTokens function is invoked. event ClaimedTokens(address token, address owner, uint256 amount); //The address of the contract that will verify the signature per EIP 712. //In this case, the current address of the contract. address public verifyingContract = address(this); //An disambiguating salt for the protocol per EIP 712. //Set through the constructor. bytes32 public salt; //An address of the creators' account receiving the percentage of Commission for the game address payable public teamWallet; //Percentage of commission from the game that is sent to the creators uint256 public commissionPercent; //Percentage of reward to the player who invited new players //0.1% is equal 1 //0.5% is equal 5 //1% is equal 10 //10% is equal 100 uint256 public referralPercent; //Maximum allowed value of the referralPercent. (10% = 100) uint256 public maxReferralPercent = 100; //Minimum bet value to create a new game uint256 public minBet = 0.01 ether; //Percentage of game commission added to the jackpot value uint256 public jackpotPercent; //Jackpot draw time in UNIX time stamp format. uint256 public jackpotDrawTime; //Current jackpot value uint256 public jackpotValue; //The current value of the gameId of the applicant for the jackpot. bytes32 public jackpotGameId; //Number of seconds added to jackpotDrawTime each time a new game is added to the jackpot. uint256 public jackpotGameTimerAddition; //Initial timeout for a new jackpot round. uint256 public jackpotAccumulationTimer; //Timeout in seconds during which the dispute cannot be opened. uint256 public revealTimer; //Maximum allowed value of the minRevealTimer in seconds. uint256 public maxRevealTimer; //Minimum allowed value of the minRevealTimer in seconds. uint256 public minRevealTimer; //Timeout in seconds during which the dispute cannot be closed //and players can call the functions win() and resolveDispute(). uint256 public disputeTimer; //Maximum allowed value of the maxDisputeTimer in seconds. uint256 public maxDisputeTimer; //Minimum allowed value of the minDisputeTimer in seconds. uint256 public minDisputeTimer; //Timeout in seconds after the first bet //during which the second player's bet is expected //and the game cannot be closed. uint256 public waitingBetTimer; //Maximum allowed value of the waitingBetTimer in seconds. uint256 public maxWaitingBetTimer; //Minimum allowed value of the waitingBetTimer in seconds. uint256 public minWaitingBetTimer; //The time during which the game must be completed to qualify for the jackpot. uint256 public gameDurationForJackpot; uint256 public chainId; //Mapping for storing information about all games mapping(bytes32 => Game) public games; //Mapping for storing information about all disputes mapping(bytes32 => Dispute) public disputes; //Mapping for storing information about all players mapping(address => Statistics) public players; struct Game { uint256 bet; // bet value for the game address payable host; // address of the initiating player address payable join; // address of the joining player uint256 creationTime; // the time of the last bet in the game. GameState state; // current state of the game bytes hostSignature; // the value of the initiating player's signature bytes joinSignature; // the value of the joining player's signature bytes32 gameId; // 32 byte game identifier } struct Dispute { address payable disputeOpener; // address of the player, who opened the dispute. uint256 creationTime; // dispute opening time of the dispute. bytes32 opponentHash; // hash from an opponent's secret and salt uint256 secret; // secret value of the player, who opened the dispute bytes32 salt; // salt value of the player, who opened the dispute bool isHost; // true if the player initiated the game. } struct Statistics { uint256 totalGames; // totalGames played by the player uint256 totalUnrevealedGames; // total games that have been disputed against a player for unrevealing the secret on time uint256 totalNotFundedGames; // total number of games a player has not send funds on time uint256 totalOpenedDisputes; // total number of disputed games created by a player against someone for unrevealing the secret on time uint256 avgBetAmount; // average bet value } /** * @dev Throws if the game state is not Filled. */ modifier isFilled(bytes32 _gameId) { require(games[_gameId].state == GameState.Filled, "game state is not Filled"); _; } /** * @dev Throws if the game is not Filled or dispute has not been opened. */ modifier verifyGameState(bytes32 _gameId) { require( games[_gameId].state == GameState.DisputeOpenedByHost || games[_gameId].state == GameState.DisputeOpenedByJoin || games[_gameId].state == GameState.Filled, "game state are not Filled or OpenedDispute" ); _; } /** * @dev Throws if at least one player has not made a bet. */ modifier isOpen(bytes32 _gameId) { require( games[_gameId].state == GameState.HostBetted || games[_gameId].state == GameState.JoinBetted, "game state is not Open"); _; } /** * @dev Throws if called by any account other than the participant's one in this game. */ modifier onlyParticipant(bytes32 _gameId) { require( games[_gameId].host == msg.sender || games[_gameId].join == msg.sender, "you are not a participant of this game" ); _; } /** * @dev Setting the parameters of the contract. * Description of the main parameters can be found above. * @param _chainId Id of the current chain. * @param _maxValueOfTimer maximum value for revealTimer, disputeTimer and waitingBetTimer. * Minimum values are set with revealTimer, disputeTimer, and waitingBetTimer values passed to the constructor. */ constructor ( uint256 _chainId, address payable _teamWallet, uint256 _commissionPercent, uint256 _jackpotPercent, uint256 _referralPercent, uint256 _jackpotGameTimerAddition, uint256 _jackpotAccumulationTimer, uint256 _revealTimer, uint256 _disputeTimer, uint256 _waitingBetTimer, uint256 _gameDurationForJackpot, bytes32 _salt, uint256 _maxValueOfTimer ) public { teamWallet = _teamWallet; jackpotDrawTime = getTime().add(_jackpotAccumulationTimer); jackpotAccumulationTimer = _jackpotAccumulationTimer; commissionPercent = _commissionPercent; jackpotPercent = _jackpotPercent; referralPercent = _referralPercent; jackpotGameTimerAddition = _jackpotGameTimerAddition; revealTimer = _revealTimer; minRevealTimer = _revealTimer; maxRevealTimer = _maxValueOfTimer; disputeTimer = _disputeTimer; minDisputeTimer = _disputeTimer; maxDisputeTimer = _maxValueOfTimer; waitingBetTimer = _waitingBetTimer; minWaitingBetTimer = _waitingBetTimer; maxWaitingBetTimer = _maxValueOfTimer; gameDurationForJackpot = _gameDurationForJackpot; salt = _salt; chainId = _chainId; DOMAIN_SEPARATOR = keccak256(abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256("Find The Rabbit"), keccak256("0.1"), _chainId, verifyingContract, salt )); } /** * @dev Change the current waitingBetTimer value. * Change can be made only within the maximum and minimum values. * @param _waitingBetTimer is a new value of waitingBetTimer */ function setWaitingBetTimerValue(uint256 _waitingBetTimer) external onlyOwner { require(_waitingBetTimer >= minWaitingBetTimer, "must be more than minWaitingBetTimer"); require(_waitingBetTimer <= maxWaitingBetTimer, "must be less than maxWaitingBetTimer"); waitingBetTimer = _waitingBetTimer; } /** * @dev Change the current disputeTimer value. * Change can be made only within the maximum and minimum values. * @param _disputeTimer is a new value of disputeTimer. */ function setDisputeTimerValue(uint256 _disputeTimer) external onlyOwner { require(_disputeTimer >= minDisputeTimer, "must be more than minDisputeTimer"); require(_disputeTimer <= maxDisputeTimer, "must be less than maxDisputeTimer"); disputeTimer = _disputeTimer; } /** * @dev Change the current revealTimer value. * Change can be made only within the maximum and minimum values. * @param _revealTimer is a new value of revealTimer */ function setRevealTimerValue(uint256 _revealTimer) external onlyOwner { require(_revealTimer >= minRevealTimer, "must be more than minRevealTimer"); require(_revealTimer <= maxRevealTimer, "must be less than maxRevealTimer"); revealTimer = _revealTimer; } /** * @dev Change the current minBet value. * @param _newValue is a new value of minBet. */ function setMinBetValue(uint256 _newValue) external onlyOwner { require(_newValue != 0, "must be greater than 0"); minBet = _newValue; } /** * @dev Change the current jackpotGameTimerAddition. * Change can be made only within the maximum and minimum values. * Jackpot should not hold significant value * @param _jackpotGameTimerAddition is a new value of jackpotGameTimerAddition */ function setJackpotGameTimerAddition(uint256 _jackpotGameTimerAddition) external onlyOwner { if (chainId == 1) { // jackpot must be less than 150 DAI. 1 ether = 150 DAI require(jackpotValue <= 1 ether); } if (chainId == 99) { // jackpot must be less than 150 DAI. 1 POA = 0.03 DAI require(jackpotValue <= 4500 ether); } require(_jackpotGameTimerAddition >= 2 minutes, "must be more than 2 minutes"); require(_jackpotGameTimerAddition <= 1 hours, "must be less than 1 hour"); jackpotGameTimerAddition = _jackpotGameTimerAddition; } /** * @dev Change the current referralPercent value. * Example: * 1 = 0.1% * 5 = 0.5% * 10 = 1% * @param _newValue is a new value of referralPercent. */ function setReferralPercentValue(uint256 _newValue) external onlyOwner { require(_newValue <= maxReferralPercent, "must be less than maxReferralPercent"); referralPercent = _newValue; } /** * @dev Change the current commissionPercent value. * Example: * 1 = 1% * @param _newValue is a new value of commissionPercent. */ function setCommissionPercent(uint256 _newValue) external onlyOwner { require(_newValue <= 20, "must be less than 20"); commissionPercent = _newValue; } /** * @dev Change the current teamWallet address. * @param _newTeamWallet is a new teamWallet address. */ function setTeamWalletAddress(address payable _newTeamWallet) external onlyOwner { require(_newTeamWallet != address(0)); teamWallet = _newTeamWallet; } /** * @return information about the jackpot. */ function getJackpotInfo() external view returns ( uint256 _jackpotDrawTime, uint256 _jackpotValue, bytes32 _jackpotGameId ) { _jackpotDrawTime = jackpotDrawTime; _jackpotValue = jackpotValue; _jackpotGameId = jackpotGameId; } /** * @return timers used for games. */ function getTimers() external view returns ( uint256 _revealTimer, uint256 _disputeTimer, uint256 _waitingBetTimer, uint256 _jackpotAccumulationTimer ) { _revealTimer = revealTimer; _disputeTimer = disputeTimer; _waitingBetTimer = waitingBetTimer; _jackpotAccumulationTimer = jackpotAccumulationTimer; } /** * @dev Transfer of tokens from the contract * @param _token the address of the tokens to be transferred. */ function claimTokens(address _token) public onlyOwner { ERC20Basic erc20token = ERC20Basic(_token); uint256 balance = erc20token.balanceOf(address(this)); erc20token.transfer(owner(), balance); emit ClaimedTokens(_token, owner(), balance); } /** * @dev Allows to create a game and place a bet. * @param _isHost True if the sending account initiated the game. * @param _hashOfMySecret Hash value of the sending account's secret and salt. * @param _hashOfOpponentSecret Hash value of the opponent account's secret and salt. * @param _hostSignature Signature of the initiating player from the following values: * bet, * isHost, // true * opponentAddress, // join address * hashOfMySecret, // hash of host secret * hashOfOpponentSecret // hash of join secret * @param _joinSignature Signature of the joining player from the following values: * bet, * isHost, // false * opponentAddress, // host address * hashOfMySecret, // hash of join secret * hashOfOpponentSecret // hash of host secret */ function createGame( bool _isHost, bytes32 _hashOfMySecret, bytes32 _hashOfOpponentSecret, bytes memory _hostSignature, bytes memory _joinSignature ) public payable { require(msg.value >= minBet, "must be greater than the minimum value"); bytes32 gameId = getGameId(_hostSignature, _joinSignature); address opponent = _getSignerAddress( msg.value, !_isHost, msg.sender, _hashOfOpponentSecret, _hashOfMySecret, _isHost ? _joinSignature : _hostSignature); require(opponent != msg.sender, "send your opponent's signature"); Game storage game = games[gameId]; if (game.gameId == 0){ _recordGameInfo(msg.value, _isHost, gameId, opponent, _hostSignature, _joinSignature); emit GameOpened(game.gameId, msg.sender); } else { require(game.host == msg.sender || game.join == msg.sender, "you are not paticipant in this game"); require(game.state == GameState.HostBetted || game.state == GameState.JoinBetted, "the game is not Opened"); if (_isHost) { require(game.host == msg.sender, "you are not the host in this game"); require(game.join == opponent, "invalid join signature"); require(game.state == GameState.JoinBetted, "you have already made a bet"); } else { require(game.join == msg.sender, "you are not the join in this game."); require(game.host == opponent, "invalid host signature"); require(game.state == GameState.HostBetted, "you have already made a bet"); } game.creationTime = getTime(); game.state = GameState.Filled; emit GameCreated(game.host, game.join, game.bet, game.gameId, game.state); } } /** * @dev If the disclosure is true, the winner gets a prize. * @notice a referrer will be sent a reward to. * only if the referrer has previously played the game and the sending account has not. * @param _gameId 32 byte game identifier. * @param _hostSecret The initiating player's secret. * @param _hostSalt The initiating player's salt. * @param _joinSecret The joining player's secret. * @param _joinSalt The joining player's salt. * @param _referrer The winning player's referrer. The referrer must have played games. */ function win( bytes32 _gameId, uint8 _hostSecret, bytes32 _hostSalt, uint8 _joinSecret, bytes32 _joinSalt, address payable _referrer ) public verifyGameState(_gameId) onlyParticipant(_gameId) { Game storage game = games[_gameId]; bytes32 hashOfHostSecret = _hashOfSecret(_hostSalt, _hostSecret); bytes32 hashOfJoinSecret = _hashOfSecret(_joinSalt, _joinSecret); address host = _getSignerAddress( game.bet, true, game.join, hashOfHostSecret, hashOfJoinSecret, game.hostSignature ); address join = _getSignerAddress( game.bet, false, game.host, hashOfJoinSecret, hashOfHostSecret, game.joinSignature ); require(host == game.host && join == game.join, "invalid reveals"); address payable winner; if (_hostSecret == _joinSecret){ winner = game.join; game.state = GameState.WonByJoin; } else { winner = game.host; game.state = GameState.WonByHost; } if (isPlayerExist(_referrer) && _referrer != msg.sender) { _processPayments(game.bet, winner, _referrer); } else { _processPayments(game.bet, winner, address(0)); } _jackpotPayoutProcessing(_gameId); _recordStatisticInfo(game.host, game.join, game.bet); } /** * @dev If during the time specified in revealTimer one of the players does not send * the secret and salt to the opponent, the player can open a dispute. * @param _gameId 32 byte game identifier * @param _secret Secret of the player, who opens the dispute. * @param _salt Salt of the player, who opens the dispute. * @param _isHost True if the sending account initiated the game. * @param _hashOfOpponentSecret The hash value of the opponent account's secret and salt. */ function openDispute( bytes32 _gameId, uint8 _secret, bytes32 _salt, bool _isHost, bytes32 _hashOfOpponentSecret ) public onlyParticipant(_gameId) { require(timeUntilOpenDispute(_gameId) == 0, "the waiting time for revealing is not over yet"); Game storage game = games[_gameId]; require(isSecretDataValid( _gameId, _secret, _salt, _isHost, _hashOfOpponentSecret ), "invalid salt or secret"); _recordDisputeInfo(_gameId, msg.sender, _hashOfOpponentSecret, _secret, _salt, _isHost); game.state = _isHost ? GameState.DisputeOpenedByHost : GameState.DisputeOpenedByJoin; address defendant = _isHost ? game.join : game.host; players[msg.sender].totalOpenedDisputes = (players[msg.sender].totalOpenedDisputes).add(1); players[defendant].totalUnrevealedGames = (players[defendant].totalUnrevealedGames).add(1); emit DisputeOpened(_gameId, msg.sender, defendant); } /** * @dev Allows the accused player to make a secret disclosure * and pick up the winnings in case of victory. * @param _gameId 32 byte game identifier. * @param _secret An accused player's secret. * @param _salt An accused player's salt. * @param _isHost True if the sending account initiated the game. * @param _hashOfOpponentSecret The hash value of the opponent account's secret and salt. */ function resolveDispute( bytes32 _gameId, uint8 _secret, bytes32 _salt, bool _isHost, bytes32 _hashOfOpponentSecret ) public returns(address payable winner) { require(isDisputeOpened(_gameId), "there is no dispute"); Game storage game = games[_gameId]; Dispute memory dispute = disputes[_gameId]; require(msg.sender != dispute.disputeOpener, "only for the opponent"); require(isSecretDataValid( _gameId, _secret, _salt, _isHost, _hashOfOpponentSecret ), "invalid salt or secret"); if (_secret == dispute.secret) { winner = game.join; game.state = GameState.WonByJoin; } else { winner = game.host; game.state = GameState.WonByHost; } _processPayments(game.bet, winner, address(0)); _jackpotPayoutProcessing(_gameId); _recordStatisticInfo(game.host, game.join, game.bet); emit DisputeResolved(_gameId, msg.sender); } /** * @dev If during the time specified in disputeTimer the accused player does not manage to resolve a dispute * the player, who has opened the dispute, can close the dispute and get the win. * @param _gameId 32 byte game identifier. * @return address of the winning player. */ function closeDisputeOnTimeout(bytes32 _gameId) public returns (address payable winner) { Game storage game = games[_gameId]; Dispute memory dispute = disputes[_gameId]; require(timeUntilCloseDispute(_gameId) == 0, "the time has not yet come out"); winner = dispute.disputeOpener; game.state = (winner == game.host) ? GameState.DisputeWonOnTimeoutByHost : GameState.DisputeWonOnTimeoutByJoin; _processPayments(game.bet, winner, address(0)); _jackpotPayoutProcessing(_gameId); _recordStatisticInfo(game.host, game.join, game.bet); emit DisputeClosedOnTimeout(_gameId, msg.sender); } /** * @dev If one of the player made a bet and during the time specified in waitingBetTimer * the opponent does not make a bet too, the player can take his bet back. * @param _gameId 32 byte game identifier. */ function cancelGame( bytes32 _gameId ) public onlyParticipant(_gameId) { require(timeUntilCancel(_gameId) == 0, "the waiting time for the second player's bet is not over yet"); Game storage game = games[_gameId]; address payable recipient; recipient = game.state == GameState.HostBetted ? game.host : game.join; address defendant = game.state == GameState.HostBetted ? game.join : game.host; game.state = (recipient == game.host) ? GameState.CanceledByHost : GameState.CanceledByJoin; recipient.transfer(game.bet); players[defendant].totalNotFundedGames = (players[defendant].totalNotFundedGames).add(1); emit GameCanceled(_gameId, msg.sender, defendant); } /** * @dev Jackpot draw if the time has come and there is a winner. */ function drawJackpot() public { require(isJackpotAvailable(), "is not avaliable yet"); require(jackpotGameId != 0, "no game to claim on the jackpot"); require(jackpotValue != 0, "jackpot's empty"); _payoutJackpot(); } /** * @return true if there is open dispute for given `_gameId` */ function isDisputeOpened(bytes32 _gameId) public view returns(bool) { return ( games[_gameId].state == GameState.DisputeOpenedByHost || games[_gameId].state == GameState.DisputeOpenedByJoin ); } /** * @return true if a player played at least one game and did not Cancel it. */ function isPlayerExist(address _player) public view returns (bool) { return players[_player].totalGames != 0; } /** * @return the time after which a player can close the game. * @param _gameId 32 byte game identifier. */ function timeUntilCancel( bytes32 _gameId ) public view isOpen(_gameId) returns (uint256 remainingTime) { uint256 timePassed = getTime().sub(games[_gameId].creationTime); if (waitingBetTimer > timePassed) { return waitingBetTimer.sub(timePassed); } else { return 0; } } /** * @return the time after which a player can open the dispute. * @param _gameId 32 byte game identifier. */ function timeUntilOpenDispute( bytes32 _gameId ) public view isFilled(_gameId) returns (uint256 remainingTime) { uint256 timePassed = getTime().sub(games[_gameId].creationTime); if (revealTimer > timePassed) { return revealTimer.sub(timePassed); } else { return 0; } } /** * @return the time after which a player can close the dispute opened by him. * @param _gameId 32 byte game identifier. */ function timeUntilCloseDispute( bytes32 _gameId ) public view returns (uint256 remainingTime) { require(isDisputeOpened(_gameId), "there is no open dispute"); uint256 timePassed = getTime().sub(disputes[_gameId].creationTime); if (disputeTimer > timePassed) { return disputeTimer.sub(timePassed); } else { return 0; } } /** * @return the current time in UNIX timestamp format. */ function getTime() public view returns(uint) { return block.timestamp; } /** * @return the current game state. * @param _gameId 32 byte game identifier */ function getGameState(bytes32 _gameId) public view returns(GameState) { return games[_gameId].state; } /** * @return true if the sent secret and salt match the genuine ones. * @param _gameId 32 byte game identifier. * @param _secret A player's secret. * @param _salt A player's salt. * @param _isHost True if the sending account initiated the game. * @param _hashOfOpponentSecret The hash value of the opponent account's secret and salt. */ function isSecretDataValid( bytes32 _gameId, uint8 _secret, bytes32 _salt, bool _isHost, bytes32 _hashOfOpponentSecret ) public view returns (bool) { Game memory game = games[_gameId]; bytes32 hashOfPlayerSecret = _hashOfSecret(_salt, _secret); address player = _getSignerAddress( game.bet, _isHost, _isHost ? game.join : game.host, hashOfPlayerSecret, _hashOfOpponentSecret, _isHost ? game.hostSignature : game.joinSignature ); require(msg.sender == player, "the received address does not match with msg.sender"); if (_isHost) { return player == game.host; } else { return player == game.join; } } /** * @return true if the jackpotDrawTime has come. */ function isJackpotAvailable() public view returns (bool) { return getTime() >= jackpotDrawTime; } function isGameAllowedForJackpot(bytes32 _gameId) public view returns (bool) { return getTime() - games[_gameId].creationTime < gameDurationForJackpot; } /** * @return an array of statuses for the listed games. * @param _games array of games identifier. */ function getGamesStates(bytes32[] memory _games) public view returns(GameState[] memory) { GameState[] memory _states = new GameState[](_games.length); for (uint i=0; i<_games.length; i++) { Game storage game = games[_games[i]]; _states[i] = game.state; } return _states; } /** * @return an array of Statistics for the listed players. * @param _players array of players' addresses. */ function getPlayersStatistic(address[] memory _players) public view returns(uint[] memory) { uint[] memory _statistics = new uint[](_players.length * 5); for (uint i=0; i<_players.length; i++) { Statistics storage player = players[_players[i]]; _statistics[5*i + 0] = player.totalGames; _statistics[5*i + 1] = player.totalUnrevealedGames; _statistics[5*i + 2] = player.totalNotFundedGames; _statistics[5*i + 3] = player.totalOpenedDisputes; _statistics[5*i + 4] = player.avgBetAmount; } return _statistics; } /** * @return GameId generated for current values of the signatures. * @param _signatureHost Signature of the initiating player. * @param _signatureJoin Signature of the joining player. */ function getGameId(bytes memory _signatureHost, bytes memory _signatureJoin) public pure returns (bytes32) { return keccak256(abi.encodePacked(_signatureHost, _signatureJoin)); } /** * @dev jackpot draw. */ function _payoutJackpot() internal { Game storage jackpotGame = games[jackpotGameId]; uint256 reward = jackpotValue.div(2); jackpotValue = 0; jackpotGameId = 0; jackpotDrawTime = (getTime()).add(jackpotAccumulationTimer); if (jackpotGame.host.send(reward)) { emit JackpotReward(jackpotGame.gameId, jackpotGame.host, reward.mul(2)); } if (jackpotGame.join.send(reward)) { emit JackpotReward(jackpotGame.gameId, jackpotGame.join, reward.mul(2)); } } /** * @dev adds the completed game to the jackpot draw. * @param _gameId 32 byte game identifier. */ function _addGameToJackpot(bytes32 _gameId) internal { jackpotDrawTime = jackpotDrawTime.add(jackpotGameTimerAddition); jackpotGameId = _gameId; emit CurrentJackpotGame(_gameId); } /** * @dev update jackpot info. * @param _gameId 32 byte game identifier. */ function _jackpotPayoutProcessing(bytes32 _gameId) internal { if (isJackpotAvailable()) { if (jackpotGameId != 0 && jackpotValue != 0) { _payoutJackpot(); } else { jackpotDrawTime = (getTime()).add(jackpotAccumulationTimer); } } if (isGameAllowedForJackpot(_gameId)) { _addGameToJackpot(_gameId); } } /** * @dev take a commission to the creators, reward to referrer, and commission for the jackpot from the winning amount. * Sending prize to winner. * @param _bet bet in the current game. * @param _winner the winner's address. * @param _referrer the referrer's address. */ function _processPayments(uint256 _bet, address payable _winner, address payable _referrer) internal { uint256 doubleBet = (_bet).mul(2); uint256 commission = (doubleBet.mul(commissionPercent)).div(100); uint256 jackpotPart = (doubleBet.mul(jackpotPercent)).div(100); uint256 winnerStake; if (_referrer != address(0) && referralPercent != 0 ) { uint256 referrerPart = (doubleBet.mul(referralPercent)).div(1000); winnerStake = doubleBet.sub(commission).sub(jackpotPart).sub(referrerPart); if (_referrer.send(referrerPart)) { emit ReferredReward(_referrer, referrerPart); } } else { winnerStake = doubleBet.sub(commission).sub(jackpotPart); } jackpotValue = jackpotValue.add(jackpotPart); _winner.transfer(winnerStake); teamWallet.transfer(commission); emit WinnerReward(_winner, winnerStake); } /** * @dev filling in the "Game" structure. */ function _recordGameInfo( uint256 _value, bool _isHost, bytes32 _gameId, address _opponent, bytes memory _hostSignature, bytes memory _joinSignature ) internal { Game memory _game = Game({ bet: _value, host: _isHost ? msg.sender : address(uint160(_opponent)), join: _isHost ? address(uint160(_opponent)) : msg.sender, creationTime: getTime(), state: _isHost ? GameState.HostBetted : GameState.JoinBetted , gameId: _gameId, hostSignature: _hostSignature, joinSignature: _joinSignature }); games[_gameId] = _game; } /** * @dev filling in the "Dispute" structure. */ function _recordDisputeInfo( bytes32 _gameId, address payable _disputeOpener, bytes32 _hashOfOpponentSecret, uint8 _secret, bytes32 _salt, bool _isHost ) internal { Dispute memory _dispute = Dispute({ disputeOpener: _disputeOpener, creationTime: getTime(), opponentHash: _hashOfOpponentSecret, secret: _secret, salt: _salt, isHost: _isHost }); disputes[_gameId] = _dispute; } /** * @dev filling in the "Statistics" structure. */ function _recordStatisticInfo(address _host, address _join, uint256 _bet) internal { Statistics storage statHost = players[_host]; Statistics storage statJoin = players[_join]; statHost.avgBetAmount = _calculateAvgBet(_host, _bet); statJoin.avgBetAmount = _calculateAvgBet(_join, _bet); statHost.totalGames = (statHost.totalGames).add(1); statJoin.totalGames = (statJoin.totalGames).add(1); } /** * @dev recalculation of an average bet value for a player. * @param _player the address of the player. * @param _bet bet from the last played game. */ function _calculateAvgBet(address _player, uint256 _bet) internal view returns (uint256 newAvgBetValue){ Statistics storage statistics = players[_player]; uint256 totalBets = (statistics.avgBetAmount).mul(statistics.totalGames).add(_bet); newAvgBetValue = totalBets.div(statistics.totalGames.add(1)); } }
If during the time specified in revealTimer one of the players does not send the secret and salt to the opponent, the player can open a dispute. _gameId 32 byte game identifier _secret Secret of the player, who opens the dispute. _salt Salt of the player, who opens the dispute. _isHost True if the sending account initiated the game. _hashOfOpponentSecret The hash value of the opponent account's secret and salt./
function openDispute( bytes32 _gameId, uint8 _secret, bytes32 _salt, bool _isHost, bytes32 _hashOfOpponentSecret ) public onlyParticipant(_gameId) { require(timeUntilOpenDispute(_gameId) == 0, "the waiting time for revealing is not over yet"); Game storage game = games[_gameId]; require(isSecretDataValid( _gameId, _secret, _salt, _isHost, _hashOfOpponentSecret ), "invalid salt or secret"); _recordDisputeInfo(_gameId, msg.sender, _hashOfOpponentSecret, _secret, _salt, _isHost); game.state = _isHost ? GameState.DisputeOpenedByHost : GameState.DisputeOpenedByJoin; address defendant = _isHost ? game.join : game.host; players[msg.sender].totalOpenedDisputes = (players[msg.sender].totalOpenedDisputes).add(1); players[defendant].totalUnrevealedGames = (players[defendant].totalUnrevealedGames).add(1); emit DisputeOpened(_gameId, msg.sender, defendant); }
13,000,745
./full_match/4/0x56AcaA025dBDEc3F776A75001724f2712200ef64/sources/browser/LiquidityTransformer.sol
checks for investors count on each day return _allInvestors array with investors count for each day/
function investorsOnAllDays() external view returns (uint256[31] memory _allInvestors) { for (uint256 i = 1; i <= INVESTMENT_DAYS; i++) { _allInvestors[i] = investorsOnDay(i); } }
747,148
pragma solidity 0.8.6; import "ERC721.sol"; import "Ownable.sol"; import "ReentrancyGuard.sol"; import "Strings.sol"; import "Base64.sol"; /** ////////////////// \\\ /// ///////////\\\ /// \\\ ////////////// ////////////\\\ ///////////////// \\\ /// /////////////\\\ /// /// ///////////// /////////////\\\ /// /// \\\ /// /// /// /// /// /// /// /// /// /// \\\ /// /// /// /// /// /// /// /// /// /// \\\ /// /// /// /// /// /// /// /// /// \\\ /// /// /// /// /// /// /// /// /// \\v/// //////////// //////////////// ////////////// //////////// /// \/// /////////// //////////////// ///////////// /////////// /// \\\ /// /// /// /// /// /// \\\ /// \\\ /// /// /// /// /// /// \\\ /// \\\ /// /// /// /// /// /// /// \\\ ///\\\\\\\\\\\\\\\ /// /// /// /// ////////////// /// \\\ ///\\\\\\\\\\\\\\\\ /// /// /// /// ///////////// /// \\\ "Personal worth is not what a person is worth I can give a dollar to every person on Earth" - Kanye West, DONDA, Pure Souls "So nerdy but the flow wordy Brain-freezin' with the flow slurpie" - Childish Gambino, Sway in the Morning, Freestyle "Don't get offended by this, but that's the market y'all missed That's the target I'll hit and that's the heart of my pitch I wanna do this whole thing different" - Lil Dicky, Professional Rapper, Professional Rapper CYPHER ON-CHAIN 2021 **/ contract Cypher is ERC721, ReentrancyGuard, Ownable { uint256 public totalSupply; // Track, album, bars length uint256 public constant trackLength = 20; uint256 public constant albumLength = 10; uint256 public constant maxSupply = trackLength*albumLength; uint256 private constant barsPerBlock = 4; uint256 private immutable maxCharactersPerBar = 40; uint256 private immutable minCharactersPerBar = 10; // Time related constaints uint256 public blockStartTime; uint256 public albumStartTime; uint256 public blockInterval = 5*60; uint256 public trackInterval = 1 days + 300; // Storage of bars and writers mapping(uint256 => string) public tokenIdToBars; mapping(uint256 => address) public tokenIdToWriter; constructor() public ERC721("Cypher on-chain: EP", "BARS") Ownable() { } /******************/ /* MINT LOGIC */ /******************/ function mint(string memory user_bars) payable external nonReentrant { require(totalSupply < maxSupply, 'Cypher: all blocks minted'); require(msg.value == 0.01 ether, "Cypher: 0.01 ETH to mint"); require(balanceOf(msg.sender) <= 2, "Cypher: max 3 per wallet"); require(block.timestamp >= blockStartTime + blockInterval, "Cypher: next block not yet available"); require(block.timestamp >= (albumStartTime + (totalSupply / trackLength * trackInterval)), 'Cypher: next track not yet available.'); if(totalSupply == 0){ require(msg.sender == owner(), "Cypher: only the owner can mint the first block in the first track."); albumStartTime = block.timestamp; } else { require(tokenIdToWriter[totalSupply] != msg.sender, "Cypher: same wallet can't mint twice in a row"); } _cypherValidations(user_bars); _mint(msg.sender, ++totalSupply); tokenIdToBars[totalSupply] = user_bars; tokenIdToWriter[totalSupply] = msg.sender; blockStartTime = block.timestamp; } function _cypherValidations(string memory user_bars) internal view { bytes memory _bytes = abi.encodePacked(bytes(user_bars), '\n'); uint256 barCount; uint256 lastBarStart; uint256 lastLastBarStart; uint256 lastBarEnd; bool isSpaceOrNewline = false; bool prevPrevIsSpaceOrNewLine = true; bool prevIsSpaceOrNewline = true; bool prevIsComma = false; bytes1 char; uint8 charInt; // To save gas, all validation happens in the same for loop for (uint256 i = 0; i < _bytes.length; i++){ char = _bytes[i]; charInt = uint8(char); isSpaceOrNewline = (charInt == 32 || charInt == 10); // Validation: No special characters if (! (isSpaceOrNewline || charInt == 44 || (charInt >= 97 && charInt <= 122) || (charInt >= 65 && charInt <= 90)) ) { require(false, "Cypher: invalid characters"); } // Validation: No adjacent empty characters if((isSpaceOrNewline) && (prevIsSpaceOrNewline)){ require(false, "Cypher: adjacent empty chars"); } if(prevIsComma && !(charInt == 32 && !prevPrevIsSpaceOrNewLine)){ require(false, "Cypher: comma must be followed by a space and preceded by letters"); } prevIsComma = charInt == 44; // Reached new bar: Check per-bar validations if (charInt == 10) { if (barCount == 0 && totalSupply % trackLength != 0) { require(_rhymeCheckAcrossTokens(totalSupply, _bytes, 0, i-1), "Cypher: first bar must rhyme with prior block's last bar"); } if(barCount == 1 || barCount == 3){ require(strictRhymes(_bytes, lastLastBarStart, lastBarEnd-1, _bytes, lastBarStart, i-1), "Cypher: first two bars and last two bars must rhyme"); } barCount = barCount + 1; require(i - lastBarStart >= minCharactersPerBar, "Cypher: need >= 10 characters in each bar"); require(i - lastBarStart <= maxCharactersPerBar, "Cypher: need <= 40 characters in each bar"); lastLastBarStart = lastBarStart; lastBarEnd = i; lastBarStart = i+1; } prevPrevIsSpaceOrNewLine = prevIsSpaceOrNewline; prevIsSpaceOrNewline = isSpaceOrNewline; } require(barCount == barsPerBlock, "Cypher: there must be four bars in a block"); } function setBlockInterval(uint256 newInterval) external onlyOwner { blockInterval = newInterval; } function setTrackInterval(uint256 newInterval) external onlyOwner { trackInterval = newInterval; } function withdrawAll() public payable onlyOwner { require(payable(_msgSender()).send(address(this).balance)); } function _isVowel(bytes1 char) internal view virtual returns (bool) { return (uint8(char) == 97 || uint8(char) == 101 || uint8(char) == 105 || uint8(char) == 111 || uint8(char) == 117 || uint8(char) == 121 || uint8(char) == 65 || uint8(char) == 69 || uint8(char) == 73 || uint8(char) == 79 || uint8(char) == 85 || uint8(char) == 89); } function lower(bytes1 char) internal view virtual returns (bytes1){ if(uint8(char) >= 65 && uint8(char) <= 90) { return bytes1(uint8(char) + 32); } else { return char; } } function _rhymeCheckAcrossTokens(uint256 tokenId, bytes memory user_bars, uint256 start, uint256 end) internal view virtual returns (bool) { string memory prevBarsString = tokenIdToBars[tokenId]; bytes memory prev_bars = bytes(prevBarsString); uint256 index = prev_bars.length-1; while(index >= 0){ if(prev_bars[index] == '\n'){ break; } index -= 1; } return strictRhymes(prev_bars, index+1, prev_bars.length-1, user_bars, start, end); } function strictRhymes(bytes memory s1, uint256 s1Start, uint256 s1End, bytes memory s2, uint256 s2Start, uint256 s2End) internal view returns (bool) { uint256 s1Ind = s1End; uint256 s2Ind = s2End; bool vowelSeen = false; uint256 consecutive = 0; uint256 checked = 0; uint256 vowelCt = 10000; bool consec = true; while(s1Ind >= s1Start && s2Ind >= s2Start){ bytes1 s1Char = s1[s1Ind]; bytes1 s2Char = s2[s2Ind]; if(uint8(s1Char) == 32 || uint8(s2Char) == 32){ break; } if(!vowelSeen || vowelSeen && checked < 2) { if(lower(s1Char) == lower(s2Char) && consec){ consecutive += 1; } else { consec = false; } } vowelSeen = vowelSeen || _isVowel(s1Char) || _isVowel(s2Char); if(vowelSeen && vowelCt == 10000){ vowelCt = checked; } checked += 1; if(s1Ind == s1Start || s2Ind == s2Start){ break; } s1Ind -=1; s2Ind -=1; } if(!vowelSeen || vowelCt == 0){ return consecutive >= 2 || consecutive >= checked; } else { return consecutive > vowelCt || consecutive >= checked; } } /*************/ /* TOKEN URI */ /*************/ function tokenURI(uint256 tokenId) public override view returns(string memory) { string memory lyric = tokenIdToBars[tokenId]; string[barsPerBlock] memory bars = splitOnChar(lyric, '\n'); address writer = tokenIdToWriter[tokenId]; string memory writerAscii = toAsciiString(writer); uint256 colorScheme = trackColor(tokenId); bytes memory tokenName; bytes memory jsonEscapedBars; for(uint256 i = 0; i < barsPerBlock; i++){ tokenName = abi.encodePacked(tokenName, substring(bytes(bars[i]), 0, firstCharIndex(bars[i], ' ')), ' '); jsonEscapedBars = abi.encodePacked(jsonEscapedBars, bars[i], i != barsPerBlock - 1 ? '\\n' : ''); } bytes memory jsonSvg = abi.encodePacked( '{"name":"', '#', Strings.toString(tokenId), ' - ', string(tokenName), '", "description":"Cypher on-chain is a smart contract that conducts a rap cypher on Ethereum. Cypher EP is its first collectively written album with 10 tracks. Each track contains 20 blocks, comprised of 4 bars each. A block is an NFT.", ', '"bars": "', jsonEscapedBars, '", ' ); jsonSvg = abi.encodePacked(jsonSvg, '"attributes": [{', '"trait_type": "Track", "value":"', Strings.toString(trackNumber(tokenId)), '"}, {', '"trait_type": "Block", "value":"', Strings.toString(trackBlockNumber(tokenId)), '"}', ',{', '"trait_type": "Writer", "value":"0x', writerAscii, '"}', ']', ', "image": "' 'data:image/svg+xml;base64,', Base64.encode(svgImage(tokenId, bars, colorScheme, writer, bytes(writerAscii))), '"}' ); return string( abi.encodePacked( 'data:application/json;base64,', Base64.encode( jsonSvg ) ) ); } function svgImage(uint256 tokenId, string[barsPerBlock] memory bars, uint256 colorScheme, address writer, bytes memory writerAscii) internal view returns (bytes memory){ bytes memory writerAddr = abi.encodePacked(tokenIdToWriter[tokenId]); return abi.encodePacked( '<svg version="1.1" shape-rendering="optimizeSpeed" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"', ' x="0px" y="0px" width="300" height="300" viewBox="0 0 10 10" xml:space="preserve">', styles(), svgGrid(colorScheme, writer), svgText(colorScheme, writer, bars), abi.encodePacked('<text x="0" y="1" fill="', string(abi.encodePacked('hsl(', Strings.toString(colorScheme),',95%,40%)')), '">Track: ', Strings.toString(trackNumber(tokenId)), ' - Block: ', Strings.toString(trackBlockNumber(tokenId)), '</text>'), '</svg>' ); } function styles() internal view returns (string memory) { bytes memory styles = abi.encodePacked('<style type="text/css">', 'rect{width: 1px; height: 1px;}text{font-size: 0.42px; alignment-baseline:text-after-edge}', '.c1{fill:#000000;}.writerText{font-size: 0.25px;}</style>'); return string(styles); } function trackColor(uint256 tokenId) public view returns (uint256){ uint16[10] memory colorSchemes = [180, 160, 36, 72, 96, 0, 206, 270, 288, 312]; uint256 h = trackNumber(tokenId) - 1; return colorSchemes[h]; } function trackNumber(uint256 tokenId) public view returns (uint256){ return (tokenId-1)/(trackLength) + 1; } function trackBlockNumber(uint256 tokenId) public view returns (uint256){ return ((tokenId-1) % trackLength) + 1; } function svgText(uint256 colorScheme, address writer, string[barsPerBlock] memory bars) internal view returns (string memory) { bytes memory lyricSvgs; for (uint256 i = 0; i < barsPerBlock; i++){ lyricSvgs = abi.encodePacked(lyricSvgs, '<text x="0" y="', Strings.toString(i+1+1), '" fill="white">', bytes(bars[i]), '</text>'); } lyricSvgs = abi.encodePacked(lyricSvgs, '<text x="0" y="6" fill="', string(abi.encodePacked('hsl(', Strings.toString(colorScheme),',95%,40%)')), '" class="writerText">0x', toAsciiString(writer), '</text>'); return string(lyricSvgs); } function svgGrid(uint256 colorScheme, address writer) internal view returns (string memory) { bytes memory rectString; rectString = abi.encodePacked( svgLyricCanvasRow(0), svgLyricCanvasRow(1), svgLyricCanvasRow(2), svgLyricCanvasRow(3), svgLyricCanvasRow(4), svgLyricCanvasRow(5) ); for(uint256 i=0; i < barsPerBlock; i++){ rectString = abi.encodePacked(rectString, svgSignatureRow(abi.encodePacked(writer), 6+i, colorScheme)); } return string(rectString); } function svgSignatureRow(bytes memory writer, uint256 rowIdx, uint256 colorScheme) internal view returns (string memory) { bytes memory rectString; uint256 addrInd = 0; uint256 stepSize = 2; // parts of color band that have less variance nearby if(colorScheme == 206 || colorScheme == 312 || colorScheme == 270 || colorScheme == 0 || colorScheme == 144){ stepSize = 3; } else if (colorScheme == 72 || colorScheme == 96) { stepSize = 5; } else { } for(uint256 i=0; i<10; i++){ if (writer.length != 0){ uint256 addrOffset = rowIdx >= 6 ? (rowIdx-6)*(10/5) : 0; uint256 walletInt; if (i % 2 == 0){ walletInt = uint(uint8(writer[addrInd + addrOffset] >> 4)); } else { walletInt = uint(uint8(writer[addrInd + addrOffset] & 0x0f)); addrInd += 1; } rectString = abi.encodePacked(rectString, '<rect x="', Strings.toString(i), '" y="', Strings.toString(rowIdx), '" fill="',string(abi.encodePacked('hsl(', Strings.toString(colorScheme + walletInt*stepSize),',95%,40%)')) ,'"></rect>'); } } return string(rectString); } function svgLyricCanvasRow(uint256 rowIdx) internal view returns (string memory) { bytes memory rectString; for(uint256 i=0; i<10; i++){ rectString = abi.encodePacked(rectString, '<rect x="', Strings.toString(i), '" y="', Strings.toString(rowIdx), '" class="c1 s"/>'); } return string(rectString); } function firstCharIndex (string memory base, bytes1 char) internal view virtual returns (uint) { bytes memory _bytes = bytes(base); uint256 i = 0; while (i < _bytes.length){ if (_bytes[i] == char) { return i; } i += 1; } return 0; } function splitOnChar(string memory lyric, bytes1 char) internal view returns (string[barsPerBlock] memory bars) { bytes memory b_lyrics = bytes(lyric); uint256 splits = 0; uint256 start_index = 0; for(uint256 i = 0; i < b_lyrics.length; i++){ if (b_lyrics[i] == char) { bars[splits] = string(substring(b_lyrics, start_index, i)); splits += 1; start_index = i+1; } } bars[barsPerBlock-1] = string(substring(b_lyrics, start_index, b_lyrics.length)); return bars; } function substring(bytes memory in_string, uint256 start_index, uint256 end_index) internal view virtual returns (bytes memory) { bytes memory new_str = new bytes(end_index-start_index); for(uint256 i = 0; i < end_index-start_index; i++) { new_str[i] = in_string[start_index+i]; } return new_str; } function toAsciiString(address x) internal view returns (string memory) { bytes memory s = new bytes(40); for (uint256 i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2*i] = addressChar(hi); s[2*i+1] = addressChar(lo); } return string(s); } function addressChar(bytes1 b) internal view returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC721.sol"; import "IERC721Receiver.sol"; import "IERC721Metadata.sol"; import "Address.sol"; import "Context.sol"; import "Strings.sol"; import "ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // 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 "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; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "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 /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides a function for encoding some bytes in base64 pragma solidity ^0.8.0; library Base64 { string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F))))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } }
/ MINT LOGIC //
function mint(string memory user_bars) payable external nonReentrant { require(totalSupply < maxSupply, 'Cypher: all blocks minted'); require(msg.value == 0.01 ether, "Cypher: 0.01 ETH to mint"); require(balanceOf(msg.sender) <= 2, "Cypher: max 3 per wallet"); require(block.timestamp >= blockStartTime + blockInterval, "Cypher: next block not yet available"); require(block.timestamp >= (albumStartTime + (totalSupply / trackLength * trackInterval)), 'Cypher: next track not yet available.'); if(totalSupply == 0){ require(msg.sender == owner(), "Cypher: only the owner can mint the first block in the first track."); albumStartTime = block.timestamp; require(tokenIdToWriter[totalSupply] != msg.sender, "Cypher: same wallet can't mint twice in a row"); } _cypherValidations(user_bars); _mint(msg.sender, ++totalSupply); tokenIdToBars[totalSupply] = user_bars; tokenIdToWriter[totalSupply] = msg.sender; blockStartTime = block.timestamp; }
6,069,355
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @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 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 Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // 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); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(burner, _value); emit Transfer(burner, address(0), _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 Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract TestTokenA is BurnableToken, MintableToken { string public constant name = "TestTokenA"; string public constant symbol = "TTA"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 65000000 * (10 ** uint256(decimals)); // number of tokens in reserve /** * @dev Constructor that gives msg.sender all of existing tokens. */ function TestTokenA() public{ totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(now >= openingTime && now <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public { require(_openingTime >= now); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { return now > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @param _wallet Vault address */ function RefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } /** * @param investor Investor address */ function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; emit Closed(); wallet.transfer(address(this).balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @param investor Investor address */ function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); } } /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale's vault. */ contract CappedRefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // maximum amount of funds to be raised in weis uint256 public cap; // refund vault used to hold funds while crowdsale is running RefundVault public vault; /** * @dev Constructor, creates RefundVault. * @param _goal Funding goal */ function CappedRefundableCrowdsale(uint256 _goal, uint256 _cap) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; require(_cap > 0); cap = _cap; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } /** * @dev vault finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } contract TestTokenAPreICO is CappedRefundableCrowdsale { function TestTokenAPreICO ( TestTokenA _token, uint256 _rate, address _wallet, uint256 _cap, uint256 _openingTime, uint256 _closingTime, uint256 _goal ) public Crowdsale(_rate, _wallet, _token) TimedCrowdsale(_openingTime, _closingTime) CappedRefundableCrowdsale(_goal, _cap) { } /* function createTokenContract() internal returns (MintableToken) { return new TestTokenA(); } */ // function createTokenContract(address _tokenAddress) internal returns (MintableToken) { // return TestTokenA(_tokenAddress); // } }
Constructor that gives msg.sender all of existing tokens./
function TestTokenA() public{ totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); }
1,610,239
pragma solidity 0.4.25; /** * Utility library of inline functions on addresses */ library Address { /** * 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 account address of the account to check * @return whether the target address is a contract */ function isContract(address account) 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(account) } return size > 0; } } pragma solidity 0.4.25; import "./IERC165.sol"; /** * @title ERC165 * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract ERC165 is IERC165 { bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor () internal { _registerInterface(_InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } pragma solidity 0.4.25; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./SafeMath.sol"; import "./Address.sol"; import "./ERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { require(_isApprovedOrOwner(msg.sender, tokenId)); require(to != address(0)); _clearApproval(from, tokenId); _removeTokenFrom(from, tokenId); _addTokenTo(to, tokenId); emit Transfer(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { require(to != address(0)); _addTokenTo(to, tokenId); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { _clearApproval(owner, tokenId); _removeTokenFrom(owner, tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to add a token ID to the list of a given address * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event. * @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 _addTokenTo(address to, uint256 tokenId) internal { require(_tokenOwner[tokenId] == address(0)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event, * and doesn't clear approvals. * @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 _removeTokenFrom(address from, uint256 tokenId) internal { require(ownerOf(tokenId) == from); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _tokenOwner[tokenId] = address(0); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param owner owner of the token * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(address owner, uint256 tokenId) private { require(ownerOf(tokenId) == owner); if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } pragma solidity 0.4.25; import "./IERC721Enumerable.sol"; import "./ERC721.sol"; import "./ERC165.sol"; /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => 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; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ /** * @dev Constructor function */ constructor () public { // register the supported interface to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721Enumerable); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner)); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply()); return _allTokens[index]; } /** * @dev Internal function to add a token ID to the list of a given address * This function is internal due to language limitations, see the note in ERC721.sol. * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event. * @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 _addTokenTo(address to, uint256 tokenId) internal { super._addTokenTo(to, tokenId); uint256 length = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); _ownedTokensIndex[tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * This function is internal due to language limitations, see the note in ERC721.sol. * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event, * and doesn't clear approvals. * @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 _removeTokenFrom(address from, uint256 tokenId) internal { super._removeTokenFrom(from, tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = _ownedTokensIndex[tokenId]; uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 lastToken = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastToken; // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list _ownedTokensIndex[tokenId] = 0; _ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Reorg all tokens array uint256 tokenIndex = _allTokensIndex[tokenId]; uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 lastToken = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastToken; _allTokens[lastTokenIndex] = 0; _allTokens.length--; _allTokensIndex[tokenId] = 0; _allTokensIndex[lastToken] = tokenIndex; } } pragma solidity 0.4.25; import "./ERC721.sol"; import "./IERC721Metadata.sol"; import "./ERC165.sol"; contract ERC721Metadata is ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId)); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId)); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } pragma solidity 0.4.25; /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ 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. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } pragma solidity 0.4.25; import "./IERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } pragma solidity 0.4.25; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721Enumerable is IERC721 { 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); } pragma solidity 0.4.25; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } pragma solidity 0.4.25; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } pragma solidity 0.4.25; /// @title IOracle /// @dev Interface for getting the data from the oracle contract. interface IOracle { function ethUsdPrice() external view returns(uint256); } pragma solidity 0.4.25; /// @title ISettings /// @dev Interface for getting the data from settings contract. interface ISettings { function oracleAddress() external view returns(address); function minDeposit() external view returns(uint256); function sysFee() external view returns(uint256); function userFee() external view returns(uint256); function ratio() external view returns(uint256); function globalTargetCollateralization() external view returns(uint256); function tmvAddress() external view returns(uint256); function maxStability() external view returns(uint256); function minStability() external view returns(uint256); function gasPriceLimit() external view returns(uint256); function isFeeManager(address account) external view returns (bool); function tBoxManager() external view returns(address); } pragma solidity 0.4.25; /// @title IToken /// @dev Interface for interaction with the TMV token contract. interface IToken { function burnLogic(address from, uint256 value) external; function approve(address spender, uint256 value) external; function balanceOf(address who) external view returns (uint256); function mint(address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 tokenId) external; } pragma solidity 0.4.25; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'mul'); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, 'div'); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, 'sub'); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'add'); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } pragma solidity 0.4.25; import "./TBoxToken.sol"; import "./ISettings.sol"; import "./IToken.sol"; import "./IOracle.sol"; /// @title TBoxManager contract TBoxManager is TBoxToken { // Total packed Ether uint256 public globalETH; // Precision using for USD and commission uint256 public precision = 100000; // The address of the system settings contract ISettings public settings; /// @dev An array containing the Boxes struct for all Boxes in existence. The ID /// of each Box is actually an index into this array. Box[] public boxes; /// @dev The main Box struct. Every Box in TimviSystem is represented by a copy /// of this structure. struct Box { // The collateral Ether amount in wei uint256 collateral; // The number of TMV withdrawn uint256 tmvReleased; } /// @dev The Created event is fired whenever a new Box comes into existence. This includes /// any time a Box is created through the create method. event Created(uint256 indexed id, address owner, uint256 collateral, uint256 tmvReleased); /// @dev The Closed event is fired whenever a Box is closed. Obviously, this includes /// any time a Box is closed through the close method, but it is also called when // a Box is closed through the closeDust method. event Closed(uint256 indexed id, address indexed owner, address indexed closer); /// @dev The Capitalized event is fired whenever a Box is capitalized. event Capitalized(uint256 indexed id, address indexed owner, address indexed who, uint256 tmvAmount, uint256 totalEth, uint256 userEth); /// @dev The EthWithdrawn event is fired whenever Ether is withdrawn from a Box /// using withdrawEth method. event EthWithdrawn(uint256 indexed id, uint256 value, address who); /// @dev The TmvWithdrawn event is fired whenever TMV is withdrawn from a Box /// using withdrawTmv method. event TmvWithdrawn(uint256 indexed id, uint256 value, address who); /// @dev The EthAdded event is fired whenever Ether is added to a Box /// using addEth method. event EthAdded(uint256 indexed id, uint256 value, address who); /// @dev The TmvAdded event is fired whenever TMV is added to a Box /// using addTmv method. event TmvAdded(uint256 indexed id, uint256 value, address who); /// @dev Defends against front-running attacks. modifier validTx() { require(tx.gasprice <= settings.gasPriceLimit(), "Gas price is greater than allowed"); _; } /// @dev Throws if called by any account other than the owner. modifier onlyAdmin() { require(settings.isFeeManager(msg.sender), "You have no access"); _; } /// @dev Throws if Box with specified id does not exist. modifier onlyExists(uint256 _id) { require(_exists(_id), "Box does not exist"); _; } /// @dev Access modifier for token owner-only functionality. modifier onlyApprovedOrOwner(uint256 _id) { require(_isApprovedOrOwner(msg.sender, _id), "Box isn't your"); _; } /// @dev The constructor sets ERC721 token name and symbol. /// @param _settings The address of the system settings contract. constructor(address _settings) TBoxToken("TBoxToken", "TBX") public { settings = ISettings(_settings); } /// @notice The funds are safe. /// @dev Creates Box with max collateral percent. function() external payable { // Redirect to the create method with no tokens to withdraw create(0); } /// @dev Withdraws system fee. function withdrawFee(address _beneficiary) external onlyAdmin { require(_beneficiary != address(0), "Zero address, be careful"); // Fee is the difference between the contract balance and // amount of Ether used in the entire system collateralization uint256 _fees = address(this).balance.sub(globalETH); // Check that the fee is collected require(_fees > 0, "There is no available fees"); // Transfer fee to provided address _beneficiary.transfer(_fees); } /// @dev Checks possibility of the issue of the specified token amount /// for provided Ether collateral and creates new Box /// @param _tokensToWithdraw Number of tokens to withdraw /// @return New Box ID. function create(uint256 _tokensToWithdraw) public payable validTx returns (uint256) { // Check that msg.value isn't smaller than minimum deposit require(msg.value >= settings.minDeposit(), "Deposit is very small"); // Calculate collateralization when tokens are needed if (_tokensToWithdraw > 0) { // The number of tokens when collateralization is high uint256 _tokenLimit = overCapWithdrawableTmv(msg.value); // The number of tokens that can be safely withdrawn from the system uint256 _maxGlobal = globalWithdrawableTmv(msg.value); // Determine the higher number of tokens if (_tokenLimit > _maxGlobal) { _tokenLimit = _maxGlobal; } // The number of tokens that can be withdrawn anyway uint256 _local = defaultWithdrawableTmv(msg.value); // Determine the higher number of tokens if (_tokenLimit < _local) { _tokenLimit = _local; } // You can only withdraw available amount require(_tokensToWithdraw <= _tokenLimit, "Token amount is more than available"); // Mint TMV tokens to the Box creator IToken(settings.tmvAddress()).mint(msg.sender, _tokensToWithdraw); } // The id of the new Box uint256 _id = boxes.push(Box(msg.value, _tokensToWithdraw)).sub(1); // Increase global Ether counter globalETH = globalETH.add(msg.value); // Mint TBX token to the Box creator _mint(msg.sender, _id); // Fire the event emit Created(_id, msg.sender, msg.value, _tokensToWithdraw); // return the new Box's ID return _id; } /// @dev Allows the owner or approved user of the Box to close one by burning the /// required number of tokens and return the Box's collateral. /// @param _id A Box ID to close. function close(uint256 _id) external onlyApprovedOrOwner(_id) { // Address of the owner of the Box address _owner = _tokenOwner[_id]; // Burn needed number of tokens uint256 _tokensNeed = boxes[_id].tmvReleased; _burnTMV(msg.sender, _tokensNeed); // Grab a reference to the Box's collateral in storage uint256 _collateral = boxes[_id].collateral; // burn Box token _burn(_owner, _id); // Removes Box delete boxes[_id]; // Send the Box's collateral to the person who made closing happen msg.sender.transfer(_collateral); // Decrease global Ether counter globalETH = globalETH.sub(_collateral); // Fire the event emit Closed(_id, _owner, msg.sender); } /// @notice This allows you not to be tied to the current ETH/USD rate. /// @dev Allows the user to capitalize a Box with the maximum current amount. /// @param _id A Box ID to capitalize. function capitalizeMax(uint256 _id) external { capitalize(_id, maxCapAmount(_id)); } /// @dev Allows the user to capitalize a Box with specified number of tokens. /// @param _id A Box ID to capitalize. /// @param _tmv Specified number of tokens to capitalize. function capitalize(uint256 _id, uint256 _tmv) public validTx { // The maximum number of tokens for which Box can be capitalized uint256 _maxCapAmount = maxCapAmount(_id); // Check the number of tokens require(_tmv <= _maxCapAmount && _tmv >= 10 ** 17, "Tokens amount out of range"); // Decrease Box TMV withdrawn counter boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_tmv); // Calculate the Ether equivalent of tokens according to the logic // where 1 TMV is equal to 1 USD uint256 _equivalentETH = _tmv.mul(precision).div(rate()); // Calculate system fee uint256 _fee = _tmv.mul(settings.sysFee()).div(rate()); // Calculate user bonus uint256 _userReward = _tmv.mul(settings.userFee()).div(rate()); // Decrease Box's collateral amount boxes[_id].collateral = boxes[_id].collateral.sub(_fee.add(_userReward).add(_equivalentETH)); // Decrease global Ether counter globalETH = globalETH.sub(_fee.add(_userReward).add(_equivalentETH)); // burn Box token _burnTMV(msg.sender, _tmv); // Send the Ether equivalent & user benefit to the person who made capitalization happen. msg.sender.transfer(_equivalentETH.add(_userReward)); // Fire the event emit Capitalized(_id, ownerOf(_id), msg.sender, _tmv, _equivalentETH.add(_userReward).add(_fee), _equivalentETH.add(_userReward)); } /// @notice This allows you not to be tied to the current ETH/USD rate. /// @dev Allows an owner or approved user of the Box to withdraw maximum amount /// of Ether from the Box. /// @param _id A Box ID. function withdrawEthMax(uint256 _id) external { withdrawEth(_id, withdrawableEth(_id)); } /// @dev Allows an owner or approved user of the Box to withdraw specified amount /// of Ether from the Box. /// @param _id A Box ID. /// @param _amount The number of Ether to withdraw. function withdrawEth(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx { require(_amount > 0, "Withdrawing zero"); require(_amount <= withdrawableEth(_id), "You can't withdraw so much"); // Decrease Box's collateral amount boxes[_id].collateral = boxes[_id].collateral.sub(_amount); // Decrease global Ether counter globalETH = globalETH.sub(_amount); // Send the Ether to the person who made capitalization happen msg.sender.transfer(_amount); // Fire the event emit EthWithdrawn(_id, _amount, msg.sender); } /// @notice This allows you not to be tied to the current ETH/USD rate. /// @dev Allows an owner or approved user of the Box to withdraw maximum number /// of TMV tokens from the Box. /// @param _id A Box ID. function withdrawTmvMax(uint256 _id) external onlyApprovedOrOwner(_id) { withdrawTmv(_id, boxWithdrawableTmv(_id)); } /// @dev Allows an owner or approved user of the Box to withdraw specified number /// of TMV tokens from the Box. /// @param _id A Box ID. /// @param _amount The number of tokens to withdraw. function withdrawTmv(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx { require(_amount > 0, "Withdrawing zero"); // Check the number of tokens require(_amount <= boxWithdrawableTmv(_id), "You can't withdraw so much"); // Increase Box TMV withdrawn counter boxes[_id].tmvReleased = boxes[_id].tmvReleased.add(_amount); // Mints tokens to the person who made withdrawing IToken(settings.tmvAddress()).mint(msg.sender, _amount); // Fire the event emit TmvWithdrawn(_id, _amount, msg.sender); } /// @dev Allows anyone to add Ether to a Box. /// @param _id A Box ID. function addEth(uint256 _id) external payable onlyExists(_id) { require(msg.value > 0, "Don't add 0"); // Increase Box collateral boxes[_id].collateral = boxes[_id].collateral.add(msg.value); // Increase global Ether counter globalETH = globalETH.add(msg.value); // Fire the event emit EthAdded(_id, msg.value, msg.sender); } /// @dev Allows anyone to add TMV to a Box. /// @param _id A Box ID. /// @param _amount The number of tokens to add. function addTmv(uint256 _id, uint256 _amount) external onlyExists(_id) { require(_amount > 0, "Don't add 0"); // Check the number of tokens require(_amount <= boxes[_id].tmvReleased, "Too much tokens"); // Removes added tokens from the collateralization _burnTMV(msg.sender, _amount); boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_amount); // Fire the event emit TmvAdded(_id, _amount, msg.sender); } /// @dev Allows anyone to close Box with collateral amount smaller than 3 USD. /// The person who made closing happen will benefit like capitalization. /// @param _id A Box ID. function closeDust(uint256 _id) external onlyExists(_id) validTx { // Check collateral percent of the Box require(collateralPercent(_id) >= settings.minStability(), "This Box isn't collapsable"); // Check collateral amount of the Box require(boxes[_id].collateral.mul(rate()) < precision.mul(3).mul(10 ** 18), "It's only possible to collapse dust"); // Burn needed TMV amount to close uint256 _tmvReleased = boxes[_id].tmvReleased; _burnTMV(msg.sender, _tmvReleased); uint256 _collateral = boxes[_id].collateral; // Calculate the Ether equivalent of tokens according to the logic // where 1 TMV is equal to 1 USD uint256 _eth = _tmvReleased.mul(precision).div(rate()); // Calculate user bonus uint256 _userReward = _tmvReleased.mul(settings.userFee()).div(rate()); // The owner of the Box address _owner = ownerOf(_id); // Remove a Box delete boxes[_id]; // Burn Box token _burn(_owner, _id); // Send the Ether equivalent & user benefit to the person who made closing happen msg.sender.transfer(_eth.add(_userReward)); // Decrease global Ether counter globalETH = globalETH.sub(_collateral); // Fire the event emit Closed(_id, _owner, msg.sender); } /// @dev Burns specified number of TMV tokens. function _burnTMV(address _from, uint256 _amount) internal { if (_amount > 0) { require(IToken(settings.tmvAddress()).balanceOf(_from) >= _amount, "You don't have enough tokens"); IToken(settings.tmvAddress()).burnLogic(_from, _amount); } } /// @dev Returns current oracle ETH/USD price with precision. function rate() public view returns(uint256) { return IOracle(settings.oracleAddress()).ethUsdPrice(); } /// @dev Given a Box ID, returns a number of tokens that can be withdrawn. function boxWithdrawableTmv(uint256 _id) public view onlyExists(_id) returns(uint256) { Box memory box = boxes[_id]; // Number of tokens that can be withdrawn for Box's collateral uint256 _amount = withdrawableTmv(box.collateral); if (box.tmvReleased >= _amount) { return 0; } // Return withdrawable rest return _amount.sub(box.tmvReleased); } /// @dev Given a Box ID, returns an amount of Ether that can be withdrawn. function withdrawableEth(uint256 _id) public view onlyExists(_id) returns(uint256) { // Amount of Ether that is not used in collateralization uint256 _avlbl = _freeEth(_id); // Return available Ether to withdraw if (_avlbl == 0) { return 0; } uint256 _rest = boxes[_id].collateral.sub(_avlbl); if (_rest < settings.minDeposit()) { return boxes[_id].collateral.sub(settings.minDeposit()); } else return _avlbl; } /// @dev Given a Box ID, returns amount of ETH that is not used in collateralization. function _freeEth(uint256 _id) internal view returns(uint256) { // Grab a reference to the Box Box memory box = boxes[_id]; // When there are no tokens withdrawn if (box.tmvReleased == 0) { return box.collateral; } // The amount of Ether that can be safely withdrawn from the system uint256 _maxGlobal = globalWithdrawableEth(); uint256 _globalAvailable; if (_maxGlobal > 0) { // The amount of Ether backing the tokens when the system is overcapitalized uint256 _need = overCapFrozenEth(box.tmvReleased); if (box.collateral > _need) { // Free Ether amount when the system is overcapitalized uint256 _free = box.collateral.sub(_need); if (_free > _maxGlobal) { // Store available amount when Box available Ether amount // is more than global available _globalAvailable = _maxGlobal; } // Return available amount of Ether to withdraw when the Box withdrawable // amount of Ether is smaller than global withdrawable amount of Ether else return _free; } } // The amount of Ether backing the tokens by default uint256 _frozen = defaultFrozenEth(box.tmvReleased); if (box.collateral > _frozen) { // Define the biggest number and return available Ether amount uint256 _localAvailable = box.collateral.sub(_frozen); return (_localAvailable > _globalAvailable) ? _localAvailable : _globalAvailable; } else { // Return available Ether amount return _globalAvailable; } } /// @dev Given a Box ID, returns collateral percent. function collateralPercent(uint256 _id) public view onlyExists(_id) returns(uint256) { Box memory box = boxes[_id]; if (box.tmvReleased == 0) { return 10**27; //some unreachable number } uint256 _ethCollateral = box.collateral; // division by 100 is not necessary because to get the percent you need to multiply by 100 return _ethCollateral.mul(rate()).div(box.tmvReleased); } /// @dev Checks if a given address currently has approval for a particular Box. /// @param _spender the address we are confirming Box is approved for. /// @param _tokenId Box ID. function isApprovedOrOwner(address _spender, uint256 _tokenId) external view returns (bool) { return _isApprovedOrOwner(_spender, _tokenId); } /// @dev Returns the global collateralization percent. function globalCollateralization() public view returns (uint256) { uint256 _supply = IToken(settings.tmvAddress()).totalSupply(); if (_supply == 0) { return settings.globalTargetCollateralization(); } return globalETH.mul(rate()).div(_supply); } /// @dev Returns the number of tokens that can be safely withdrawn from the system. function globalWithdrawableTmv(uint256 _value) public view returns (uint256) { uint256 _supply = IToken(settings.tmvAddress()).totalSupply(); if (globalCollateralization() <= settings.globalTargetCollateralization()) { return 0; } uint256 _totalBackedTmv = defaultWithdrawableTmv(globalETH.add(_value)); return _totalBackedTmv.sub(_supply); } /// @dev Returns Ether amount that can be safely withdrawn from the system. function globalWithdrawableEth() public view returns (uint256) { uint256 _supply = IToken(settings.tmvAddress()).totalSupply(); if (globalCollateralization() <= settings.globalTargetCollateralization()) { return 0; } uint256 _need = defaultFrozenEth(_supply); return globalETH.sub(_need); } /// @dev Returns the number of tokens that can be withdrawn /// for the specified collateral amount by default. function defaultWithdrawableTmv(uint256 _collateral) public view returns (uint256) { uint256 _num = _collateral.mul(rate()); uint256 _div = settings.globalTargetCollateralization(); return _num.div(_div); } /// @dev Returns the number of tokens that can be withdrawn /// for the specified collateral amount when the system is overcapitalized. function overCapWithdrawableTmv(uint256 _collateral) public view returns (uint256) { uint256 _num = _collateral.mul(rate()); uint256 _div = settings.ratio(); return _num.div(_div); } /// @dev Returns Ether amount backing the specified number of tokens by default. function defaultFrozenEth(uint256 _supply) public view returns (uint256) { return _supply.mul(settings.globalTargetCollateralization()).div(rate()); } /// @dev Returns Ether amount backing the specified number of tokens /// when the system is overcapitalized. function overCapFrozenEth(uint256 _supply) public view returns (uint256) { return _supply.mul(settings.ratio()).div(rate()); } /// @dev Returns the number of TMV that can capitalize the specified Box. function maxCapAmount(uint256 _id) public view onlyExists(_id) returns (uint256) { uint256 _colP = collateralPercent(_id); require(_colP >= settings.minStability() && _colP < settings.maxStability(), "It's only possible to capitalize toxic Boxes"); Box memory box = boxes[_id]; uint256 _num = box.tmvReleased.mul(settings.ratio()).sub(box.collateral.mul(rate())); uint256 _div = settings.ratio().sub(settings.minStability()); return _num.div(_div); } /// @dev Returns the number of tokens that can be actually withdrawn /// for the specified collateral. function withdrawableTmv(uint256 _collateral) public view returns(uint256) { uint256 _amount = overCapWithdrawableTmv(_collateral); uint256 _maxGlobal = globalWithdrawableTmv(0); if (_amount > _maxGlobal) { _amount = _maxGlobal; } uint256 _local = defaultWithdrawableTmv(_collateral); if (_amount < _local) { _amount = _local; } return _amount; } /// @dev Returns the collateral percentage for which tokens can be withdrawn /// for the specified collateral. function withdrawPercent(uint256 _collateral) external view returns(uint256) { uint256 _amount = overCapWithdrawableTmv(_collateral); uint256 _maxGlobal = globalWithdrawableTmv(_collateral); if (_amount > _maxGlobal) { _amount = _maxGlobal; } uint256 _local = defaultWithdrawableTmv(_collateral); if (_amount < _local) { _amount = _local; } return _collateral.mul(rate()).div(_amount); } } pragma solidity 0.4.25; import "./ERC721.sol"; import "./ERC721Enumerable.sol"; import "./ERC721Metadata.sol"; /** * @title TBoxClassic Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract TBoxToken is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) ERC721Metadata(name, symbol) public {} } pragma solidity 0.4.25; /** * Utility library of inline functions on addresses */ library Address { /** * 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 account address of the account to check * @return whether the target address is a contract */ function isContract(address account) 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(account) } return size > 0; } } pragma solidity 0.4.25; import "./IERC165.sol"; /** * @title ERC165 * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract ERC165 is IERC165 { bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor () internal { _registerInterface(_InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } pragma solidity 0.4.25; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./SafeMath.sol"; import "./Address.sol"; import "./ERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { require(_isApprovedOrOwner(msg.sender, tokenId)); require(to != address(0)); _clearApproval(from, tokenId); _removeTokenFrom(from, tokenId); _addTokenTo(to, tokenId); emit Transfer(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { require(to != address(0)); _addTokenTo(to, tokenId); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { _clearApproval(owner, tokenId); _removeTokenFrom(owner, tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to add a token ID to the list of a given address * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event. * @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 _addTokenTo(address to, uint256 tokenId) internal { require(_tokenOwner[tokenId] == address(0)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event, * and doesn't clear approvals. * @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 _removeTokenFrom(address from, uint256 tokenId) internal { require(ownerOf(tokenId) == from); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _tokenOwner[tokenId] = address(0); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param owner owner of the token * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(address owner, uint256 tokenId) private { require(ownerOf(tokenId) == owner); if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } pragma solidity 0.4.25; import "./IERC721Enumerable.sol"; import "./ERC721.sol"; import "./ERC165.sol"; /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => 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; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ /** * @dev Constructor function */ constructor () public { // register the supported interface to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721Enumerable); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner)); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply()); return _allTokens[index]; } /** * @dev Internal function to add a token ID to the list of a given address * This function is internal due to language limitations, see the note in ERC721.sol. * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event. * @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 _addTokenTo(address to, uint256 tokenId) internal { super._addTokenTo(to, tokenId); uint256 length = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); _ownedTokensIndex[tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * This function is internal due to language limitations, see the note in ERC721.sol. * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event, * and doesn't clear approvals. * @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 _removeTokenFrom(address from, uint256 tokenId) internal { super._removeTokenFrom(from, tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = _ownedTokensIndex[tokenId]; uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 lastToken = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastToken; // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list _ownedTokensIndex[tokenId] = 0; _ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Reorg all tokens array uint256 tokenIndex = _allTokensIndex[tokenId]; uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 lastToken = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastToken; _allTokens[lastTokenIndex] = 0; _allTokens.length--; _allTokensIndex[tokenId] = 0; _allTokensIndex[lastToken] = tokenIndex; } } pragma solidity 0.4.25; import "./ERC721.sol"; import "./IERC721Metadata.sol"; import "./ERC165.sol"; contract ERC721Metadata is ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId)); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId)); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } pragma solidity 0.4.25; /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ 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. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } pragma solidity 0.4.25; import "./IERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } pragma solidity 0.4.25; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721Enumerable is IERC721 { 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); } pragma solidity 0.4.25; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } pragma solidity 0.4.25; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } pragma solidity 0.4.25; /// @title IOracle /// @dev Interface for getting the data from the oracle contract. interface IOracle { function ethUsdPrice() external view returns(uint256); } pragma solidity 0.4.25; /// @title ISettings /// @dev Interface for getting the data from settings contract. interface ISettings { function oracleAddress() external view returns(address); function minDeposit() external view returns(uint256); function sysFee() external view returns(uint256); function userFee() external view returns(uint256); function ratio() external view returns(uint256); function globalTargetCollateralization() external view returns(uint256); function tmvAddress() external view returns(uint256); function maxStability() external view returns(uint256); function minStability() external view returns(uint256); function gasPriceLimit() external view returns(uint256); function isFeeManager(address account) external view returns (bool); function tBoxManager() external view returns(address); } pragma solidity 0.4.25; /// @title IToken /// @dev Interface for interaction with the TMV token contract. interface IToken { function burnLogic(address from, uint256 value) external; function approve(address spender, uint256 value) external; function balanceOf(address who) external view returns (uint256); function mint(address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 tokenId) external; } pragma solidity 0.4.25; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'mul'); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, 'div'); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, 'sub'); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'add'); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } pragma solidity 0.4.25; import "./TBoxToken.sol"; import "./ISettings.sol"; import "./IToken.sol"; import "./IOracle.sol"; /// @title TBoxManager contract TBoxManager is TBoxToken { // Total packed Ether uint256 public globalETH; // Precision using for USD and commission uint256 public precision = 100000; // The address of the system settings contract ISettings public settings; /// @dev An array containing the Boxes struct for all Boxes in existence. The ID /// of each Box is actually an index into this array. Box[] public boxes; /// @dev The main Box struct. Every Box in TimviSystem is represented by a copy /// of this structure. struct Box { // The collateral Ether amount in wei uint256 collateral; // The number of TMV withdrawn uint256 tmvReleased; } /// @dev The Created event is fired whenever a new Box comes into existence. This includes /// any time a Box is created through the create method. event Created(uint256 indexed id, address owner, uint256 collateral, uint256 tmvReleased); /// @dev The Closed event is fired whenever a Box is closed. Obviously, this includes /// any time a Box is closed through the close method, but it is also called when // a Box is closed through the closeDust method. event Closed(uint256 indexed id, address indexed owner, address indexed closer); /// @dev The Capitalized event is fired whenever a Box is capitalized. event Capitalized(uint256 indexed id, address indexed owner, address indexed who, uint256 tmvAmount, uint256 totalEth, uint256 userEth); /// @dev The EthWithdrawn event is fired whenever Ether is withdrawn from a Box /// using withdrawEth method. event EthWithdrawn(uint256 indexed id, uint256 value, address who); /// @dev The TmvWithdrawn event is fired whenever TMV is withdrawn from a Box /// using withdrawTmv method. event TmvWithdrawn(uint256 indexed id, uint256 value, address who); /// @dev The EthAdded event is fired whenever Ether is added to a Box /// using addEth method. event EthAdded(uint256 indexed id, uint256 value, address who); /// @dev The TmvAdded event is fired whenever TMV is added to a Box /// using addTmv method. event TmvAdded(uint256 indexed id, uint256 value, address who); /// @dev Defends against front-running attacks. modifier validTx() { require(tx.gasprice <= settings.gasPriceLimit(), "Gas price is greater than allowed"); _; } /// @dev Throws if called by any account other than the owner. modifier onlyAdmin() { require(settings.isFeeManager(msg.sender), "You have no access"); _; } /// @dev Throws if Box with specified id does not exist. modifier onlyExists(uint256 _id) { require(_exists(_id), "Box does not exist"); _; } /// @dev Access modifier for token owner-only functionality. modifier onlyApprovedOrOwner(uint256 _id) { require(_isApprovedOrOwner(msg.sender, _id), "Box isn't your"); _; } /// @dev The constructor sets ERC721 token name and symbol. /// @param _settings The address of the system settings contract. constructor(address _settings) TBoxToken("TBoxToken", "TBX") public { settings = ISettings(_settings); } /// @notice The funds are safe. /// @dev Creates Box with max collateral percent. function() external payable { // Redirect to the create method with no tokens to withdraw create(0); } /// @dev Withdraws system fee. function withdrawFee(address _beneficiary) external onlyAdmin { require(_beneficiary != address(0), "Zero address, be careful"); // Fee is the difference between the contract balance and // amount of Ether used in the entire system collateralization uint256 _fees = address(this).balance.sub(globalETH); // Check that the fee is collected require(_fees > 0, "There is no available fees"); // Transfer fee to provided address _beneficiary.transfer(_fees); } /// @dev Checks possibility of the issue of the specified token amount /// for provided Ether collateral and creates new Box /// @param _tokensToWithdraw Number of tokens to withdraw /// @return New Box ID. function create(uint256 _tokensToWithdraw) public payable validTx returns (uint256) { // Check that msg.value isn't smaller than minimum deposit require(msg.value >= settings.minDeposit(), "Deposit is very small"); // Calculate collateralization when tokens are needed if (_tokensToWithdraw > 0) { // The number of tokens when collateralization is high uint256 _tokenLimit = overCapWithdrawableTmv(msg.value); // The number of tokens that can be safely withdrawn from the system uint256 _maxGlobal = globalWithdrawableTmv(msg.value); // Determine the higher number of tokens if (_tokenLimit > _maxGlobal) { _tokenLimit = _maxGlobal; } // The number of tokens that can be withdrawn anyway uint256 _local = defaultWithdrawableTmv(msg.value); // Determine the higher number of tokens if (_tokenLimit < _local) { _tokenLimit = _local; } // You can only withdraw available amount require(_tokensToWithdraw <= _tokenLimit, "Token amount is more than available"); // Mint TMV tokens to the Box creator IToken(settings.tmvAddress()).mint(msg.sender, _tokensToWithdraw); } // The id of the new Box uint256 _id = boxes.push(Box(msg.value, _tokensToWithdraw)).sub(1); // Increase global Ether counter globalETH = globalETH.add(msg.value); // Mint TBX token to the Box creator _mint(msg.sender, _id); // Fire the event emit Created(_id, msg.sender, msg.value, _tokensToWithdraw); // return the new Box's ID return _id; } /// @dev Allows the owner or approved user of the Box to close one by burning the /// required number of tokens and return the Box's collateral. /// @param _id A Box ID to close. function close(uint256 _id) external onlyApprovedOrOwner(_id) { // Address of the owner of the Box address _owner = _tokenOwner[_id]; // Burn needed number of tokens uint256 _tokensNeed = boxes[_id].tmvReleased; _burnTMV(msg.sender, _tokensNeed); // Grab a reference to the Box's collateral in storage uint256 _collateral = boxes[_id].collateral; // burn Box token _burn(_owner, _id); // Removes Box delete boxes[_id]; // Send the Box's collateral to the person who made closing happen msg.sender.transfer(_collateral); // Decrease global Ether counter globalETH = globalETH.sub(_collateral); // Fire the event emit Closed(_id, _owner, msg.sender); } /// @notice This allows you not to be tied to the current ETH/USD rate. /// @dev Allows the user to capitalize a Box with the maximum current amount. /// @param _id A Box ID to capitalize. function capitalizeMax(uint256 _id) external { capitalize(_id, maxCapAmount(_id)); } /// @dev Allows the user to capitalize a Box with specified number of tokens. /// @param _id A Box ID to capitalize. /// @param _tmv Specified number of tokens to capitalize. function capitalize(uint256 _id, uint256 _tmv) public validTx { // The maximum number of tokens for which Box can be capitalized uint256 _maxCapAmount = maxCapAmount(_id); // Check the number of tokens require(_tmv <= _maxCapAmount && _tmv >= 10 ** 17, "Tokens amount out of range"); // Decrease Box TMV withdrawn counter boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_tmv); // Calculate the Ether equivalent of tokens according to the logic // where 1 TMV is equal to 1 USD uint256 _equivalentETH = _tmv.mul(precision).div(rate()); // Calculate system fee uint256 _fee = _tmv.mul(settings.sysFee()).div(rate()); // Calculate user bonus uint256 _userReward = _tmv.mul(settings.userFee()).div(rate()); // Decrease Box's collateral amount boxes[_id].collateral = boxes[_id].collateral.sub(_fee.add(_userReward).add(_equivalentETH)); // Decrease global Ether counter globalETH = globalETH.sub(_fee.add(_userReward).add(_equivalentETH)); // burn Box token _burnTMV(msg.sender, _tmv); // Send the Ether equivalent & user benefit to the person who made capitalization happen. msg.sender.transfer(_equivalentETH.add(_userReward)); // Fire the event emit Capitalized(_id, ownerOf(_id), msg.sender, _tmv, _equivalentETH.add(_userReward).add(_fee), _equivalentETH.add(_userReward)); } /// @notice This allows you not to be tied to the current ETH/USD rate. /// @dev Allows an owner or approved user of the Box to withdraw maximum amount /// of Ether from the Box. /// @param _id A Box ID. function withdrawEthMax(uint256 _id) external { withdrawEth(_id, withdrawableEth(_id)); } /// @dev Allows an owner or approved user of the Box to withdraw specified amount /// of Ether from the Box. /// @param _id A Box ID. /// @param _amount The number of Ether to withdraw. function withdrawEth(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx { require(_amount > 0, "Withdrawing zero"); require(_amount <= withdrawableEth(_id), "You can't withdraw so much"); // Decrease Box's collateral amount boxes[_id].collateral = boxes[_id].collateral.sub(_amount); // Decrease global Ether counter globalETH = globalETH.sub(_amount); // Send the Ether to the person who made capitalization happen msg.sender.transfer(_amount); // Fire the event emit EthWithdrawn(_id, _amount, msg.sender); } /// @notice This allows you not to be tied to the current ETH/USD rate. /// @dev Allows an owner or approved user of the Box to withdraw maximum number /// of TMV tokens from the Box. /// @param _id A Box ID. function withdrawTmvMax(uint256 _id) external onlyApprovedOrOwner(_id) { withdrawTmv(_id, boxWithdrawableTmv(_id)); } /// @dev Allows an owner or approved user of the Box to withdraw specified number /// of TMV tokens from the Box. /// @param _id A Box ID. /// @param _amount The number of tokens to withdraw. function withdrawTmv(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx { require(_amount > 0, "Withdrawing zero"); // Check the number of tokens require(_amount <= boxWithdrawableTmv(_id), "You can't withdraw so much"); // Increase Box TMV withdrawn counter boxes[_id].tmvReleased = boxes[_id].tmvReleased.add(_amount); // Mints tokens to the person who made withdrawing IToken(settings.tmvAddress()).mint(msg.sender, _amount); // Fire the event emit TmvWithdrawn(_id, _amount, msg.sender); } /// @dev Allows anyone to add Ether to a Box. /// @param _id A Box ID. function addEth(uint256 _id) external payable onlyExists(_id) { require(msg.value > 0, "Don't add 0"); // Increase Box collateral boxes[_id].collateral = boxes[_id].collateral.add(msg.value); // Increase global Ether counter globalETH = globalETH.add(msg.value); // Fire the event emit EthAdded(_id, msg.value, msg.sender); } /// @dev Allows anyone to add TMV to a Box. /// @param _id A Box ID. /// @param _amount The number of tokens to add. function addTmv(uint256 _id, uint256 _amount) external onlyExists(_id) { require(_amount > 0, "Don't add 0"); // Check the number of tokens require(_amount <= boxes[_id].tmvReleased, "Too much tokens"); // Removes added tokens from the collateralization _burnTMV(msg.sender, _amount); boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_amount); // Fire the event emit TmvAdded(_id, _amount, msg.sender); } /// @dev Allows anyone to close Box with collateral amount smaller than 3 USD. /// The person who made closing happen will benefit like capitalization. /// @param _id A Box ID. function closeDust(uint256 _id) external onlyExists(_id) validTx { // Check collateral percent of the Box require(collateralPercent(_id) >= settings.minStability(), "This Box isn't collapsable"); // Check collateral amount of the Box require(boxes[_id].collateral.mul(rate()) < precision.mul(3).mul(10 ** 18), "It's only possible to collapse dust"); // Burn needed TMV amount to close uint256 _tmvReleased = boxes[_id].tmvReleased; _burnTMV(msg.sender, _tmvReleased); uint256 _collateral = boxes[_id].collateral; // Calculate the Ether equivalent of tokens according to the logic // where 1 TMV is equal to 1 USD uint256 _eth = _tmvReleased.mul(precision).div(rate()); // Calculate user bonus uint256 _userReward = _tmvReleased.mul(settings.userFee()).div(rate()); // The owner of the Box address _owner = ownerOf(_id); // Remove a Box delete boxes[_id]; // Burn Box token _burn(_owner, _id); // Send the Ether equivalent & user benefit to the person who made closing happen msg.sender.transfer(_eth.add(_userReward)); // Decrease global Ether counter globalETH = globalETH.sub(_collateral); // Fire the event emit Closed(_id, _owner, msg.sender); } /// @dev Burns specified number of TMV tokens. function _burnTMV(address _from, uint256 _amount) internal { if (_amount > 0) { require(IToken(settings.tmvAddress()).balanceOf(_from) >= _amount, "You don't have enough tokens"); IToken(settings.tmvAddress()).burnLogic(_from, _amount); } } /// @dev Returns current oracle ETH/USD price with precision. function rate() public view returns(uint256) { return IOracle(settings.oracleAddress()).ethUsdPrice(); } /// @dev Given a Box ID, returns a number of tokens that can be withdrawn. function boxWithdrawableTmv(uint256 _id) public view onlyExists(_id) returns(uint256) { Box memory box = boxes[_id]; // Number of tokens that can be withdrawn for Box's collateral uint256 _amount = withdrawableTmv(box.collateral); if (box.tmvReleased >= _amount) { return 0; } // Return withdrawable rest return _amount.sub(box.tmvReleased); } /// @dev Given a Box ID, returns an amount of Ether that can be withdrawn. function withdrawableEth(uint256 _id) public view onlyExists(_id) returns(uint256) { // Amount of Ether that is not used in collateralization uint256 _avlbl = _freeEth(_id); // Return available Ether to withdraw if (_avlbl == 0) { return 0; } uint256 _rest = boxes[_id].collateral.sub(_avlbl); if (_rest < settings.minDeposit()) { return boxes[_id].collateral.sub(settings.minDeposit()); } else return _avlbl; } /// @dev Given a Box ID, returns amount of ETH that is not used in collateralization. function _freeEth(uint256 _id) internal view returns(uint256) { // Grab a reference to the Box Box memory box = boxes[_id]; // When there are no tokens withdrawn if (box.tmvReleased == 0) { return box.collateral; } // The amount of Ether that can be safely withdrawn from the system uint256 _maxGlobal = globalWithdrawableEth(); uint256 _globalAvailable; if (_maxGlobal > 0) { // The amount of Ether backing the tokens when the system is overcapitalized uint256 _need = overCapFrozenEth(box.tmvReleased); if (box.collateral > _need) { // Free Ether amount when the system is overcapitalized uint256 _free = box.collateral.sub(_need); if (_free > _maxGlobal) { // Store available amount when Box available Ether amount // is more than global available _globalAvailable = _maxGlobal; } // Return available amount of Ether to withdraw when the Box withdrawable // amount of Ether is smaller than global withdrawable amount of Ether else return _free; } } // The amount of Ether backing the tokens by default uint256 _frozen = defaultFrozenEth(box.tmvReleased); if (box.collateral > _frozen) { // Define the biggest number and return available Ether amount uint256 _localAvailable = box.collateral.sub(_frozen); return (_localAvailable > _globalAvailable) ? _localAvailable : _globalAvailable; } else { // Return available Ether amount return _globalAvailable; } } /// @dev Given a Box ID, returns collateral percent. function collateralPercent(uint256 _id) public view onlyExists(_id) returns(uint256) { Box memory box = boxes[_id]; if (box.tmvReleased == 0) { return 10**27; //some unreachable number } uint256 _ethCollateral = box.collateral; // division by 100 is not necessary because to get the percent you need to multiply by 100 return _ethCollateral.mul(rate()).div(box.tmvReleased); } /// @dev Checks if a given address currently has approval for a particular Box. /// @param _spender the address we are confirming Box is approved for. /// @param _tokenId Box ID. function isApprovedOrOwner(address _spender, uint256 _tokenId) external view returns (bool) { return _isApprovedOrOwner(_spender, _tokenId); } /// @dev Returns the global collateralization percent. function globalCollateralization() public view returns (uint256) { uint256 _supply = IToken(settings.tmvAddress()).totalSupply(); if (_supply == 0) { return settings.globalTargetCollateralization(); } return globalETH.mul(rate()).div(_supply); } /// @dev Returns the number of tokens that can be safely withdrawn from the system. function globalWithdrawableTmv(uint256 _value) public view returns (uint256) { uint256 _supply = IToken(settings.tmvAddress()).totalSupply(); if (globalCollateralization() <= settings.globalTargetCollateralization()) { return 0; } uint256 _totalBackedTmv = defaultWithdrawableTmv(globalETH.add(_value)); return _totalBackedTmv.sub(_supply); } /// @dev Returns Ether amount that can be safely withdrawn from the system. function globalWithdrawableEth() public view returns (uint256) { uint256 _supply = IToken(settings.tmvAddress()).totalSupply(); if (globalCollateralization() <= settings.globalTargetCollateralization()) { return 0; } uint256 _need = defaultFrozenEth(_supply); return globalETH.sub(_need); } /// @dev Returns the number of tokens that can be withdrawn /// for the specified collateral amount by default. function defaultWithdrawableTmv(uint256 _collateral) public view returns (uint256) { uint256 _num = _collateral.mul(rate()); uint256 _div = settings.globalTargetCollateralization(); return _num.div(_div); } /// @dev Returns the number of tokens that can be withdrawn /// for the specified collateral amount when the system is overcapitalized. function overCapWithdrawableTmv(uint256 _collateral) public view returns (uint256) { uint256 _num = _collateral.mul(rate()); uint256 _div = settings.ratio(); return _num.div(_div); } /// @dev Returns Ether amount backing the specified number of tokens by default. function defaultFrozenEth(uint256 _supply) public view returns (uint256) { return _supply.mul(settings.globalTargetCollateralization()).div(rate()); } /// @dev Returns Ether amount backing the specified number of tokens /// when the system is overcapitalized. function overCapFrozenEth(uint256 _supply) public view returns (uint256) { return _supply.mul(settings.ratio()).div(rate()); } /// @dev Returns the number of TMV that can capitalize the specified Box. function maxCapAmount(uint256 _id) public view onlyExists(_id) returns (uint256) { uint256 _colP = collateralPercent(_id); require(_colP >= settings.minStability() && _colP < settings.maxStability(), "It's only possible to capitalize toxic Boxes"); Box memory box = boxes[_id]; uint256 _num = box.tmvReleased.mul(settings.ratio()).sub(box.collateral.mul(rate())); uint256 _div = settings.ratio().sub(settings.minStability()); return _num.div(_div); } /// @dev Returns the number of tokens that can be actually withdrawn /// for the specified collateral. function withdrawableTmv(uint256 _collateral) public view returns(uint256) { uint256 _amount = overCapWithdrawableTmv(_collateral); uint256 _maxGlobal = globalWithdrawableTmv(0); if (_amount > _maxGlobal) { _amount = _maxGlobal; } uint256 _local = defaultWithdrawableTmv(_collateral); if (_amount < _local) { _amount = _local; } return _amount; } /// @dev Returns the collateral percentage for which tokens can be withdrawn /// for the specified collateral. function withdrawPercent(uint256 _collateral) external view returns(uint256) { uint256 _amount = overCapWithdrawableTmv(_collateral); uint256 _maxGlobal = globalWithdrawableTmv(_collateral); if (_amount > _maxGlobal) { _amount = _maxGlobal; } uint256 _local = defaultWithdrawableTmv(_collateral); if (_amount < _local) { _amount = _local; } return _collateral.mul(rate()).div(_amount); } } pragma solidity 0.4.25; import "./ERC721.sol"; import "./ERC721Enumerable.sol"; import "./ERC721Metadata.sol"; /** * @title TBoxClassic Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract TBoxToken is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) ERC721Metadata(name, symbol) public {} } pragma solidity 0.4.25; /** * Utility library of inline functions on addresses */ library Address { /** * 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 account address of the account to check * @return whether the target address is a contract */ function isContract(address account) 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(account) } return size > 0; } } pragma solidity 0.4.25; import "./IERC165.sol"; /** * @title ERC165 * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract ERC165 is IERC165 { bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor () internal { _registerInterface(_InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } pragma solidity 0.4.25; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./SafeMath.sol"; import "./Address.sol"; import "./ERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { require(_isApprovedOrOwner(msg.sender, tokenId)); require(to != address(0)); _clearApproval(from, tokenId); _removeTokenFrom(from, tokenId); _addTokenTo(to, tokenId); emit Transfer(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { require(to != address(0)); _addTokenTo(to, tokenId); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { _clearApproval(owner, tokenId); _removeTokenFrom(owner, tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to add a token ID to the list of a given address * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event. * @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 _addTokenTo(address to, uint256 tokenId) internal { require(_tokenOwner[tokenId] == address(0)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event, * and doesn't clear approvals. * @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 _removeTokenFrom(address from, uint256 tokenId) internal { require(ownerOf(tokenId) == from); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _tokenOwner[tokenId] = address(0); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param owner owner of the token * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(address owner, uint256 tokenId) private { require(ownerOf(tokenId) == owner); if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } pragma solidity 0.4.25; import "./IERC721Enumerable.sol"; import "./ERC721.sol"; import "./ERC165.sol"; /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => 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; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ /** * @dev Constructor function */ constructor () public { // register the supported interface to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721Enumerable); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner)); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply()); return _allTokens[index]; } /** * @dev Internal function to add a token ID to the list of a given address * This function is internal due to language limitations, see the note in ERC721.sol. * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event. * @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 _addTokenTo(address to, uint256 tokenId) internal { super._addTokenTo(to, tokenId); uint256 length = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); _ownedTokensIndex[tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * This function is internal due to language limitations, see the note in ERC721.sol. * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event, * and doesn't clear approvals. * @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 _removeTokenFrom(address from, uint256 tokenId) internal { super._removeTokenFrom(from, tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = _ownedTokensIndex[tokenId]; uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 lastToken = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastToken; // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list _ownedTokensIndex[tokenId] = 0; _ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Reorg all tokens array uint256 tokenIndex = _allTokensIndex[tokenId]; uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 lastToken = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastToken; _allTokens[lastTokenIndex] = 0; _allTokens.length--; _allTokensIndex[tokenId] = 0; _allTokensIndex[lastToken] = tokenIndex; } } pragma solidity 0.4.25; import "./ERC721.sol"; import "./IERC721Metadata.sol"; import "./ERC165.sol"; contract ERC721Metadata is ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId)); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId)); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } pragma solidity 0.4.25; /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ 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. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } pragma solidity 0.4.25; import "./IERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } pragma solidity 0.4.25; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721Enumerable is IERC721 { 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); } pragma solidity 0.4.25; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } pragma solidity 0.4.25; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } pragma solidity 0.4.25; /// @title IOracle /// @dev Interface for getting the data from the oracle contract. interface IOracle { function ethUsdPrice() external view returns(uint256); } pragma solidity 0.4.25; /// @title ISettings /// @dev Interface for getting the data from settings contract. interface ISettings { function oracleAddress() external view returns(address); function minDeposit() external view returns(uint256); function sysFee() external view returns(uint256); function userFee() external view returns(uint256); function ratio() external view returns(uint256); function globalTargetCollateralization() external view returns(uint256); function tmvAddress() external view returns(uint256); function maxStability() external view returns(uint256); function minStability() external view returns(uint256); function gasPriceLimit() external view returns(uint256); function isFeeManager(address account) external view returns (bool); function tBoxManager() external view returns(address); } pragma solidity 0.4.25; /// @title IToken /// @dev Interface for interaction with the TMV token contract. interface IToken { function burnLogic(address from, uint256 value) external; function approve(address spender, uint256 value) external; function balanceOf(address who) external view returns (uint256); function mint(address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 tokenId) external; } pragma solidity 0.4.25; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'mul'); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, 'div'); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, 'sub'); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'add'); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } pragma solidity 0.4.25; import "./TBoxToken.sol"; import "./ISettings.sol"; import "./IToken.sol"; import "./IOracle.sol"; /// @title TBoxManager contract TBoxManager is TBoxToken { // Total packed Ether uint256 public globalETH; // Precision using for USD and commission uint256 public precision = 100000; // The address of the system settings contract ISettings public settings; /// @dev An array containing the Boxes struct for all Boxes in existence. The ID /// of each Box is actually an index into this array. Box[] public boxes; /// @dev The main Box struct. Every Box in TimviSystem is represented by a copy /// of this structure. struct Box { // The collateral Ether amount in wei uint256 collateral; // The number of TMV withdrawn uint256 tmvReleased; } /// @dev The Created event is fired whenever a new Box comes into existence. This includes /// any time a Box is created through the create method. event Created(uint256 indexed id, address owner, uint256 collateral, uint256 tmvReleased); /// @dev The Closed event is fired whenever a Box is closed. Obviously, this includes /// any time a Box is closed through the close method, but it is also called when // a Box is closed through the closeDust method. event Closed(uint256 indexed id, address indexed owner, address indexed closer); /// @dev The Capitalized event is fired whenever a Box is capitalized. event Capitalized(uint256 indexed id, address indexed owner, address indexed who, uint256 tmvAmount, uint256 totalEth, uint256 userEth); /// @dev The EthWithdrawn event is fired whenever Ether is withdrawn from a Box /// using withdrawEth method. event EthWithdrawn(uint256 indexed id, uint256 value, address who); /// @dev The TmvWithdrawn event is fired whenever TMV is withdrawn from a Box /// using withdrawTmv method. event TmvWithdrawn(uint256 indexed id, uint256 value, address who); /// @dev The EthAdded event is fired whenever Ether is added to a Box /// using addEth method. event EthAdded(uint256 indexed id, uint256 value, address who); /// @dev The TmvAdded event is fired whenever TMV is added to a Box /// using addTmv method. event TmvAdded(uint256 indexed id, uint256 value, address who); /// @dev Defends against front-running attacks. modifier validTx() { require(tx.gasprice <= settings.gasPriceLimit(), "Gas price is greater than allowed"); _; } /// @dev Throws if called by any account other than the owner. modifier onlyAdmin() { require(settings.isFeeManager(msg.sender), "You have no access"); _; } /// @dev Throws if Box with specified id does not exist. modifier onlyExists(uint256 _id) { require(_exists(_id), "Box does not exist"); _; } /// @dev Access modifier for token owner-only functionality. modifier onlyApprovedOrOwner(uint256 _id) { require(_isApprovedOrOwner(msg.sender, _id), "Box isn't your"); _; } /// @dev The constructor sets ERC721 token name and symbol. /// @param _settings The address of the system settings contract. constructor(address _settings) TBoxToken("TBoxToken", "TBX") public { settings = ISettings(_settings); } /// @notice The funds are safe. /// @dev Creates Box with max collateral percent. function() external payable { // Redirect to the create method with no tokens to withdraw create(0); } /// @dev Withdraws system fee. function withdrawFee(address _beneficiary) external onlyAdmin { require(_beneficiary != address(0), "Zero address, be careful"); // Fee is the difference between the contract balance and // amount of Ether used in the entire system collateralization uint256 _fees = address(this).balance.sub(globalETH); // Check that the fee is collected require(_fees > 0, "There is no available fees"); // Transfer fee to provided address _beneficiary.transfer(_fees); } /// @dev Checks possibility of the issue of the specified token amount /// for provided Ether collateral and creates new Box /// @param _tokensToWithdraw Number of tokens to withdraw /// @return New Box ID. function create(uint256 _tokensToWithdraw) public payable validTx returns (uint256) { // Check that msg.value isn't smaller than minimum deposit require(msg.value >= settings.minDeposit(), "Deposit is very small"); // Calculate collateralization when tokens are needed if (_tokensToWithdraw > 0) { // The number of tokens when collateralization is high uint256 _tokenLimit = overCapWithdrawableTmv(msg.value); // The number of tokens that can be safely withdrawn from the system uint256 _maxGlobal = globalWithdrawableTmv(msg.value); // Determine the higher number of tokens if (_tokenLimit > _maxGlobal) { _tokenLimit = _maxGlobal; } // The number of tokens that can be withdrawn anyway uint256 _local = defaultWithdrawableTmv(msg.value); // Determine the higher number of tokens if (_tokenLimit < _local) { _tokenLimit = _local; } // You can only withdraw available amount require(_tokensToWithdraw <= _tokenLimit, "Token amount is more than available"); // Mint TMV tokens to the Box creator IToken(settings.tmvAddress()).mint(msg.sender, _tokensToWithdraw); } // The id of the new Box uint256 _id = boxes.push(Box(msg.value, _tokensToWithdraw)).sub(1); // Increase global Ether counter globalETH = globalETH.add(msg.value); // Mint TBX token to the Box creator _mint(msg.sender, _id); // Fire the event emit Created(_id, msg.sender, msg.value, _tokensToWithdraw); // return the new Box's ID return _id; } /// @dev Allows the owner or approved user of the Box to close one by burning the /// required number of tokens and return the Box's collateral. /// @param _id A Box ID to close. function close(uint256 _id) external onlyApprovedOrOwner(_id) { // Address of the owner of the Box address _owner = _tokenOwner[_id]; // Burn needed number of tokens uint256 _tokensNeed = boxes[_id].tmvReleased; _burnTMV(msg.sender, _tokensNeed); // Grab a reference to the Box's collateral in storage uint256 _collateral = boxes[_id].collateral; // burn Box token _burn(_owner, _id); // Removes Box delete boxes[_id]; // Send the Box's collateral to the person who made closing happen msg.sender.transfer(_collateral); // Decrease global Ether counter globalETH = globalETH.sub(_collateral); // Fire the event emit Closed(_id, _owner, msg.sender); } /// @notice This allows you not to be tied to the current ETH/USD rate. /// @dev Allows the user to capitalize a Box with the maximum current amount. /// @param _id A Box ID to capitalize. function capitalizeMax(uint256 _id) external { capitalize(_id, maxCapAmount(_id)); } /// @dev Allows the user to capitalize a Box with specified number of tokens. /// @param _id A Box ID to capitalize. /// @param _tmv Specified number of tokens to capitalize. function capitalize(uint256 _id, uint256 _tmv) public validTx { // The maximum number of tokens for which Box can be capitalized uint256 _maxCapAmount = maxCapAmount(_id); // Check the number of tokens require(_tmv <= _maxCapAmount && _tmv >= 10 ** 17, "Tokens amount out of range"); // Decrease Box TMV withdrawn counter boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_tmv); // Calculate the Ether equivalent of tokens according to the logic // where 1 TMV is equal to 1 USD uint256 _equivalentETH = _tmv.mul(precision).div(rate()); // Calculate system fee uint256 _fee = _tmv.mul(settings.sysFee()).div(rate()); // Calculate user bonus uint256 _userReward = _tmv.mul(settings.userFee()).div(rate()); // Decrease Box's collateral amount boxes[_id].collateral = boxes[_id].collateral.sub(_fee.add(_userReward).add(_equivalentETH)); // Decrease global Ether counter globalETH = globalETH.sub(_fee.add(_userReward).add(_equivalentETH)); // burn Box token _burnTMV(msg.sender, _tmv); // Send the Ether equivalent & user benefit to the person who made capitalization happen. msg.sender.transfer(_equivalentETH.add(_userReward)); // Fire the event emit Capitalized(_id, ownerOf(_id), msg.sender, _tmv, _equivalentETH.add(_userReward).add(_fee), _equivalentETH.add(_userReward)); } /// @notice This allows you not to be tied to the current ETH/USD rate. /// @dev Allows an owner or approved user of the Box to withdraw maximum amount /// of Ether from the Box. /// @param _id A Box ID. function withdrawEthMax(uint256 _id) external { withdrawEth(_id, withdrawableEth(_id)); } /// @dev Allows an owner or approved user of the Box to withdraw specified amount /// of Ether from the Box. /// @param _id A Box ID. /// @param _amount The number of Ether to withdraw. function withdrawEth(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx { require(_amount > 0, "Withdrawing zero"); require(_amount <= withdrawableEth(_id), "You can't withdraw so much"); // Decrease Box's collateral amount boxes[_id].collateral = boxes[_id].collateral.sub(_amount); // Decrease global Ether counter globalETH = globalETH.sub(_amount); // Send the Ether to the person who made capitalization happen msg.sender.transfer(_amount); // Fire the event emit EthWithdrawn(_id, _amount, msg.sender); } /// @notice This allows you not to be tied to the current ETH/USD rate. /// @dev Allows an owner or approved user of the Box to withdraw maximum number /// of TMV tokens from the Box. /// @param _id A Box ID. function withdrawTmvMax(uint256 _id) external onlyApprovedOrOwner(_id) { withdrawTmv(_id, boxWithdrawableTmv(_id)); } /// @dev Allows an owner or approved user of the Box to withdraw specified number /// of TMV tokens from the Box. /// @param _id A Box ID. /// @param _amount The number of tokens to withdraw. function withdrawTmv(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx { require(_amount > 0, "Withdrawing zero"); // Check the number of tokens require(_amount <= boxWithdrawableTmv(_id), "You can't withdraw so much"); // Increase Box TMV withdrawn counter boxes[_id].tmvReleased = boxes[_id].tmvReleased.add(_amount); // Mints tokens to the person who made withdrawing IToken(settings.tmvAddress()).mint(msg.sender, _amount); // Fire the event emit TmvWithdrawn(_id, _amount, msg.sender); } /// @dev Allows anyone to add Ether to a Box. /// @param _id A Box ID. function addEth(uint256 _id) external payable onlyExists(_id) { require(msg.value > 0, "Don't add 0"); // Increase Box collateral boxes[_id].collateral = boxes[_id].collateral.add(msg.value); // Increase global Ether counter globalETH = globalETH.add(msg.value); // Fire the event emit EthAdded(_id, msg.value, msg.sender); } /// @dev Allows anyone to add TMV to a Box. /// @param _id A Box ID. /// @param _amount The number of tokens to add. function addTmv(uint256 _id, uint256 _amount) external onlyExists(_id) { require(_amount > 0, "Don't add 0"); // Check the number of tokens require(_amount <= boxes[_id].tmvReleased, "Too much tokens"); // Removes added tokens from the collateralization _burnTMV(msg.sender, _amount); boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_amount); // Fire the event emit TmvAdded(_id, _amount, msg.sender); } /// @dev Allows anyone to close Box with collateral amount smaller than 3 USD. /// The person who made closing happen will benefit like capitalization. /// @param _id A Box ID. function closeDust(uint256 _id) external onlyExists(_id) validTx { // Check collateral percent of the Box require(collateralPercent(_id) >= settings.minStability(), "This Box isn't collapsable"); // Check collateral amount of the Box require(boxes[_id].collateral.mul(rate()) < precision.mul(3).mul(10 ** 18), "It's only possible to collapse dust"); // Burn needed TMV amount to close uint256 _tmvReleased = boxes[_id].tmvReleased; _burnTMV(msg.sender, _tmvReleased); uint256 _collateral = boxes[_id].collateral; // Calculate the Ether equivalent of tokens according to the logic // where 1 TMV is equal to 1 USD uint256 _eth = _tmvReleased.mul(precision).div(rate()); // Calculate user bonus uint256 _userReward = _tmvReleased.mul(settings.userFee()).div(rate()); // The owner of the Box address _owner = ownerOf(_id); // Remove a Box delete boxes[_id]; // Burn Box token _burn(_owner, _id); // Send the Ether equivalent & user benefit to the person who made closing happen msg.sender.transfer(_eth.add(_userReward)); // Decrease global Ether counter globalETH = globalETH.sub(_collateral); // Fire the event emit Closed(_id, _owner, msg.sender); } /// @dev Burns specified number of TMV tokens. function _burnTMV(address _from, uint256 _amount) internal { if (_amount > 0) { require(IToken(settings.tmvAddress()).balanceOf(_from) >= _amount, "You don't have enough tokens"); IToken(settings.tmvAddress()).burnLogic(_from, _amount); } } /// @dev Returns current oracle ETH/USD price with precision. function rate() public view returns(uint256) { return IOracle(settings.oracleAddress()).ethUsdPrice(); } /// @dev Given a Box ID, returns a number of tokens that can be withdrawn. function boxWithdrawableTmv(uint256 _id) public view onlyExists(_id) returns(uint256) { Box memory box = boxes[_id]; // Number of tokens that can be withdrawn for Box's collateral uint256 _amount = withdrawableTmv(box.collateral); if (box.tmvReleased >= _amount) { return 0; } // Return withdrawable rest return _amount.sub(box.tmvReleased); } /// @dev Given a Box ID, returns an amount of Ether that can be withdrawn. function withdrawableEth(uint256 _id) public view onlyExists(_id) returns(uint256) { // Amount of Ether that is not used in collateralization uint256 _avlbl = _freeEth(_id); // Return available Ether to withdraw if (_avlbl == 0) { return 0; } uint256 _rest = boxes[_id].collateral.sub(_avlbl); if (_rest < settings.minDeposit()) { return boxes[_id].collateral.sub(settings.minDeposit()); } else return _avlbl; } /// @dev Given a Box ID, returns amount of ETH that is not used in collateralization. function _freeEth(uint256 _id) internal view returns(uint256) { // Grab a reference to the Box Box memory box = boxes[_id]; // When there are no tokens withdrawn if (box.tmvReleased == 0) { return box.collateral; } // The amount of Ether that can be safely withdrawn from the system uint256 _maxGlobal = globalWithdrawableEth(); uint256 _globalAvailable; if (_maxGlobal > 0) { // The amount of Ether backing the tokens when the system is overcapitalized uint256 _need = overCapFrozenEth(box.tmvReleased); if (box.collateral > _need) { // Free Ether amount when the system is overcapitalized uint256 _free = box.collateral.sub(_need); if (_free > _maxGlobal) { // Store available amount when Box available Ether amount // is more than global available _globalAvailable = _maxGlobal; } // Return available amount of Ether to withdraw when the Box withdrawable // amount of Ether is smaller than global withdrawable amount of Ether else return _free; } } // The amount of Ether backing the tokens by default uint256 _frozen = defaultFrozenEth(box.tmvReleased); if (box.collateral > _frozen) { // Define the biggest number and return available Ether amount uint256 _localAvailable = box.collateral.sub(_frozen); return (_localAvailable > _globalAvailable) ? _localAvailable : _globalAvailable; } else { // Return available Ether amount return _globalAvailable; } } /// @dev Given a Box ID, returns collateral percent. function collateralPercent(uint256 _id) public view onlyExists(_id) returns(uint256) { Box memory box = boxes[_id]; if (box.tmvReleased == 0) { return 10**27; //some unreachable number } uint256 _ethCollateral = box.collateral; // division by 100 is not necessary because to get the percent you need to multiply by 100 return _ethCollateral.mul(rate()).div(box.tmvReleased); } /// @dev Checks if a given address currently has approval for a particular Box. /// @param _spender the address we are confirming Box is approved for. /// @param _tokenId Box ID. function isApprovedOrOwner(address _spender, uint256 _tokenId) external view returns (bool) { return _isApprovedOrOwner(_spender, _tokenId); } /// @dev Returns the global collateralization percent. function globalCollateralization() public view returns (uint256) { uint256 _supply = IToken(settings.tmvAddress()).totalSupply(); if (_supply == 0) { return settings.globalTargetCollateralization(); } return globalETH.mul(rate()).div(_supply); } /// @dev Returns the number of tokens that can be safely withdrawn from the system. function globalWithdrawableTmv(uint256 _value) public view returns (uint256) { uint256 _supply = IToken(settings.tmvAddress()).totalSupply(); if (globalCollateralization() <= settings.globalTargetCollateralization()) { return 0; } uint256 _totalBackedTmv = defaultWithdrawableTmv(globalETH.add(_value)); return _totalBackedTmv.sub(_supply); } /// @dev Returns Ether amount that can be safely withdrawn from the system. function globalWithdrawableEth() public view returns (uint256) { uint256 _supply = IToken(settings.tmvAddress()).totalSupply(); if (globalCollateralization() <= settings.globalTargetCollateralization()) { return 0; } uint256 _need = defaultFrozenEth(_supply); return globalETH.sub(_need); } /// @dev Returns the number of tokens that can be withdrawn /// for the specified collateral amount by default. function defaultWithdrawableTmv(uint256 _collateral) public view returns (uint256) { uint256 _num = _collateral.mul(rate()); uint256 _div = settings.globalTargetCollateralization(); return _num.div(_div); } /// @dev Returns the number of tokens that can be withdrawn /// for the specified collateral amount when the system is overcapitalized. function overCapWithdrawableTmv(uint256 _collateral) public view returns (uint256) { uint256 _num = _collateral.mul(rate()); uint256 _div = settings.ratio(); return _num.div(_div); } /// @dev Returns Ether amount backing the specified number of tokens by default. function defaultFrozenEth(uint256 _supply) public view returns (uint256) { return _supply.mul(settings.globalTargetCollateralization()).div(rate()); } /// @dev Returns Ether amount backing the specified number of tokens /// when the system is overcapitalized. function overCapFrozenEth(uint256 _supply) public view returns (uint256) { return _supply.mul(settings.ratio()).div(rate()); } /// @dev Returns the number of TMV that can capitalize the specified Box. function maxCapAmount(uint256 _id) public view onlyExists(_id) returns (uint256) { uint256 _colP = collateralPercent(_id); require(_colP >= settings.minStability() && _colP < settings.maxStability(), "It's only possible to capitalize toxic Boxes"); Box memory box = boxes[_id]; uint256 _num = box.tmvReleased.mul(settings.ratio()).sub(box.collateral.mul(rate())); uint256 _div = settings.ratio().sub(settings.minStability()); return _num.div(_div); } /// @dev Returns the number of tokens that can be actually withdrawn /// for the specified collateral. function withdrawableTmv(uint256 _collateral) public view returns(uint256) { uint256 _amount = overCapWithdrawableTmv(_collateral); uint256 _maxGlobal = globalWithdrawableTmv(0); if (_amount > _maxGlobal) { _amount = _maxGlobal; } uint256 _local = defaultWithdrawableTmv(_collateral); if (_amount < _local) { _amount = _local; } return _amount; } /// @dev Returns the collateral percentage for which tokens can be withdrawn /// for the specified collateral. function withdrawPercent(uint256 _collateral) external view returns(uint256) { uint256 _amount = overCapWithdrawableTmv(_collateral); uint256 _maxGlobal = globalWithdrawableTmv(_collateral); if (_amount > _maxGlobal) { _amount = _maxGlobal; } uint256 _local = defaultWithdrawableTmv(_collateral); if (_amount < _local) { _amount = _local; } return _collateral.mul(rate()).div(_amount); } } pragma solidity 0.4.25; import "./ERC721.sol"; import "./ERC721Enumerable.sol"; import "./ERC721Metadata.sol"; /** * @title TBoxClassic Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract TBoxToken is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) ERC721Metadata(name, symbol) public {} }
Burns specified number of TMV tokens.
function _burnTMV(address _from, uint256 _amount) internal { if (_amount > 0) { require(IToken(settings.tmvAddress()).balanceOf(_from) >= _amount, "You don't have enough tokens"); IToken(settings.tmvAddress()).burnLogic(_from, _amount); } }
911,866
./full_match/43113/0x9849832a1d8274aaeDb1112ad9686413461e7101/sources/contracts/WeightedPoolFactory.sol
Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported./ We're going to dynamically create a revert string based on the error code, with the following format: 'BAL{errorCode}' where the code is left-padded with zeroes to three digits (so they range from 000 to 999). We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a number (8 to 16 bits) than the individual string characters. The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a safe place to rely on it without worrying about how its usage might affect e.g. memory contents.
function _revert(uint256 errorCode) pure { function getProtocolFeesCollector() external view returns (IProtocolFeesCollector); function setPaused(bool paused) external; function WETH() external view returns (IWETH); } pragma solidity ^0.7.0; } assembly { let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) mstore(0x24, 7) mstore(0x44, revertReason) revert(0, 100) } }
7,161,796
// Sources flattened with hardhat v2.8.2 https://hardhat.org // File contracts/solidity/proxy/IBeacon.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function childImplementation() external view returns (address); function upgradeChildTo(address newImplementation) external; } // File contracts/solidity/interface/INFTXVaultFactory.sol pragma solidity ^0.8.0; interface INFTXVaultFactory is IBeacon { // Read functions. function numVaults() external view returns (uint256); function zapContract() external view returns (address); function feeDistributor() external view returns (address); function eligibilityManager() external view returns (address); function vault(uint256 vaultId) external view returns (address); function allVaults() external view returns (address[] memory); function vaultsForAsset(address asset) external view returns (address[] memory); function isLocked(uint256 id) external view returns (bool); function excludedFromFees(address addr) external view returns (bool); function factoryMintFee() external view returns (uint64); function factoryRandomRedeemFee() external view returns (uint64); function factoryTargetRedeemFee() external view returns (uint64); function factoryRandomSwapFee() external view returns (uint64); function factoryTargetSwapFee() external view returns (uint64); function vaultFees(uint256 vaultId) external view returns (uint256, uint256, uint256, uint256, uint256); event NewFeeDistributor(address oldDistributor, address newDistributor); event NewZapContract(address oldZap, address newZap); event FeeExclusion(address feeExcluded, bool excluded); event NewEligibilityManager(address oldEligManager, address newEligManager); event NewVault(uint256 indexed vaultId, address vaultAddress, address assetAddress); event UpdateVaultFees(uint256 vaultId, uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee); event DisableVaultFees(uint256 vaultId); event UpdateFactoryFees(uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee); // Write functions. function __NFTXVaultFactory_init(address _vaultImpl, address _feeDistributor) external; function createVault( string calldata name, string calldata symbol, address _assetAddress, bool is1155, bool allowAllItems ) external returns (uint256); function setFeeDistributor(address _feeDistributor) external; function setEligibilityManager(address _eligibilityManager) external; function setZapContract(address _zapContract) external; function setFeeExclusion(address _excludedAddr, bool excluded) external; function setFactoryFees( uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee ) external; function setVaultFees( uint256 vaultId, uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee ) external; function disableVaultFees(uint256 vaultId) external; } // File contracts/solidity/token/IERC20Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/solidity/interface/IRewardDistributionToken.sol pragma solidity ^0.8.0; interface IRewardDistributionToken is IERC20Upgradeable { function distributeRewards(uint amount) external; function __RewardDistributionToken_init(IERC20Upgradeable _target, string memory _name, string memory _symbol) external; function mint(address account, address to, uint256 amount) external; function burnFrom(address account, uint256 amount) external; function withdrawReward(address user) external; function dividendOf(address _owner) external view returns(uint256); function withdrawnRewardOf(address _owner) external view returns(uint256); function accumulativeRewardOf(address _owner) external view returns(uint256); } // File contracts/solidity/util/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File contracts/solidity/util/SafeERC20Upgradeable.sol pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using Address for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/solidity/proxy/Initializable.sol // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // File contracts/solidity/util/ContextUpgradeable.sol pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File contracts/solidity/util/OwnableUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File contracts/solidity/util/PausableUpgradeable.sol pragma solidity ^0.8.0; contract PausableUpgradeable is OwnableUpgradeable { function __Pausable_init() internal initializer { __Ownable_init(); } event SetPaused(uint256 lockId, bool paused); event SetIsGuardian(address addr, bool isGuardian); mapping(address => bool) public isGuardian; mapping(uint256 => bool) public isPaused; // 0 : createVault // 1 : mint // 2 : redeem // 3 : swap // 4 : flashloan function onlyOwnerIfPaused(uint256 lockId) public view virtual { require(!isPaused[lockId] || msg.sender == owner(), "Paused"); } function unpause(uint256 lockId) public virtual onlyOwner { isPaused[lockId] = false; emit SetPaused(lockId, false); } function pause(uint256 lockId) public virtual { require(isGuardian[msg.sender], "Can't pause"); isPaused[lockId] = true; emit SetPaused(lockId, true); } function setIsGuardian(address addr, bool _isGuardian) public virtual onlyOwner { isGuardian[addr] = _isGuardian; emit SetIsGuardian(addr, _isGuardian); } } // File contracts/solidity/proxy/ClonesUpgradeable.sol pragma solidity ^0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library ClonesUpgradeable { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt, address deployer) internal pure returns (address predicted) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // File contracts/solidity/token/IERC20Metadata.sol pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File contracts/solidity/StakingTokenProvider.sol pragma solidity ^0.8.0; // Author: 0xKiwi. contract StakingTokenProvider is OwnableUpgradeable { address public uniLikeExchange; address public defaultPairedToken; string public defaultPrefix; mapping(address => address) public pairedToken; mapping(address => string) public pairedPrefix; event NewDefaultPaired(address oldPaired, address newPaired); event NewPairedTokenForVault(address vaultToken, address oldPairedtoken, address newPairedToken); // This is an address provder to allow us to abstract out what liquidity // our vault tokens should be paired with. function __StakingTokenProvider_init(address _uniLikeExchange, address _defaultPairedtoken, string memory _defaultPrefix) public initializer { __Ownable_init(); require(_uniLikeExchange != address(0), "Cannot be address(0)"); require(_defaultPairedtoken != address(0), "Cannot be address(0)"); uniLikeExchange = _uniLikeExchange; defaultPairedToken = _defaultPairedtoken; defaultPrefix = _defaultPrefix; } function setPairedTokenForVaultToken(address _vaultToken, address _newPairedToken, string calldata _newPrefix) external onlyOwner { require(_newPairedToken != address(0), "Cannot be address(0)"); emit NewPairedTokenForVault(_vaultToken, pairedToken[_vaultToken], _newPairedToken); pairedToken[_vaultToken] = _newPairedToken; pairedPrefix[_vaultToken] = _newPrefix; } function setDefaultPairedToken(address _newDefaultPaired, string calldata _newDefaultPrefix) external onlyOwner { emit NewDefaultPaired(defaultPairedToken, _newDefaultPaired); defaultPairedToken = _newDefaultPaired; defaultPrefix = _newDefaultPrefix; } function stakingTokenForVaultToken(address _vaultToken) external view returns (address) { address _pairedToken = pairedToken[_vaultToken]; if (_pairedToken == address(0)) { _pairedToken = defaultPairedToken; } return pairFor(uniLikeExchange, _vaultToken, _pairedToken); } function nameForStakingToken(address _vaultToken) external view returns (string memory) { string memory _pairedPrefix = pairedPrefix[_vaultToken]; if (bytes(_pairedPrefix).length == 0) { _pairedPrefix = defaultPrefix; } address _pairedToken = pairedToken[_vaultToken]; if (_pairedToken == address(0)) { _pairedToken = defaultPairedToken; } string memory symbol1 = IERC20Metadata(_vaultToken).symbol(); string memory symbol2 = IERC20Metadata(_pairedToken).symbol(); return string(abi.encodePacked(_pairedPrefix, symbol1, symbol2)); } function pairForVaultToken(address _vaultToken, address _pairedToken) external view returns (address) { return pairFor(uniLikeExchange, _vaultToken, _pairedToken); } // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint160(uint256(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash ))))); } } // File contracts/solidity/token/ERC20Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ 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_; } function _setMetadata(string memory name_, string memory symbol_) internal { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[45] private __gap; } // File contracts/solidity/util/SafeMathUpgradeable.sol pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // File contracts/solidity/util/SafeMathInt.sol pragma solidity ^0.8.0; /** * @title SafeMathInt * @dev Math operations with safety checks that revert on error * @dev SafeMath adapted for int256 * Based on code of https://github.com/RequestNetwork/requestNetwork/blob/master/packages/requestNetworkSmartContracts/contracts/base/math/SafeMathInt.sol */ library SafeMathInt { function mul(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when multiplying INT256_MIN with -1 // https://github.com/RequestNetwork/requestNetwork/issues/43 require(!(a == - 2**255 && b == -1) && !(b == - 2**255 && a == -1)); int256 c = a * b; require((b == 0) || (c / b == a)); return c; } function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing INT256_MIN by -1 // https://github.com/RequestNetwork/requestNetwork/issues/43 require(!(a == - 2**255 && b == -1) && (b > 0)); return a / b; } function sub(int256 a, int256 b) internal pure returns (int256) { require((b >= 0 && a - b <= a) || (b < 0 && a - b > a)); return a - b; } function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } // File contracts/solidity/token/TimelockRewardDistributionTokenImpl.sol pragma solidity ^0.8.0; /// @title Reward-Paying Token (renamed from Dividend) /// @author Roger Wu (https://github.com/roger-wu) /// @dev A mintable ERC20 token that allows anyone to pay and distribute a target token /// to token holders as dividends and allows token holders to withdraw their dividends. /// Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code contract TimelockRewardDistributionTokenImpl is OwnableUpgradeable, ERC20Upgradeable { using SafeMathUpgradeable for uint256; using SafeMathInt for int256; using SafeERC20Upgradeable for IERC20Upgradeable; IERC20Upgradeable public target; // With `magnitude`, we can properly distribute dividends even if the amount of received target is small. // For more discussion about choosing the value of `magnitude`, // see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728 uint256 constant internal magnitude = 2**128; uint256 internal magnifiedRewardPerShare; // About dividendCorrection: // If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with: // `dividendOf(_user) = dividendPerShare * balanceOf(_user)`. // When `balanceOf(_user)` is changed (via minting/burning/transferring tokens), // `dividendOf(_user)` should not be changed, // but the computed value of `dividendPerShare * balanceOf(_user)` is changed. // To keep the `dividendOf(_user)` unchanged, we add a correction term: // `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`, // where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed: // `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`. // So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed. mapping(address => int256) internal magnifiedRewardCorrections; mapping(address => uint256) internal withdrawnRewards; mapping(address => uint256) internal timelock; event Timelocked(address user, uint256 amount, uint256 until); function __TimelockRewardDistributionToken_init(IERC20Upgradeable _target, string memory _name, string memory _symbol) public initializer { __Ownable_init(); __ERC20_init(_name, _symbol); target = _target; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, 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(), allowance(sender, _msgSender()).sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function mint(address account, uint256 amount) public onlyOwner virtual { _mint(account, amount); } function timelockMint(address account, uint256 amount, uint256 timelockLength) public onlyOwner virtual { uint256 timelockFinish = block.timestamp + timelockLength; timelock[account] = timelockFinish; emit Timelocked(account, amount, timelockFinish); _mint(account, amount); } function timelockUntil(address account) public view returns (uint256) { return timelock[account]; } /** * @dev Destroys `amount` tokens from `account`, without deducting from the caller's * allowance. Dangerous. * * See {ERC20-_burn} and {ERC20-allowance}. */ function burnFrom(address account, uint256 amount) public virtual onlyOwner { _burn(account, amount); } /// @notice Distributes target to token holders as dividends. /// @dev It reverts if the total supply of tokens is 0. /// It emits the `RewardsDistributed` event if the amount of received target is greater than 0. /// About undistributed target tokens: /// In each distribution, there is a small amount of target not distributed, /// the magnified amount of which is /// `(amount * magnitude) % totalSupply()`. /// With a well-chosen `magnitude`, the amount of undistributed target /// (de-magnified) in a distribution can be less than 1 wei. /// We can actually keep track of the undistributed target in a distribution /// and try to distribute it in the next distribution, /// but keeping track of such data on-chain costs much more than /// the saved target, so we don't do that. function distributeRewards(uint amount) external virtual onlyOwner { require(totalSupply() > 0, "RewardDist: 0 supply"); require(amount > 0, "RewardDist: 0 amount"); // Because we receive the tokens from the staking contract, we assume the tokens have been received. magnifiedRewardPerShare = magnifiedRewardPerShare.add( (amount).mul(magnitude) / totalSupply() ); emit RewardsDistributed(msg.sender, amount); } /// @notice Withdraws the target distributed to the sender. /// @dev It emits a `RewardWithdrawn` event if the amount of withdrawn target is greater than 0. function withdrawReward(address user) external onlyOwner { uint256 _withdrawableReward = withdrawableRewardOf(user); if (_withdrawableReward > 0) { withdrawnRewards[user] = withdrawnRewards[user].add(_withdrawableReward); target.safeTransfer(user, _withdrawableReward); emit RewardWithdrawn(user, _withdrawableReward); } } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) public view returns(uint256) { return withdrawableRewardOf(_owner); } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function withdrawableRewardOf(address _owner) internal view returns(uint256) { return accumulativeRewardOf(_owner).sub(withdrawnRewards[_owner]); } /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has withdrawn. function withdrawnRewardOf(address _owner) public view returns(uint256) { return withdrawnRewards[_owner]; } /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeRewardOf(_owner) = withdrawableRewardOf(_owner) + withdrawnRewardOf(_owner) /// = (magnifiedRewardPerShare * balanceOf(_owner) + magnifiedRewardCorrections[_owner]) / magnitude /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has earned in total. function accumulativeRewardOf(address _owner) public view returns(uint256) { return magnifiedRewardPerShare.mul(balanceOf(_owner)).toInt256() .add(magnifiedRewardCorrections[_owner]).toUint256Safe() / magnitude; } /// @dev Internal function that transfer tokens from one address to another. /// Update magnifiedRewardCorrections to keep dividends unchanged. /// @param from The address to transfer from. /// @param to The address to transfer to. /// @param value The amount to be transferred. function _transfer(address from, address to, uint256 value) internal override { require(block.timestamp > timelock[from], "User locked"); super._transfer(from, to, value); int256 _magCorrection = magnifiedRewardPerShare.mul(value).toInt256(); magnifiedRewardCorrections[from] = magnifiedRewardCorrections[from].add(_magCorrection); magnifiedRewardCorrections[to] = magnifiedRewardCorrections[to].sub(_magCorrection); } /// @dev Internal function that mints tokens to an account. /// Update magnifiedRewardCorrections to keep dividends unchanged. /// @param account The account that will receive the created tokens. /// @param value The amount that will be created. function _mint(address account, uint256 value) internal override { super._mint(account, value); magnifiedRewardCorrections[account] = magnifiedRewardCorrections[account] .sub( (magnifiedRewardPerShare.mul(value)).toInt256() ); } /// @dev Internal function that burns an amount of the token of a given account. /// Update magnifiedRewardCorrections to keep dividends unchanged. /// @param account The account whose tokens will be burnt. /// @param value The amount that will be burnt. function _burn(address account, uint256 value) internal override { require(block.timestamp > timelock[account], "User locked"); super._burn(account, value); magnifiedRewardCorrections[account] = magnifiedRewardCorrections[account] .add( (magnifiedRewardPerShare.mul(value)).toInt256() ); } /// @dev This event MUST emit when target is distributed to token holders. /// @param from The address which sends target to this contract. /// @param weiAmount The amount of distributed target in wei. event RewardsDistributed( address indexed from, uint256 weiAmount ); /// @dev This event MUST emit when an address withdraws their dividend. /// @param to The address which withdraws target from this contract. /// @param weiAmount The amount of withdrawn target in wei. event RewardWithdrawn( address indexed to, uint256 weiAmount ); } // File contracts/solidity/NFTXLPStaking.sol pragma solidity ^0.8.0; // Author: 0xKiwi. // Pausing codes for LP staking are: // 10: Deposit contract NFTXLPStaking is PausableUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; INFTXVaultFactory public nftxVaultFactory; IRewardDistributionToken public rewardDistTokenImpl; StakingTokenProvider public stakingTokenProvider; event PoolCreated(uint256 vaultId, address pool); event PoolUpdated(uint256 vaultId, address pool); event FeesReceived(uint256 vaultId, uint256 amount); struct StakingPool { address stakingToken; address rewardToken; } mapping(uint256 => StakingPool) public vaultStakingInfo; TimelockRewardDistributionTokenImpl public newTimelockRewardDistTokenImpl; function __NFTXLPStaking__init(address _stakingTokenProvider) external initializer { __Ownable_init(); require(_stakingTokenProvider != address(0), "Provider != address(0)"); require(address(newTimelockRewardDistTokenImpl) == address(0), "Already assigned"); stakingTokenProvider = StakingTokenProvider(_stakingTokenProvider); newTimelockRewardDistTokenImpl = new TimelockRewardDistributionTokenImpl(); newTimelockRewardDistTokenImpl.__TimelockRewardDistributionToken_init(IERC20Upgradeable(address(0)), "", ""); } modifier onlyAdmin() { require(msg.sender == owner() || msg.sender == nftxVaultFactory.feeDistributor(), "LPStaking: Not authorized"); _; } function setNFTXVaultFactory(address newFactory) external onlyOwner { require(address(nftxVaultFactory) == address(0), "nftxVaultFactory is immutable"); nftxVaultFactory = INFTXVaultFactory(newFactory); } function setStakingTokenProvider(address newProvider) external onlyOwner { require(newProvider != address(0)); stakingTokenProvider = StakingTokenProvider(newProvider); } function addPoolForVault(uint256 vaultId) external onlyAdmin { require(address(nftxVaultFactory) != address(0), "LPStaking: Factory not set"); require(vaultStakingInfo[vaultId].stakingToken == address(0), "LPStaking: Pool already exists"); address _rewardToken = nftxVaultFactory.vault(vaultId); address _stakingToken = stakingTokenProvider.stakingTokenForVaultToken(_rewardToken); StakingPool memory pool = StakingPool(_stakingToken, _rewardToken); vaultStakingInfo[vaultId] = pool; address newRewardDistToken = _deployDividendToken(pool); emit PoolCreated(vaultId, newRewardDistToken); } function updatePoolForVaults(uint256[] calldata vaultIds) external { uint256 length = vaultIds.length; for (uint256 i; i < length; ++i) { updatePoolForVault(vaultIds[i]); } } // In case the provider changes, this lets the pool be updated. Anyone can call it. function updatePoolForVault(uint256 vaultId) public { StakingPool memory pool = vaultStakingInfo[vaultId]; // Not letting people use this function to create new pools. require(pool.stakingToken != address(0), "LPStaking: Pool doesn't exist"); address _stakingToken = stakingTokenProvider.stakingTokenForVaultToken(pool.rewardToken); StakingPool memory newPool = StakingPool(_stakingToken, pool.rewardToken); vaultStakingInfo[vaultId] = newPool; // If the pool is already deployed, ignore the update. address addr = address(_rewardDistributionTokenAddr(newPool)); if (isContract(addr)) { return; } address newRewardDistToken = _deployDividendToken(newPool); emit PoolUpdated(vaultId, newRewardDistToken); } function receiveRewards(uint256 vaultId, uint256 amount) external onlyAdmin returns (bool) { StakingPool memory pool = vaultStakingInfo[vaultId]; if (pool.stakingToken == address(0)) { // In case the pair is updated, but not yet return false; } TimelockRewardDistributionTokenImpl rewardDistToken = _rewardDistributionTokenAddr(pool); // Don't distribute rewards unless there are people to distribute to. // Also added here if the distribution token is not deployed, just forfeit rewards for now. if (!isContract(address(rewardDistToken)) || rewardDistToken.totalSupply() == 0) { return false; } // We "pull" to the dividend tokens so the vault only needs to approve this contract. IERC20Upgradeable(pool.rewardToken).safeTransferFrom(msg.sender, address(rewardDistToken), amount); rewardDistToken.distributeRewards(amount); emit FeesReceived(vaultId, amount); return true; } function deposit(uint256 vaultId, uint256 amount) external { onlyOwnerIfPaused(10); // Check the pool in case its been updated. updatePoolForVault(vaultId); StakingPool memory pool = vaultStakingInfo[vaultId]; require(pool.stakingToken != address(0), "LPStaking: Nonexistent pool"); IERC20Upgradeable(pool.stakingToken).safeTransferFrom(msg.sender, address(this), amount); TimelockRewardDistributionTokenImpl xSLPToken = _rewardDistributionTokenAddr(pool); // If the user has an existing timelock, check if it is in the future. uint256 currentTimelock = xSLPToken.timelockUntil(msg.sender); if (currentTimelock > block.timestamp) { // Maintain the same timelock if they already have one. // We do this instead of patching in the token because // the xSLP contracts as currently deployed are not upgradeable. xSLPToken.timelockMint(msg.sender, amount, currentTimelock-block.timestamp); } else { // Timelock for 2 seconds if they don't already have a timelock to prevent flash loans. xSLPToken.timelockMint(msg.sender, amount, 2); } } function timelockDepositFor(uint256 vaultId, address account, uint256 amount, uint256 timelockLength) external { require(timelockLength < 2592000, "Timelock too long"); require(nftxVaultFactory.excludedFromFees(msg.sender), "Not zap"); onlyOwnerIfPaused(10); // Check the pool in case its been updated. updatePoolForVault(vaultId); StakingPool memory pool = vaultStakingInfo[vaultId]; require(pool.stakingToken != address(0), "LPStaking: Nonexistent pool"); IERC20Upgradeable(pool.stakingToken).safeTransferFrom(msg.sender, address(this), amount); _rewardDistributionTokenAddr(pool).timelockMint(account, amount, timelockLength); } function exit(uint256 vaultId) external { StakingPool memory pool = vaultStakingInfo[vaultId]; _claimRewards(pool, msg.sender); _withdraw(pool, balanceOf(vaultId, msg.sender), msg.sender); } function emergencyExitAndClaim(address _stakingToken, address _rewardToken) external { StakingPool memory pool = StakingPool(_stakingToken, _rewardToken); TimelockRewardDistributionTokenImpl dist = _rewardDistributionTokenAddr(pool); require(isContract(address(dist)), "Not a pool"); _claimRewards(pool, msg.sender); _withdraw(pool, dist.balanceOf(msg.sender), msg.sender); } function emergencyExit(address _stakingToken, address _rewardToken) external { StakingPool memory pool = StakingPool(_stakingToken, _rewardToken); TimelockRewardDistributionTokenImpl dist = _rewardDistributionTokenAddr(pool); require(isContract(address(dist)), "Not a pool"); _withdraw(pool, dist.balanceOf(msg.sender), msg.sender); } function emergencyMigrate(uint256 vaultId) external { StakingPool memory pool = vaultStakingInfo[vaultId]; IRewardDistributionToken unusedDist = _unusedRewardDistributionTokenAddr(pool); IRewardDistributionToken oldDist = _oldRewardDistributionTokenAddr(pool); uint256 unusedDistBal; if (isContract(address(unusedDist))) { unusedDistBal = unusedDist.balanceOf(msg.sender); if (unusedDistBal > 0) { unusedDist.burnFrom(msg.sender, unusedDistBal); } } uint256 oldDistBal; if (isContract(address(oldDist))) { oldDistBal = oldDist.balanceOf(msg.sender); if (oldDistBal > 0) { oldDist.withdrawReward(msg.sender); oldDist.burnFrom(msg.sender, oldDistBal); } } TimelockRewardDistributionTokenImpl newDist = _rewardDistributionTokenAddr(pool); if (!isContract(address(newDist))) { address deployedDist = _deployDividendToken(pool); require(deployedDist == address(newDist), "Not deploying proper distro"); emit PoolUpdated(vaultId, deployedDist); } require(unusedDistBal + oldDistBal > 0, "Nothing to migrate"); newDist.mint(msg.sender, unusedDistBal + oldDistBal); } function withdraw(uint256 vaultId, uint256 amount) external { StakingPool memory pool = vaultStakingInfo[vaultId]; _claimRewards(pool, msg.sender); _withdraw(pool, amount, msg.sender); } function claimRewards(uint256 vaultId) public { StakingPool memory pool = vaultStakingInfo[vaultId]; _claimRewards(pool, msg.sender); } function claimMultipleRewards(uint256[] calldata vaultIds) external { uint256 length = vaultIds.length; for (uint256 i; i < length; ++i) { claimRewards(vaultIds[i]); } } function newRewardDistributionToken(uint256 vaultId) external view returns (TimelockRewardDistributionTokenImpl) { StakingPool memory pool = vaultStakingInfo[vaultId]; if (pool.stakingToken == address(0)) { return TimelockRewardDistributionTokenImpl(address(0)); } return _rewardDistributionTokenAddr(pool); } function rewardDistributionToken(uint256 vaultId) external view returns (IRewardDistributionToken) { StakingPool memory pool = vaultStakingInfo[vaultId]; if (pool.stakingToken == address(0)) { return IRewardDistributionToken(address(0)); } return _unusedRewardDistributionTokenAddr(pool); } function oldRewardDistributionToken(uint256 vaultId) external view returns (address) { StakingPool memory pool = vaultStakingInfo[vaultId]; if (pool.stakingToken == address(0)) { return address(0); } return address(_oldRewardDistributionTokenAddr(pool)); } function unusedRewardDistributionToken(uint256 vaultId) external view returns (address) { StakingPool memory pool = vaultStakingInfo[vaultId]; if (pool.stakingToken == address(0)) { return address(0); } return address(_unusedRewardDistributionTokenAddr(pool)); } function rewardDistributionTokenAddr(address stakedToken, address rewardToken) public view returns (address) { StakingPool memory pool = StakingPool(stakedToken, rewardToken); return address(_rewardDistributionTokenAddr(pool)); } function balanceOf(uint256 vaultId, address addr) public view returns (uint256) { StakingPool memory pool = vaultStakingInfo[vaultId]; TimelockRewardDistributionTokenImpl dist = _rewardDistributionTokenAddr(pool); require(isContract(address(dist)), "Not a pool"); return dist.balanceOf(addr); } function oldBalanceOf(uint256 vaultId, address addr) public view returns (uint256) { StakingPool memory pool = vaultStakingInfo[vaultId]; IRewardDistributionToken dist = _oldRewardDistributionTokenAddr(pool); require(isContract(address(dist)), "Not a pool"); return dist.balanceOf(addr); } function unusedBalanceOf(uint256 vaultId, address addr) public view returns (uint256) { StakingPool memory pool = vaultStakingInfo[vaultId]; IRewardDistributionToken dist = _unusedRewardDistributionTokenAddr(pool); require(isContract(address(dist)), "Not a pool"); return dist.balanceOf(addr); } function lockedUntil(uint256 vaultId, address who) external view returns (uint256) { StakingPool memory pool = vaultStakingInfo[vaultId]; TimelockRewardDistributionTokenImpl dist = _rewardDistributionTokenAddr(pool); return dist.timelockUntil(who); } function lockedLPBalance(uint256 vaultId, address who) external view returns (uint256) { StakingPool memory pool = vaultStakingInfo[vaultId]; TimelockRewardDistributionTokenImpl dist = _rewardDistributionTokenAddr(pool); if(block.timestamp > dist.timelockUntil(who)) { return 0; } return dist.balanceOf(who); } function _claimRewards(StakingPool memory pool, address account) internal { require(pool.stakingToken != address(0), "LPStaking: Nonexistent pool"); _rewardDistributionTokenAddr(pool).withdrawReward(account); } function _withdraw(StakingPool memory pool, uint256 amount, address account) internal { require(pool.stakingToken != address(0), "LPStaking: Nonexistent pool"); _rewardDistributionTokenAddr(pool).burnFrom(account, amount); IERC20Upgradeable(pool.stakingToken).safeTransfer(account, amount); } function _deployDividendToken(StakingPool memory pool) internal returns (address) { // Changed to use new nonces. bytes32 salt = keccak256(abi.encodePacked(pool.stakingToken, pool.rewardToken, uint256(2))); address rewardDistToken = ClonesUpgradeable.cloneDeterministic(address(newTimelockRewardDistTokenImpl), salt); string memory name = stakingTokenProvider.nameForStakingToken(pool.rewardToken); TimelockRewardDistributionTokenImpl(rewardDistToken).__TimelockRewardDistributionToken_init(IERC20Upgradeable(pool.rewardToken), name, name); return rewardDistToken; } // Note: this function does not guarantee the token is deployed, we leave that check to elsewhere to save gas. function _rewardDistributionTokenAddr(StakingPool memory pool) public view returns (TimelockRewardDistributionTokenImpl) { bytes32 salt = keccak256(abi.encodePacked(pool.stakingToken, pool.rewardToken, uint256(2) /* small nonce to change tokens */)); address tokenAddr = ClonesUpgradeable.predictDeterministicAddress(address(newTimelockRewardDistTokenImpl), salt); return TimelockRewardDistributionTokenImpl(tokenAddr); } // Note: this function does not guarantee the token is deployed, we leave that check to elsewhere to save gas. function _oldRewardDistributionTokenAddr(StakingPool memory pool) public view returns (IRewardDistributionToken) { bytes32 salt = keccak256(abi.encodePacked(pool.stakingToken, pool.rewardToken, uint256(1))); address tokenAddr = ClonesUpgradeable.predictDeterministicAddress(address(rewardDistTokenImpl), salt); return IRewardDistributionToken(tokenAddr); } // Note: this function does not guarantee the token is deployed, we leave that check to elsewhere to save gas. function _unusedRewardDistributionTokenAddr(StakingPool memory pool) public view returns (IRewardDistributionToken) { bytes32 salt = keccak256(abi.encodePacked(pool.stakingToken, pool.rewardToken)); address tokenAddr = ClonesUpgradeable.predictDeterministicAddress(address(rewardDistTokenImpl), salt); return IRewardDistributionToken(tokenAddr); } 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; } }
Interface for the optional metadata functions from the ERC20 standard. _Available since v4.1._/
interface IERC20Metadata is IERC20Upgradeable { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); }
1,435,864
pragma solidity ^0.4.18; import "./PetBase.sol"; /** *@title PetCore * Front contract for CryptoPets. Holds create pet funtionality and token name and symbol */ contract PetCore is PetBase{ // @notice Name and symbol of the non fungible token, as defined in ERC721. string public name = "CryptoPets"; string public symbol = "CP"; /** *@dev Creates the main CryptoPets smart contract instance. * sets the owenr and issues the first pet */ function PetCore() public { owner = msg.sender; createPet("Waxfang",9000,owner); } /** *@notice No tipping! *@dev fallback function to reject all Ether from being sent to contract */ function() external payable { require(msg.value == 0); } /** *@dev this is the function to create a pet and update the mappings with a new pet *@param _kind a string variable repreenting the kind of cryptopet *@param _genes a string variable representing the unique genes of the cryptopet *@param _owner an address to which the pet will be given, defaults to the owner */ function createPet(string _kind, uint _genes, address _owner) public onlyOwner() { if(_owner == address(0)) { _owner = owner; } uint256 newPetId = totalTokens; pets[newPetId] = Pet({ kind: _kind, genes: _genes, birthTime: uint64(now) }); transferFrom(address(0),_owner,newPetId); Birth(_owner,newPetId, _kind, _genes); } }
this is the function to create a pet and update the mappings with a new pet _kind a string variable repreenting the kind of cryptopet _genes a string variable representing the unique genes of the cryptopet _owner an address to which the pet will be given, defaults to the owner/
function createPet(string _kind, uint _genes, address _owner) public onlyOwner() { if(_owner == address(0)) { _owner = owner; } uint256 newPetId = totalTokens; pets[newPetId] = Pet({ kind: _kind, genes: _genes, birthTime: uint64(now) }); transferFrom(address(0),_owner,newPetId); Birth(_owner,newPetId, _kind, _genes); }
1,079,330
// pragma solidity >=0.5.16 <0.9.0; pragma experimental ABIEncoderV2; /* TODO: CHANGE DELETED DOCTOR/PATIENT TO POINTER TO FIRST ELEMENT/EMPTY ADDRESS */ // Service contract, combines patient, doctor, file contracts // and handles higher-level functionality contract Service { // Doctor Mappings mapping (address => doctor) internal doctors; mapping (address => mapping(address => uint)) internal doctorToPatient; // File mappings mapping (bytes32 => file) internal fileHashDict; // Patient mappings mapping (address => patient) internal patients; // dictionary of all patients mapping (address => mapping (address => uint)) internal patientToDoctor; // dictionary mapping patient to doctor mapping (address => mapping (bytes32 => uint)) internal patientToFile; // dictionary mapping patient to files /***** Main Structures *****/ // Doctor struct struct doctor { // doctor name string name; // clinic/practice name string clinic; // doctor wallet address address addr; // list of active patients address[] patient_list; string email; } // File struct struct file { string file_name; // type of record (i.e. blood test, etc) string record_type; // wallet address of the doctor who uploaded it address uploader_address; // name of the doctor who uploaded it string uploader_name; // file contents, currently stored as unencrypted string string contents; // date the file was uploaded string date_uploaded; } // Patient struct struct patient { string name; string dob; // wallet address address addr; bytes32[] files; // hashes of file that belong to this user for display purpose address[] doctor_list; string email; } /***** Doctor Methods *****/ // check address is a valid doctor modifier checkDoctor(address addr) { doctor memory d = doctors[addr]; require(d.addr > address(0x0), "doctor is not valid"); _; } // getter function for doctor's information function getDoctorInfo() public view checkDoctor(msg.sender) returns(string memory, address[] memory, address, string memory, string memory) { doctor memory d = doctors[msg.sender]; require((d.addr > address(0x0)), "doctor does not exist"); return (d.name, d.patient_list, d.addr, d.clinic, d.email); } // Create a new doctor method function signupDoctor(string memory _name, string memory _clinic, string memory _email) public returns(string memory, address, address[] memory, string memory, string memory) { // get doctor struct, make sure the name, clinic, and address exist doctor memory d = doctors[msg.sender]; require(keccak256(abi.encodePacked(_name)) != keccak256(""), "no name"); require(keccak256(abi.encodePacked(_clinic)) != keccak256(""), "no clinic"); require(!(d.addr > address(0x0)), "doctor exists"); // create doctor structure, return saved info doctors[msg.sender] = doctor({name:_name, clinic:_clinic, addr:msg.sender, patient_list:new address[](0), email:_email}); return (doctors[msg.sender].name, doctors[msg.sender].addr, doctors[msg.sender].patient_list, doctors[msg.sender].clinic, doctors[msg.sender].email); } /***** File Methods *****/ // method to test file contract function testFile(string memory _file_contents, string memory _file_name) public returns(bytes32, string memory){ bytes32 file_hash = keccak256(abi.encodePacked(_file_contents)); fileHashDict[file_hash] = file({file_name:_file_name,record_type:"blood test",uploader_address:address(0x0),uploader_name:"Test Doctor",contents:_file_contents, date_uploaded:"today"}); return (file_hash, "Blood Test 1"); } // used for testing, get the hash of a file's contents function getFileHash(string memory file_contents) public pure returns (bytes32) { return keccak256(abi.encodePacked(file_contents)); } // used for testing, get a file's name from the hash dictionary function getFileName(bytes32 file_hash) public view checkFile(file_hash) returns (string memory) { return fileHashDict[file_hash].file_name; } // make sure a file actually exists modifier checkFile(bytes32 file_hash) { bytes memory file_check = bytes(fileHashDict[file_hash].file_name); require(file_check.length > 0, "file does not exist"); _; } // given a file hash, get the file's name, type, and uploader's name and address function getFileInfo(bytes32 file_hash) public view checkFile(file_hash) returns(file memory) { return fileHashDict[file_hash]; } /***** Patient methods *****/ // check that a given patient actually exists modifier checkPatient(address addr) { patient memory p = patients[addr]; require(p.addr > address(0x0), "patient does not exist"); _; } // get info for a given patient (name, dob, files, list of whitelisted doctors) function getPatientInfo() public view checkPatient(msg.sender) returns(string memory, string memory, bytes32[] memory, address[] memory, string memory) { patient memory p = patients[msg.sender]; return (p.name, p.dob, p.files, p.doctor_list, p.email); } // add a new patient function signupPatient(string memory _name, string memory _dob, string memory _email) public returns(string memory, string memory, address, bytes32[] memory, address[] memory, string memory) { // store msg.sender as a patient in memory patient memory p = patients[msg.sender]; // make sure a patient with this addr doesn't already exist require(!(p.addr > address(0x0)), "patient with this address already exists"); // check to make sure the patient has a valid name require(keccak256(abi.encodePacked(_name)) != keccak256(""), "patient name not valid"); // add to patient dict patients[msg.sender] = patient({name:_name,dob:_dob,addr:msg.sender,files:new bytes32[](0),doctor_list:new address[](0), email: _email}); return (patients[msg.sender].name, patients[msg.sender].dob, patients[msg.sender].addr, patients[msg.sender].files, patients[msg.sender].doctor_list, patients[msg.sender].email); } /***** Service Methods *****/ // message sender address private owner; // set owner constructor() public{ owner = msg.sender; } // make sure that the sender is the owner modifier onlyOwner() { require(msg.sender == owner, "sender is not contract owner"); _; } // return message sender for testing purposes function testService() public view returns(address){ return msg.sender; } // add a file to a patient's list function addFile(string memory _file_name, string memory _file_type, address _patient_addr, string memory _contents, string memory _date_uploaded) public checkPatient(_patient_addr) { bytes32 file_hash = keccak256(abi.encode(_contents)); patient storage p = patients[_patient_addr]; require(patientToFile[_patient_addr][file_hash] < 1, "file hash error"); doctor memory d = doctors[msg.sender]; require((d.addr > address(0x0)), "doctor does not exist"); // add this file to the file hash dict and the patient's file list fileHashDict[file_hash] = file({file_name:_file_name, record_type:_file_type, uploader_address:msg.sender, uploader_name:d.name, contents:_contents, date_uploaded:_date_uploaded}); p.files.push(file_hash); uint file_pos = p.files.length; // add the position in the file list to patientToFile mapping (avoid duplicates in the future) patientToFile[_patient_addr][file_hash] = file_pos; } // method to grant a doctor access to a patient's record function grantDoctorAccess(address _doctor_address) public checkPatient(msg.sender) checkDoctor(_doctor_address) { // get struct for patient and doctor patient storage p = patients[msg.sender]; doctor storage d = doctors[_doctor_address]; // check doctor does not already have access require(patientToDoctor[msg.sender][_doctor_address] < 1, "doctor already has access");// this means doctor already been access // get the index of doctor's position in patient's doctor_list p.doctor_list.push(_doctor_address);// new length of array uint idx1 = p.doctor_list.length; // add doctor to patient's doctor list patientToDoctor[msg.sender][_doctor_address] = idx1; // add patient to doctor's patient list and to the doctortopatient mapping d.patient_list.push(msg.sender); uint idx2 = d.patient_list.length; doctorToPatient[_doctor_address][msg.sender] = idx2; } // method to revoke a doctor's access to a patient's record function revokeDoctorAccess(address _doctor_address) public checkPatient(msg.sender) checkDoctor(_doctor_address) { // get the patient and doctor structs // patient storage p = patients[msg.sender]; // doctor storage d = doctors[_doctor_address]; // make sure this doctor has been given access already require(patientToDoctor[msg.sender][_doctor_address] > 0, "doctor not in patient's list"); require(doctorToPatient[_doctor_address][msg.sender] > 0, "patient not in doctor's list"); // change the pointer to address 0 patientToDoctor[msg.sender][_doctor_address] = 0; doctorToPatient[_doctor_address][msg.sender] = 0; } // function to get patient info (a doctor requests) function getPatientInfoForDoctor(address _patient_requested) public view checkPatient(_patient_requested) checkDoctor(msg.sender) returns(string memory, string memory, bytes32[] memory, string memory){ // get the patient from the patient list patient memory p = patients[_patient_requested]; // make sure the patient actually exists in this doctor's care circle require(patientToDoctor[_patient_requested][msg.sender] > 0, "patient is not in doctor's care circle"); // return the patient's name, age, and files return (p.name, p.dob, p.files, p.email); } // function to get doctor info (for a patient) -- will see how necessary this ends up being function getDoctorInfoForPatient(address _doctor_requested) public view checkPatient(msg.sender) checkDoctor(_doctor_requested) returns(string memory, string memory, string memory){ // get the doctor from the doctors list doctor memory d = doctors[_doctor_requested]; // make sure the doctor actually exists require(doctorToPatient[_doctor_requested][msg.sender] > 0, "doctor does not exist (get doctor for patient)"); return (d.name, d.clinic, d.email); } function checkRevokeAccess(address _doctor) public view returns (uint) { uint a = patientToDoctor[msg.sender][_doctor]; return a; } }
getter function for doctor's information
function getDoctorInfo() public view checkDoctor(msg.sender) returns(string memory, address[] memory, address, string memory, string memory) { doctor memory d = doctors[msg.sender]; require((d.addr > address(0x0)), "doctor does not exist"); return (d.name, d.patient_list, d.addr, d.clinic, d.email); }
7,290,052
./partial_match/1/0x6601d3f885D1A91FfE63B4b4A834Cf9E2490C2D8/sources/src/settled-physical/AccountPhysicalEngine.sol
Transfers long tokens to another account. _subAccount subaccount that will be update in place/ decode parameters update the account in state
function _transferLong(address _subAccount, bytes calldata _data) internal virtual { (uint256 tokenId, address to, uint64 amount) = abi.decode(_data, (uint256, address, uint64)); _decreaseLongInAccount(_subAccount, tokenId, amount); _increaseLongInAccount(to, tokenId, amount); emit PhysicalOptionTokenTransferred(_subAccount, to, tokenId, amount); }
4,198,891
pragma solidity ^0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev 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; } } interface Token { function totalSupply() external view returns (uint _supply); function name() external view returns (string _name); function symbol() external view returns (string _symbol); function decimals() external view returns (uint8 _decimals); function balanceOf(address _owner) external view returns (uint _balance); function transfer(address _to, uint _tokens) external returns (bool _success); function transferFrom(address _from, address _to, uint _tokens) external returns (bool _success); function allowance(address _owner, address _spender) external view returns (uint _remaining); function approve(address _spender, uint _tokens) external returns (bool _success); event Transfer(address indexed _from, address indexed _to, uint _tokens, bytes indexed _data); event Approval(address indexed _owner, address indexed _spender, uint _tokens); } contract StandardToken is Token { using SafeMath for uint; function processTransfer(address _from, address _to, uint256 _value, bytes _data) internal returns (bool success) { if (balances[_from] >= _value && _value > 0) { balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); // ERC223 - ensure if we get told to transfer to a contract address // it must support tokenFallback method and approve the transfer. if (isContract(_to)) { iReceiver receiver = iReceiver(_to); receiver.tokenFallback(_from, _value, _data); } emit Transfer(_from, _to, _value, _data); return true; } return false; } /// @notice send `_value` token to `_to` from `msg.sender` with `_data` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @param _data Data to be logged and sent /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value, bytes _data) external returns (bool success) { return processTransfer(msg.sender, _to, _value, _data); } /// @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) external returns (bool success) { bytes memory empty; return processTransfer(msg.sender, _to, _value, empty); } /// @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) external returns (bool success) { if (allowed[_from][msg.sender] >= _value) { bytes memory empty; return processTransfer(_from, _to, _value, empty); } return false; } /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) external view returns (uint256 balance) { return balances[_owner]; } /// @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) external returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /// @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) external view returns (uint256 remaining) { return allowed[_owner][_spender]; } string public name; uint8 public decimals; string public symbol; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; function totalSupply() external view returns (uint _supply) { return totalSupply; } function name() external view returns (string _name) { return name; } function symbol() external view returns (string _symbol) { return symbol; } function decimals() external view returns (uint8 _decimals) { return decimals; } function isContract(address _addr) internal view returns (bool _is_contract) { uint length; assembly { length := extcodesize(_addr) } return (length>0); } } contract FLOCK is StandardToken { // CHANGE THIS. Update the contract name. using SafeMath for uint; /* 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 version = "H1.0"; uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We&#39;ll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? Round[] rounds; struct Round { uint start; uint end; uint price; } // This is a constructor function // which means the following function name has to match the contract name declared above function FLOCK() public { totalSupply = 10000000000; // Update total supply balances[msg.sender] = totalSupply; // Give the creator all initial tokens. name = "FLOCK"; // Set the name for display purposes decimals = 0; // Amount of decimals for display purposes symbol = "FLK"; // Set the symbol for display purposes fundsWallet = msg.sender; // The owner of the contract gets ETH uint ts = 1523764800; rounds.push(Round(ts, ts += 5 days, 500000)); // Round 1 rounds.push(Round(ts, ts += 5 days, 500000)); // Round 2 rounds.push(Round(ts, ts += 2 days, 250000)); // Round 3 rounds.push(Round(ts, ts += 2 days, 166667)); // Round 4 rounds.push(Round(ts, ts += 2 days, 125000)); // Round 5 rounds.push(Round(ts, ts += 2 days, 100000)); // Round 6 rounds.push(Round(ts, ts += 2 days, 83333)); // Round 7 rounds.push(Round(ts, ts += 2 days, 71429)); // Round 8 rounds.push(Round(ts, ts += 2 days, 62500)); // Round 9 rounds.push(Round(ts, ts += 2 days, 55556)); // Round 10 rounds.push(Round(ts, ts += 2 days, 50000)); // Round 11 } /// @notice Gets the conversion rate for ETH purchases. /// @return Amount of tokens per ETH paid. function unitsOneEthCanBuy() public view returns (uint _units) { for (uint i = 0; i < rounds.length; i++) { Round memory round = rounds[i]; if (block.timestamp >= round.start && block.timestamp < round.end) { return round.price; } } return 0; } /// @notice Accepts payment of eth in exchange for a variable amount of tokens, depending /// upon the conversion rate of the current sale round. function() external payable { uint ethInWei = msg.value; totalEthInWei = totalEthInWei + ethInWei; uint perEth = unitsOneEthCanBuy(); // The following division is necessary to convert the number of decimal places in // eth(wei=`18`) and our number of `decimal` places, since we have `unitsPerEth`: uint256 amount = ethInWei.mul(perEth).div(10**uint(18 - decimals)); require(amount > 0); require(balances[fundsWallet] >= amount); //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); bytes memory empty; processTransfer(fundsWallet, msg.sender, amount, empty); } /// @notice Approves and then calls the receiving contract function approveAndCall(address _spender, uint256 _value, bytes _data) external returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); // Call the receiveApproval function on the contract you want to be notified. iApprover(_spender).receiveApproval(msg.sender, _value, address(this), _data); return true; } /// @notice Safety function so any accidentally sent ERC20 compliant tokens can be recovered. function reclaimERC20(address _token, uint _tokens) external returns (bool _success) { require(msg.sender == fundsWallet); return Token(_token).transfer(msg.sender, _tokens); } } interface iReceiver { function tokenFallback(address _from, uint _value, bytes _data) external; } interface iApprover { function receiveApproval(address _from, uint256 _value, address _token, bytes _data) external; }
_owner The address from which the balance will be retrieved return The balance
function balanceOf(address _owner) external view returns (uint256 balance) { return balances[_owner]; }
2,339,797
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IERC721Proxy} from "./IERC721Proxy.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {StorageSlot} from "@openzeppelin/contracts/utils/StorageSlot.sol"; import {TokenRoles} from "../../roles/TokenRoles.sol"; import {DomainAware} from "../../../tools/DomainAware.sol"; import {ERC1820Client} from "../../../erc1820/ERC1820Client.sol"; import {ERC1820Implementer} from "../../../erc1820/ERC1820Implementer.sol"; import {IERC721Logic} from "../logic/IERC721Logic.sol"; import {ERC721Storage} from "../storage/ERC721Storage.sol"; import {ERC721Logic} from "../logic/ERC721Logic.sol"; import {ExtensionStorage} from "../../../extensions/ExtensionStorage.sol"; import {IToken, TokenStandard, TransferData} from "../../IToken.sol"; abstract contract ERC721Proxy is IERC721Proxy, TokenRoles, DomainAware, ERC1820Client, ERC1820Implementer { string constant internal ERC721_INTERFACE_NAME = "ERC721Token"; string constant internal ERC721_STORAGE_INTERFACE_NAME = "ERC721TokenStorage"; string constant internal ERC721_LOGIC_INTERFACE_NAME = "ERC721TokenLogic"; bytes32 constant ERC721_TOKEN_META = keccak256("erc721.token.meta"); struct TokenMeta { bool initialized; string name; string symbol; uint256 maxSupply; bool allowMint; bool allowBurn; } constructor( string memory name_, string memory symbol_, bool allowMint, bool allowBurn, address owner, uint256 maxSupply_, address logicAddress ) { require(maxSupply_ > 0, "Max supply must be non-zero"); StorageSlot.getAddressSlot(TOKEN_MANAGER_ADDRESS).value = _msgSender(); if (owner != _msgSender()) { transferOwnership(owner); } if (allowMint) { _addRole(owner, TOKEN_MANAGER_ADDRESS); } TokenMeta storage m = _getTokenMeta(); m.name = name_; m.symbol = symbol_; m.maxSupply = maxSupply_; m.allowMint = allowMint; m.allowBurn = allowBurn; ERC1820Client.setInterfaceImplementation(ERC721_INTERFACE_NAME, address(this)); ERC1820Implementer._setInterface(ERC721_INTERFACE_NAME); // For migration if (logicAddress == address(0)) { ERC721Logic logic = new ERC721Logic(); logicAddress = address(logic); } require(logicAddress != address(0), "Logic address must be given"); require(logicAddress == ERC1820Client.interfaceAddr(logicAddress, ERC721_LOGIC_INTERFACE_NAME), "Not registered as a logic contract"); _setImplementation(logicAddress); } function initialize() external onlyOwner { TokenMeta storage m = _getTokenMeta(); require(!m.initialized, "This proxy has already been initialized"); ERC721Storage store = new ERC721Storage(address(this)); _setStorage(address(store)); //Update the doamin seperator now that //we've setup everything _updateDomainSeparator(); m.initialized = true; _onProxyReady(); } function _onProxyReady() internal virtual { } modifier isProxyReady { TokenMeta storage m = _getTokenMeta(); require(m.initialized, "This proxy isnt initialized"); _; } modifier mintingEnabled { require(mintingAllowed(), "Minting is disabled"); _; } modifier burningEnabled { require(burningAllowed(), "Burning is disabled"); _; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function _getTokenMeta() internal pure returns (TokenMeta storage r) { bytes32 slot = ERC721_TOKEN_META; assembly { r.slot := slot } } function _getStorageContract() internal view isProxyReady returns (IERC721Logic) { return IERC721Logic( ERC1820Client.interfaceAddr(address(this), ERC721_STORAGE_INTERFACE_NAME) ); } function _getImplementationContract() internal view returns (address) { return ERC1820Client.interfaceAddr(address(this), ERC721_LOGIC_INTERFACE_NAME); } function _setImplementation(address implementation) internal { ERC1820Client.setInterfaceImplementation(ERC721_LOGIC_INTERFACE_NAME, implementation); } function _setStorage(address store) internal { ERC1820Client.setInterfaceImplementation(ERC721_STORAGE_INTERFACE_NAME, store); } function mintingAllowed() public override view isProxyReady returns (bool) { TokenMeta storage m = _getTokenMeta(); return m.allowMint; } function burningAllowed() public override view isProxyReady returns (bool) { TokenMeta storage m = _getTokenMeta(); return m.allowBurn; } function _toggleMinting(bool allowMinting) internal { TokenMeta storage m = _getTokenMeta(); m.allowMint = allowMinting; } function _toggleBurning(bool allowBurning) internal { TokenMeta storage m = _getTokenMeta(); m.allowBurn = allowBurning; } /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) public override view isProxyReady returns (uint256) { return _getStorageContract().balanceOf(account); } /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external override view returns (address owner) { return _getStorageContract().ownerOf(tokenId); } /** * @dev Returns the name of the token. */ function name() public override view returns (string memory) { return _getTokenMeta().name; } /** * @dev Returns the symbol of the token. */ function symbol() public override view returns (string memory) { return _getTokenMeta().symbol; } function tokenURI(uint256 tokenId) external override view returns (string memory) { return _getStorageContract().tokenURI(tokenId); } /** * @dev Performs a controlled transfer of tokens given a TransferData struct. * Under the hood, this will 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: * * - The caller must have the controller role * - `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 tokenTransfer(TransferData calldata td) external override onlyControllers isProxyReady returns (bool) { require(td.token == address(this), "Invalid token"); if (td.partition != bytes32(0)) { return false; //We cannot do partition transfers } bool result = _forwardCurrentCall(); if (result) { emit Transfer(td.from, td.to, td.tokenId); } return result; } //TODO Add mint /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public override virtual burningEnabled isProxyReady returns (bool) { bool result = _forwardCurrentCall(); if (result) { emit Transfer(_msgSender(), address(0), tokenId); } return result; } /** * @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) public override isProxyReady { bool result = _forwardCurrentCall(); if (result) { emit Transfer(from, to, tokenId); } } /** * @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) public override { bool result = _forwardCurrentCall(); if (result) { emit Transfer(from, to, tokenId); } } /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external override view returns (address operator) { return _getStorageContract().getApproved(tokenId); } /** * @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) public override isProxyReady { bool result = _forwardCurrentCall(); if (result) { emit Approval(_msgSender(), to, tokenId); } } /** * @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 override { bool result = _forwardCurrentCall(); if (result) { emit ApprovalForAll(_msgSender(), operator, _approved); } } /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external override view returns (bool) { return _getStorageContract().isApprovedForAll(owner, operator); } /** * @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 override { bool result = _forwardCurrentCall(); if (result) { emit Transfer(from, to, tokenId); } } function _transfer(TransferData memory td) private returns (bool) { return _forwardCall(abi.encodeWithSelector(IToken.tokenTransfer.selector, td)); } function _burn(uint256 amount) private returns (bool) { return _forwardCall(abi.encodeWithSelector(IERC721Proxy.burn.selector, amount)); } function domainName() public virtual override(DomainAware, IERC721Proxy) view returns (bytes memory) { return bytes(name()); } function domainVersion() public virtual override(DomainAware, IERC721Proxy) view returns (bytes32) { return bytes32(uint256(uint160(address(_getImplementationContract())))); } function upgradeTo(address implementation) external override onlyManager { _setImplementation(implementation); } function registerExtension(address extension) external override onlyManager isProxyReady returns (bool) { bool result = _getStorageContract().registerExtension(extension); if (result) { address contextAddress = _getStorageContract().contextAddressForExtension(extension); ExtensionStorage context = ExtensionStorage(payable(contextAddress)); bytes32[] memory requiredRoles = context.requiredRoles(); //If we have roles we need to register, then lets register them if (requiredRoles.length > 0) { address ctxAddress = address(context); for (uint i = 0; i < requiredRoles.length; i++) { _addRole(ctxAddress, requiredRoles[i]); } } } return result; } function removeExtension(address extension) external override onlyManager isProxyReady returns (bool) { bool result = _getStorageContract().removeExtension(extension); if (result) { address contextAddress = _getStorageContract().contextAddressForExtension(extension); ExtensionStorage context = ExtensionStorage(payable(contextAddress)); bytes32[] memory requiredRoles = context.requiredRoles(); //If we have roles we need to register, then lets register them if (requiredRoles.length > 0) { address ctxAddress = address(context); for (uint i = 0; i < requiredRoles.length; i++) { _addRole(ctxAddress, requiredRoles[i]); } } } return result; } function disableExtension(address extension) external override onlyManager isProxyReady returns (bool) { return _getStorageContract().disableExtension(extension); } function enableExtension(address extension) external override onlyManager isProxyReady returns (bool) { return _getStorageContract().enableExtension(extension); } function allExtensions() external override view isProxyReady returns (address[] memory) { return _getStorageContract().allExtensions(); } function contextAddressForExtension(address extension) external override view isProxyReady returns (address) { return _getStorageContract().contextAddressForExtension(extension); } // Find facet for function that is called and execute the // function if a facet is found and return any value. fallback() external virtual payable isProxyReady { _forwardCurrentCall(); } function _forwardCurrentCall() private returns (bool) { _forwardCall(_msgData()); } function _forwardCall(bytes memory _calldata) private returns (bool) { address store = address(_getStorageContract()); // Forward call to storage contract, appending the current _msgSender to the // end of the current calldata (bool success, bytes memory result) = store.call{gas: gasleft(), value: msg.value}(abi.encodePacked(_calldata, _msgSender())); if (!success) { revert(string(result)); } return success; } receive() external payable {} function tokenStandard() external pure override returns (TokenStandard) { return TokenStandard.ERC721; } }
Burns `tokenId`. See {ERC721-_burn}. Requirements: - The caller must own `tokenId` or be an approved operator./
function burn(uint256 tokenId) public override virtual burningEnabled isProxyReady returns (bool) { bool result = _forwardCurrentCall(); if (result) { emit Transfer(_msgSender(), address(0), tokenId); } return result; }
1,790,636
./partial_match/1/0x56146633c6C9D3536eEBbf0bcB1D5F20A788B82a/sources/ETHRegistrarController.sol
Sets the `name()` record for the reverse ENS record associated with the calling account. First updates the resolver to the default reverse resolver if necessary. name The name to set for this address. return The ENS node hash of the reverse record./
function setName(string memory name) public override returns (bytes32) { return setNameForAddr( msg.sender, msg.sender, address(defaultResolver), name ); }
4,198,037
// SPDX-License-Identifier: MIT /* First satirical on-chain generative text NFT about NFT firsts. Don't sleep on this historic collection. 0xdeafbeef 2021-09-06 */ /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } 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); } } } } pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity >=0.6.0 <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); } pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } pragma solidity >=0.6.0 <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); } pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry 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. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ /* library Strings { 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); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } */ pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { // using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; // using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @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 _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @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) { return (""); /* require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); */ } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @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 || ERC721.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 _tokenOwners.contains(tokenId); } /** * @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 || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `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); _holderTokens[to].add(tokenId); _tokenOwners.set(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); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @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"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /* function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } */ function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @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 { } } pragma solidity >=0.6.0 <0.8.0; /** * @dev {ERC721} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - token ID and URI autogeneration * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ /** * @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; } } contract First is ERC721,ReentrancyGuard { address admin_address; uint32 public num_minted; //after data is written and verified, lock() // can be called once to permanently lock the contract // (no further updates permitted) bool public locked; bool public paused; bytes[32] public t1; //text data //pointers to strings in t1 uint16[32][32] public p1; uint16[32] public n1; modifier requireAdmin() { require(admin_address == msg.sender,"Requires admin privileges"); _; } //transfers contract balance to GiveDirectly.org function donate() public payable requireAdmin { payable(0xc7464dbcA260A8faF033460622B23467Df5AEA42).transfer(address(this).balance); } function calc_pointers(uint16 cid) internal { uint16 k=0; p1[cid][k] = 0; for (uint i=0;i<t1[cid].length;i++) { if (t1[cid][i]=='|') { p1[cid][++k] = uint16(i+1); } } n1[cid] = k; } function owner() public view virtual returns (address) { return admin_address; } constructor() ERC721("First", "FIRST") { admin_address = msg.sender; paused = true; for (uint16 i=0;i<32;i++) { t1[i] = "||"; calc_pointers(i); } } /* Lock contract permanently, preventing any further writes */ function lock() public requireAdmin { locked=true; } //pause or unpause function setPaused(bool m) public requireAdmin { paused = m; } /* Returns randomly generated 'first' description, returning string */ function getString(uint256 id) public view returns (string memory) { return string(generate(id)); } /* Returns randomly generated 'first' description, returning bytes */ function generate(uint256 id) public view returns (bytes memory) { require(id > 0 && id < 1000000); //generate a sequence of 25 pseudo random numbers, seeded by id uint32[25] memory seq; uint256 r = id + 20000; uint16 sp = 0; for (uint i=0;i<25;i++) { r = r * 16807 % 2147483647; //advance PRNG seq[i] = uint32(r); } bytes memory h = "The first "; bytes memory NFT = "NFT "; bytes memory s = new bytes(512); //max length uint p = 0; uint16 o = 0; uint16 f = 0; uint16 slot = 0; for (uint i=0;i<h.length;i++) s[p++] = h[i]; f = uint16(seq[sp++] % 100); if (f < 50) { //qualifier 1 slot = 2; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; } f = uint16(seq[sp++] % 100); if (f < 32) { //generative art category slot = 4; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; bytes memory str = "generative "; for (uint i=0;i<str.length;i++) s[p++] = str[i]; uint16 f2 = uint16(seq[sp++] % 100); if (f2 < 50) { slot = 7; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; } slot = 10; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; } else if (f < 50) { //PFP uint16 f2 = uint16(seq[sp++] % 100); if (f2 < 50) { slot = 9; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; p--; bytes memory str = "-derivative "; for (uint i=0;i<str.length;i++) s[p++] = str[i]; } slot = 3; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; slot = 12; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; } else if (f < 54) { // 4% with none } else { //general category slot = 0; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; } for (uint i=0;i<NFT.length;i++) s[p++] = NFT[i]; f = uint16(seq[sp++] % 100); if (f < 50) { slot = 1; //which chain o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; } f = uint16(seq[sp++] % 110); if (f < 5) { //special stuff slot = 13; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; } else if (f < 15) { //featured in bytes memory str = "to be featured "; for (uint i=0;i<str.length;i++) s[p++] = str[i]; slot = 14; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; } else if (f < 23) { //action by a 'dao vote' slot = 22; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; slot = 26; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; } else if (f < 27) { // 4% with none } else if (f < 40) { //action by a person slot = 8; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; slot = 5; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; } else if (f < 50) { //airdropped bytes memory str = "to be airdropped to "; for (uint i=0;i<str.length;i++) s[p++] = str[i]; slot = 9; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; slot = 19; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; } else if (f < 60) { //stakable/burnable for x slot = 15; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; slot = 6; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; } else if (f < 63) { //redeemable for x bytes memory str = "redeemable "; for (uint i=0;i<str.length;i++) s[p++] = str[i]; slot = 25; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; } else if (f < 67) { //other special stuff slot = 27; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; } else if (f < 80) { //with on-chain slot = 16; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; slot = 17; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; slot = 18; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; } else if (f < 83) { //that changes over x slot = 20; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; slot = 21; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; } else if (f < 87) { //sold on an x price ramp bytes memory str = "to be sold "; for (uint i=0;i<str.length;i++) s[p++] = str[i]; slot = 23; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; } else if (f < 92) { //made using 100% programming language bytes memory str = "made entirely with "; for (uint i=0;i<str.length;i++) s[p++] = str[i]; slot = 24; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; } else if (f < 99) { //inspired by bytes memory str = "inspired by "; for (uint i=0;i<str.length;i++) s[p++] = str[i]; slot = 28; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; } else if (f < 110) { bytes memory str = "to be sold at "; for (uint i=0;i<str.length;i++) s[p++] = str[i]; slot = 11; o = uint16(seq[sp++] % n1[slot]); for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i]; uint16 f2 = uint16(seq[sp++] % 100); if (f2 < 20) { bytes memory str2 = "for a record price "; for (uint i=0;i<str2.length;i++) s[p++] = str2[i]; } else if (f2 < 40) { bytes memory str2 = "for a pittance "; for (uint i=0;i<str2.length;i++) s[p++] = str2[i]; } } s[p-1] = '.'; s[p] = '0'; bytes memory s2 = new bytes(p); for (uint i=0;i<p;i++) s2[i] = s[i]; return s2; } /* Upload a chunk of data */ function setT1(uint16 cid, string calldata s) public requireAdmin { require(!locked,"Can't change data after locked"); require(cid < 32); t1[cid] = bytes(s); calc_pointers(cid); } function tokenURI(uint256 tokenId) public view override returns (string memory) { string memory output = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: Courier New; font-size: 18px; }</style><rect width="100%" height="100%" fill="black" />'; uint256 j = 25; bytes memory b = generate(tokenId); //calculate word wrapping uint i = 0; uint e = 0; uint ll = 30; //max length of each line while (true) { e = i + ll; if (e >= b.length) { e = b.length; } else { while (b[e] != ' ' && e > i) { e--; } } //splice the line in bytes memory line = new bytes(e-i); for (uint k = i; k < e; k++) { line[k-i] = b[k]; } output = string(abi.encodePacked(output,'<text class="base" x="15" y = "',toString(j),'">',line,'</text>')); if (j > 200) break; j += 22; if (e >= b.length) break; //finished i = e + 1; } output = string(abi.encodePacked(output,'</svg>')); string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "First NFT #', toString(tokenId), '", "description": "First satirical on-chain generative text NFT about NFT firsts. Don\'t sleep on this historic collection.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } function claim(uint256 tokenId) public payable nonReentrant { require(!paused,"Currently paused"); require(!locked,"Can't mint after locked"); require(tokenId > 0 && tokenId < 1000000, "Token ID invalid"); require(num_minted < 5000,"All have been claimed."); uint price = 10000000000000000; //0.01 ETH require(msg.value>=10000000000000000, "Must send minimum value to purchase!"); _mint(_msgSender(), tokenId); num_minted++; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // 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); } } /// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <brecht@loopring.org> library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } }
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./ require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); }
6,280,745
./full_match/43114/0xA36D4b75AB5c4D655ec7ed099701De094b137A66/sources/MintFactory.sol
Recover ERC20 from contract tokenAddress token address tokenAmount amount to recover/
function recoverERC20( address tokenAddress, uint256 tokenAmount ) external onlyOwner { require(tokenAmount > 0, "recoverERC20: amount is 0"); IERC20(tokenAddress).safeTransfer(_owner, tokenAmount); emit Recovered(tokenAddress, tokenAmount); }
4,511,173
/** *Submitted for verification at Etherscan.io on 2021-02-02 */ // File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @bancor/token-governance/contracts/IClaimable.sol pragma solidity 0.6.12; /// @title Claimable contract interface interface IClaimable { function owner() external view returns (address); function transferOwnership(address newOwner) external; function acceptOwnership() external; } // File: @bancor/token-governance/contracts/IMintableToken.sol pragma solidity 0.6.12; /// @title Mintable Token interface interface IMintableToken is IERC20, IClaimable { function issue(address to, uint256 amount) external; function destroy(address from, uint256 amount) external; } // File: @bancor/token-governance/contracts/ITokenGovernance.sol pragma solidity 0.6.12; /// @title The interface for mintable/burnable token governance. interface ITokenGovernance { // The address of the mintable ERC20 token. function token() external view returns (IMintableToken); /// @dev Mints new tokens. /// /// @param to Account to receive the new amount. /// @param amount Amount to increase the supply by. /// function mint(address to, uint256 amount) external; /// @dev Burns tokens from the caller. /// /// @param amount Amount to decrease the supply by. /// function burn(uint256 amount) external; } // File: solidity/contracts/utility/interfaces/ICheckpointStore.sol pragma solidity 0.6.12; /** * @dev Checkpoint store contract interface */ interface ICheckpointStore { function addCheckpoint(address _address) external; function addPastCheckpoint(address _address, uint256 _time) external; function addPastCheckpoints(address[] calldata _addresses, uint256[] calldata _times) external; function checkpoint(address _address) external view returns (uint256); } // File: solidity/contracts/utility/MathEx.sol pragma solidity 0.6.12; /** * @dev This library provides a set of complex math operations. */ library MathEx { /** * @dev returns the largest integer smaller than or equal to the square root of a positive integer * * @param _num a positive integer * * @return the largest integer smaller than or equal to the square root of the positive integer */ function floorSqrt(uint256 _num) internal pure returns (uint256) { uint256 x = _num / 2 + 1; uint256 y = (x + _num / x) / 2; while (x > y) { x = y; y = (x + _num / x) / 2; } return x; } /** * @dev returns the smallest integer larger than or equal to the square root of a positive integer * * @param _num a positive integer * * @return the smallest integer larger than or equal to the square root of the positive integer */ function ceilSqrt(uint256 _num) internal pure returns (uint256) { uint256 x = floorSqrt(_num); return x * x == _num ? x : x + 1; } /** * @dev computes a reduced-scalar ratio * * @param _n ratio numerator * @param _d ratio denominator * @param _max maximum desired scalar * * @return ratio's numerator and denominator */ function reducedRatio( uint256 _n, uint256 _d, uint256 _max ) internal pure returns (uint256, uint256) { (uint256 n, uint256 d) = (_n, _d); if (n > _max || d > _max) { (n, d) = normalizedRatio(n, d, _max); } if (n != d) { return (n, d); } return (1, 1); } /** * @dev computes "scale * a / (a + b)" and "scale * b / (a + b)". */ function normalizedRatio( uint256 _a, uint256 _b, uint256 _scale ) internal pure returns (uint256, uint256) { if (_a <= _b) { return accurateRatio(_a, _b, _scale); } (uint256 y, uint256 x) = accurateRatio(_b, _a, _scale); return (x, y); } /** * @dev computes "scale * a / (a + b)" and "scale * b / (a + b)", assuming that "a <= b". */ function accurateRatio( uint256 _a, uint256 _b, uint256 _scale ) internal pure returns (uint256, uint256) { uint256 maxVal = uint256(-1) / _scale; if (_a > maxVal) { uint256 c = _a / (maxVal + 1) + 1; _a /= c; // we can now safely compute `_a * _scale` _b /= c; } if (_a != _b) { uint256 n = _a * _scale; uint256 d = _a + _b; // can overflow if (d >= _a) { // no overflow in `_a + _b` uint256 x = roundDiv(n, d); // we can now safely compute `_scale - x` uint256 y = _scale - x; return (x, y); } if (n < _b - (_b - _a) / 2) { return (0, _scale); // `_a * _scale < (_a + _b) / 2 < MAX_UINT256 < _a + _b` } return (1, _scale - 1); // `(_a + _b) / 2 < _a * _scale < MAX_UINT256 < _a + _b` } return (_scale / 2, _scale / 2); // allow reduction to `(1, 1)` in the calling function } /** * @dev computes the nearest integer to a given quotient without overflowing or underflowing. */ function roundDiv(uint256 _n, uint256 _d) internal pure returns (uint256) { return _n / _d + (_n % _d) / (_d - _d / 2); } /** * @dev returns the average number of decimal digits in a given list of positive integers * * @param _values list of positive integers * * @return the average number of decimal digits in the given list of positive integers */ function geometricMean(uint256[] memory _values) internal pure returns (uint256) { uint256 numOfDigits = 0; uint256 length = _values.length; for (uint256 i = 0; i < length; i++) { numOfDigits += decimalLength(_values[i]); } return uint256(10)**(roundDivUnsafe(numOfDigits, length) - 1); } /** * @dev returns the number of decimal digits in a given positive integer * * @param _x positive integer * * @return the number of decimal digits in the given positive integer */ function decimalLength(uint256 _x) internal pure returns (uint256) { uint256 y = 0; for (uint256 x = _x; x > 0; x /= 10) { y++; } return y; } /** * @dev returns the nearest integer to a given quotient * the computation is overflow-safe assuming that the input is sufficiently small * * @param _n quotient numerator * @param _d quotient denominator * * @return the nearest integer to the given quotient */ function roundDivUnsafe(uint256 _n, uint256 _d) internal pure returns (uint256) { return (_n + _d / 2) / _d; } /** * @dev returns the larger of two values * * @param _val1 the first value * @param _val2 the second value */ function max(uint256 _val1, uint256 _val2) internal pure returns (uint256) { return _val1 > _val2 ? _val1 : _val2; } } // File: solidity/contracts/utility/ReentrancyGuard.sol pragma solidity 0.6.12; /** * @dev This contract provides protection against calling a function * (directly or indirectly) from within itself. */ contract ReentrancyGuard { uint256 private constant UNLOCKED = 1; uint256 private constant LOCKED = 2; // LOCKED while protected code is being executed, UNLOCKED otherwise uint256 private state = UNLOCKED; /** * @dev ensures instantiation only by sub-contracts */ constructor() internal {} // protects a function against reentrancy attacks modifier protected() { _protected(); state = LOCKED; _; state = UNLOCKED; } // error message binary size optimization function _protected() internal view { require(state == UNLOCKED, "ERR_REENTRANCY"); } } // File: solidity/contracts/utility/interfaces/IOwned.sol pragma solidity 0.6.12; /* Owned contract interface */ interface IOwned { // this function isn't since the compiler emits automatically generated getter functions as external function owner() external view returns (address); function transferOwnership(address _newOwner) external; function acceptOwnership() external; } // File: solidity/contracts/utility/Owned.sol pragma solidity 0.6.12; /** * @dev This contract provides support and utilities for contract ownership. */ contract Owned is IOwned { address public override owner; address public newOwner; /** * @dev triggered when the owner is updated * * @param _prevOwner previous owner * @param _newOwner new owner */ event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** * @dev initializes a new Owned instance */ constructor() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { _ownerOnly(); _; } // error message binary size optimization function _ownerOnly() internal view { require(msg.sender == owner, "ERR_ACCESS_DENIED"); } /** * @dev allows transferring the contract ownership * the new owner still needs to accept the transfer * can only be called by the contract owner * * @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public override ownerOnly { require(_newOwner != owner, "ERR_SAME_OWNER"); newOwner = _newOwner; } /** * @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public override { require(msg.sender == newOwner, "ERR_ACCESS_DENIED"); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } // File: solidity/contracts/token/interfaces/IERC20Token.sol pragma solidity 0.6.12; /* ERC20 Standard Token interface */ interface IERC20Token { 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 (uint256); function balanceOf(address _owner) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function transferFrom( address _from, address _to, uint256 _value ) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); } // File: solidity/contracts/utility/TokenHandler.sol pragma solidity 0.6.12; contract TokenHandler { bytes4 private constant APPROVE_FUNC_SELECTOR = bytes4(keccak256("approve(address,uint256)")); bytes4 private constant TRANSFER_FUNC_SELECTOR = bytes4(keccak256("transfer(address,uint256)")); bytes4 private constant TRANSFER_FROM_FUNC_SELECTOR = bytes4(keccak256("transferFrom(address,address,uint256)")); /** * @dev executes the ERC20 token's `approve` function and reverts upon failure * the main purpose of this function is to prevent a non standard ERC20 token * from failing silently * * @param _token ERC20 token address * @param _spender approved address * @param _value allowance amount */ function safeApprove( IERC20Token _token, address _spender, uint256 _value ) internal { (bool success, bytes memory data) = address(_token).call( abi.encodeWithSelector(APPROVE_FUNC_SELECTOR, _spender, _value) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "ERR_APPROVE_FAILED"); } /** * @dev executes the ERC20 token's `transfer` function and reverts upon failure * the main purpose of this function is to prevent a non standard ERC20 token * from failing silently * * @param _token ERC20 token address * @param _to target address * @param _value transfer amount */ function safeTransfer( IERC20Token _token, address _to, uint256 _value ) internal { (bool success, bytes memory data) = address(_token).call( abi.encodeWithSelector(TRANSFER_FUNC_SELECTOR, _to, _value) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "ERR_TRANSFER_FAILED"); } /** * @dev executes the ERC20 token's `transferFrom` function and reverts upon failure * the main purpose of this function is to prevent a non standard ERC20 token * from failing silently * * @param _token ERC20 token address * @param _from source address * @param _to target address * @param _value transfer amount */ function safeTransferFrom( IERC20Token _token, address _from, address _to, uint256 _value ) internal { (bool success, bytes memory data) = address(_token).call( abi.encodeWithSelector(TRANSFER_FROM_FUNC_SELECTOR, _from, _to, _value) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "ERR_TRANSFER_FROM_FAILED"); } } // File: solidity/contracts/utility/Types.sol pragma solidity 0.6.12; /** * @dev This contract provides types which can be used by various contracts. */ struct Fraction { uint256 n; // numerator uint256 d; // denominator } // File: solidity/contracts/utility/Time.sol pragma solidity 0.6.12; /* Time implementing contract */ contract Time { /** * @dev returns the current time */ function time() internal view virtual returns (uint256) { return block.timestamp; } } // File: solidity/contracts/utility/Utils.sol pragma solidity 0.6.12; /** * @dev Utilities & Common Modifiers */ contract Utils { // verifies that a value is greater than zero modifier greaterThanZero(uint256 _value) { _greaterThanZero(_value); _; } // error message binary size optimization function _greaterThanZero(uint256 _value) internal pure { require(_value > 0, "ERR_ZERO_VALUE"); } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { _validAddress(_address); _; } // error message binary size optimization function _validAddress(address _address) internal pure { require(_address != address(0), "ERR_INVALID_ADDRESS"); } // verifies that the address is different than this contract address modifier notThis(address _address) { _notThis(_address); _; } // error message binary size optimization function _notThis(address _address) internal view { require(_address != address(this), "ERR_ADDRESS_IS_SELF"); } // validates an external address - currently only checks that it isn't null or this modifier validExternalAddress(address _address) { _validExternalAddress(_address); _; } // error message binary size optimization function _validExternalAddress(address _address) internal view { require(_address != address(0) && _address != address(this), "ERR_INVALID_EXTERNAL_ADDRESS"); } } // File: solidity/contracts/converter/interfaces/IConverterAnchor.sol pragma solidity 0.6.12; /* Converter Anchor interface */ interface IConverterAnchor is IOwned { } // File: solidity/contracts/token/interfaces/IDSToken.sol pragma solidity 0.6.12; /* DSToken interface */ interface IDSToken is IConverterAnchor, IERC20Token { function issue(address _to, uint256 _amount) external; function destroy(address _from, uint256 _amount) external; } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionStore.sol pragma solidity 0.6.12; /* Liquidity Protection Store interface */ interface ILiquidityProtectionStore is IOwned { function withdrawTokens( IERC20Token _token, address _to, uint256 _amount ) external; function protectedLiquidity(uint256 _id) external view returns ( address, IDSToken, IERC20Token, uint256, uint256, uint256, uint256, uint256 ); function addProtectedLiquidity( address _provider, IDSToken _poolToken, IERC20Token _reserveToken, uint256 _poolAmount, uint256 _reserveAmount, uint256 _reserveRateN, uint256 _reserveRateD, uint256 _timestamp ) external returns (uint256); function updateProtectedLiquidityAmounts( uint256 _id, uint256 _poolNewAmount, uint256 _reserveNewAmount ) external; function removeProtectedLiquidity(uint256 _id) external; function lockedBalance(address _provider, uint256 _index) external view returns (uint256, uint256); function lockedBalanceRange( address _provider, uint256 _startIndex, uint256 _endIndex ) external view returns (uint256[] memory, uint256[] memory); function addLockedBalance( address _provider, uint256 _reserveAmount, uint256 _expirationTime ) external returns (uint256); function removeLockedBalance(address _provider, uint256 _index) external; function systemBalance(IERC20Token _poolToken) external view returns (uint256); function incSystemBalance(IERC20Token _poolToken, uint256 _poolAmount) external; function decSystemBalance(IERC20Token _poolToken, uint256 _poolAmount) external; } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionStats.sol pragma solidity 0.6.12; /* Liquidity Protection Stats interface */ interface ILiquidityProtectionStats { function increaseTotalAmounts( address provider, IDSToken poolToken, IERC20Token reserveToken, uint256 poolAmount, uint256 reserveAmount ) external; function decreaseTotalAmounts( address provider, IDSToken poolToken, IERC20Token reserveToken, uint256 poolAmount, uint256 reserveAmount ) external; function addProviderPool(address provider, IDSToken poolToken) external returns (bool); function removeProviderPool(address provider, IDSToken poolToken) external returns (bool); function totalPoolAmount(IDSToken poolToken) external view returns (uint256); function totalReserveAmount(IDSToken poolToken, IERC20Token reserveToken) external view returns (uint256); function totalProviderAmount( address provider, IDSToken poolToken, IERC20Token reserveToken ) external view returns (uint256); function providerPools(address provider) external view returns (IDSToken[] memory); } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionSettings.sol pragma solidity 0.6.12; /* Liquidity Protection Store Settings interface */ interface ILiquidityProtectionSettings { function addPoolToWhitelist(IConverterAnchor _poolAnchor) external; function removePoolFromWhitelist(IConverterAnchor _poolAnchor) external; function isPoolWhitelisted(IConverterAnchor _poolAnchor) external view returns (bool); function poolWhitelist() external view returns (address[] memory); function isPoolSupported(IConverterAnchor _poolAnchor) external view returns (bool); function minNetworkTokenLiquidityForMinting() external view returns (uint256); function defaultNetworkTokenMintingLimit() external view returns (uint256); function networkTokenMintingLimits(IConverterAnchor _poolAnchor) external view returns (uint256); function networkTokensMinted(IConverterAnchor _poolAnchor) external view returns (uint256); function incNetworkTokensMinted(IConverterAnchor _poolAnchor, uint256 _amount) external; function decNetworkTokensMinted(IConverterAnchor _poolAnchor, uint256 _amount) external; function minProtectionDelay() external view returns (uint256); function maxProtectionDelay() external view returns (uint256); function setProtectionDelays(uint256 _minProtectionDelay, uint256 _maxProtectionDelay) external; function minNetworkCompensation() external view returns (uint256); function setMinNetworkCompensation(uint256 _minCompensation) external; function lockDuration() external view returns (uint256); function setLockDuration(uint256 _lockDuration) external; function averageRateMaxDeviation() external view returns (uint32); function setAverageRateMaxDeviation(uint32 _averageRateMaxDeviation) external; } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionSystemStore.sol pragma solidity 0.6.12; /* Liquidity Protection System Store interface */ interface ILiquidityProtectionSystemStore { function systemBalance(IERC20Token poolToken) external view returns (uint256); function incSystemBalance(IERC20Token poolToken, uint256 poolAmount) external; function decSystemBalance(IERC20Token poolToken, uint256 poolAmount) external; function networkTokensMinted(IConverterAnchor poolAnchor) external view returns (uint256); function incNetworkTokensMinted(IConverterAnchor poolAnchor, uint256 amount) external; function decNetworkTokensMinted(IConverterAnchor poolAnchor, uint256 amount) external; } // File: solidity/contracts/utility/interfaces/ITokenHolder.sol pragma solidity 0.6.12; /* Token Holder interface */ interface ITokenHolder is IOwned { function withdrawTokens( IERC20Token _token, address _to, uint256 _amount ) external; } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtection.sol pragma solidity 0.6.12; /* Liquidity Protection interface */ interface ILiquidityProtection { function store() external view returns (ILiquidityProtectionStore); function stats() external view returns (ILiquidityProtectionStats); function settings() external view returns (ILiquidityProtectionSettings); function systemStore() external view returns (ILiquidityProtectionSystemStore); function wallet() external view returns (ITokenHolder); function addLiquidityFor( address owner, IConverterAnchor poolAnchor, IERC20Token reserveToken, uint256 amount ) external payable returns (uint256); function addLiquidity( IConverterAnchor poolAnchor, IERC20Token reserveToken, uint256 amount ) external payable returns (uint256); function removeLiquidity(uint256 id, uint32 portion) external; } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionEventsSubscriber.sol pragma solidity 0.6.12; /** * @dev Liquidity protection events subscriber interface */ interface ILiquidityProtectionEventsSubscriber { function onAddingLiquidity( address provider, IConverterAnchor poolAnchor, IERC20Token reserveToken, uint256 poolAmount, uint256 reserveAmount ) external; function onRemovingLiquidity( uint256 id, address provider, IConverterAnchor poolAnchor, IERC20Token reserveToken, uint256 poolAmount, uint256 reserveAmount ) external; } // File: solidity/contracts/converter/interfaces/IConverter.sol pragma solidity 0.6.12; /* Converter interface */ interface IConverter is IOwned { function converterType() external pure returns (uint16); function anchor() external view returns (IConverterAnchor); function isActive() external view returns (bool); function targetAmountAndFee( IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount ) external view returns (uint256, uint256); function convert( IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, address _trader, address payable _beneficiary ) external payable returns (uint256); function conversionFee() external view returns (uint32); function maxConversionFee() external view returns (uint32); function reserveBalance(IERC20Token _reserveToken) external view returns (uint256); receive() external payable; function transferAnchorOwnership(address _newOwner) external; function acceptAnchorOwnership() external; function setConversionFee(uint32 _conversionFee) external; function withdrawTokens( IERC20Token _token, address _to, uint256 _amount ) external; function withdrawETH(address payable _to) external; function addReserve(IERC20Token _token, uint32 _ratio) external; // deprecated, backward compatibility function token() external view returns (IConverterAnchor); function transferTokenOwnership(address _newOwner) external; function acceptTokenOwnership() external; function connectors(IERC20Token _address) external view returns ( uint256, uint32, bool, bool, bool ); function getConnectorBalance(IERC20Token _connectorToken) external view returns (uint256); function connectorTokens(uint256 _index) external view returns (IERC20Token); function connectorTokenCount() external view returns (uint16); /** * @dev triggered when the converter is activated * * @param _type converter type * @param _anchor converter anchor * @param _activated true if the converter was activated, false if it was deactivated */ event Activation(uint16 indexed _type, IConverterAnchor indexed _anchor, bool indexed _activated); /** * @dev triggered when a conversion between two tokens occurs * * @param _fromToken source ERC20 token * @param _toToken target ERC20 token * @param _trader wallet that initiated the trade * @param _amount input amount in units of the source token * @param _return output amount minus conversion fee in units of the target token * @param _conversionFee conversion fee in units of the target token */ event Conversion( IERC20Token indexed _fromToken, IERC20Token indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return, int256 _conversionFee ); /** * @dev triggered when the rate between two tokens in the converter changes * note that the event might be dispatched for rate updates between any two tokens in the converter * * @param _token1 address of the first token * @param _token2 address of the second token * @param _rateN rate of 1 unit of `_token1` in `_token2` (numerator) * @param _rateD rate of 1 unit of `_token1` in `_token2` (denominator) */ event TokenRateUpdate(IERC20Token indexed _token1, IERC20Token indexed _token2, uint256 _rateN, uint256 _rateD); /** * @dev triggered when the conversion fee is updated * * @param _prevFee previous fee percentage, represented in ppm * @param _newFee new fee percentage, represented in ppm */ event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee); } // File: solidity/contracts/converter/interfaces/IConverterRegistry.sol pragma solidity 0.6.12; interface IConverterRegistry { function getAnchorCount() external view returns (uint256); function getAnchors() external view returns (address[] memory); function getAnchor(uint256 _index) external view returns (IConverterAnchor); function isAnchor(address _value) external view returns (bool); function getLiquidityPoolCount() external view returns (uint256); function getLiquidityPools() external view returns (address[] memory); function getLiquidityPool(uint256 _index) external view returns (IConverterAnchor); function isLiquidityPool(address _value) external view returns (bool); function getConvertibleTokenCount() external view returns (uint256); function getConvertibleTokens() external view returns (address[] memory); function getConvertibleToken(uint256 _index) external view returns (IERC20Token); function isConvertibleToken(address _value) external view returns (bool); function getConvertibleTokenAnchorCount(IERC20Token _convertibleToken) external view returns (uint256); function getConvertibleTokenAnchors(IERC20Token _convertibleToken) external view returns (address[] memory); function getConvertibleTokenAnchor(IERC20Token _convertibleToken, uint256 _index) external view returns (IConverterAnchor); function isConvertibleTokenAnchor(IERC20Token _convertibleToken, address _value) external view returns (bool); } // File: solidity/contracts/liquidity-protection/LiquidityProtection.sol pragma solidity 0.6.12; interface ILiquidityPoolConverter is IConverter { function addLiquidity( IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _minReturn ) external payable; function removeLiquidity( uint256 _amount, IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts ) external; function recentAverageRate(IERC20Token _reserveToken) external view returns (uint256, uint256); } /** * @dev This contract implements the liquidity protection mechanism. */ contract LiquidityProtection is ILiquidityProtection, TokenHandler, Utils, Owned, ReentrancyGuard, Time { using SafeMath for uint256; using MathEx for *; struct ProtectedLiquidity { address provider; // liquidity provider IDSToken poolToken; // pool token address IERC20Token reserveToken; // reserve token address uint256 poolAmount; // pool token amount uint256 reserveAmount; // reserve token amount uint256 reserveRateN; // rate of 1 protected reserve token in units of the other reserve token (numerator) uint256 reserveRateD; // rate of 1 protected reserve token in units of the other reserve token (denominator) uint256 timestamp; // timestamp } // various rates between the two reserve tokens. the rate is of 1 unit of the protected reserve token in units of the other reserve token struct PackedRates { uint128 addSpotRateN; // spot rate of 1 A in units of B when liquidity was added (numerator) uint128 addSpotRateD; // spot rate of 1 A in units of B when liquidity was added (denominator) uint128 removeSpotRateN; // spot rate of 1 A in units of B when liquidity is removed (numerator) uint128 removeSpotRateD; // spot rate of 1 A in units of B when liquidity is removed (denominator) uint128 removeAverageRateN; // average rate of 1 A in units of B when liquidity is removed (numerator) uint128 removeAverageRateD; // average rate of 1 A in units of B when liquidity is removed (denominator) } IERC20Token internal constant ETH_RESERVE_ADDRESS = IERC20Token(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); uint32 internal constant PPM_RESOLUTION = 1000000; uint256 internal constant MAX_UINT128 = 2**128 - 1; uint256 internal constant MAX_UINT256 = uint256(-1); ILiquidityProtectionSettings public immutable override settings; ILiquidityProtectionStore public immutable override store; ILiquidityProtectionStats public immutable override stats; ILiquidityProtectionSystemStore public immutable override systemStore; ITokenHolder public immutable override wallet; IERC20Token public immutable networkToken; ITokenGovernance public immutable networkTokenGovernance; IERC20Token public immutable govToken; ITokenGovernance public immutable govTokenGovernance; ICheckpointStore public immutable lastRemoveCheckpointStore; ILiquidityProtectionEventsSubscriber public eventsSubscriber; // true if the contract is currently adding/removing liquidity from a converter, used for accepting ETH bool private updatingLiquidity = false; /** * @dev updates the event subscriber * * @param _prevEventsSubscriber the previous events subscriber * @param _newEventsSubscriber the new events subscriber */ event EventSubscriberUpdated( ILiquidityProtectionEventsSubscriber indexed _prevEventsSubscriber, ILiquidityProtectionEventsSubscriber indexed _newEventsSubscriber ); /** * @dev initializes a new LiquidityProtection contract * * @param _contractAddresses: * - [0] liquidity protection settings * - [1] liquidity protection store * - [2] liquidity protection stats * - [3] liquidity protection system store * - [4] liquidity protection wallet * - [5] network token governance * - [6] governance token governance * - [7] last liquidity removal/unprotection checkpoints store */ constructor(address[8] memory _contractAddresses) public { for (uint256 i = 0; i < _contractAddresses.length; i++) { _validAddress(_contractAddresses[i]); } settings = ILiquidityProtectionSettings(_contractAddresses[0]); store = ILiquidityProtectionStore(_contractAddresses[1]); stats = ILiquidityProtectionStats(_contractAddresses[2]); systemStore = ILiquidityProtectionSystemStore(_contractAddresses[3]); wallet = ITokenHolder(_contractAddresses[4]); networkTokenGovernance = ITokenGovernance(_contractAddresses[5]); govTokenGovernance = ITokenGovernance(_contractAddresses[6]); lastRemoveCheckpointStore = ICheckpointStore(_contractAddresses[7]); networkToken = IERC20Token(address(ITokenGovernance(_contractAddresses[5]).token())); govToken = IERC20Token(address(ITokenGovernance(_contractAddresses[6]).token())); } // ensures that the contract is currently removing liquidity from a converter modifier updatingLiquidityOnly() { require(updatingLiquidity, "ERR_NOT_UPDATING_LIQUIDITY"); _; } // ensures that the portion is valid modifier validPortion(uint32 _portion) { _validPortion(_portion); _; } // error message binary size optimization function _validPortion(uint32 _portion) internal pure { require(_portion > 0 && _portion <= PPM_RESOLUTION, "ERR_INVALID_PORTION"); } // ensures that the pool is supported and whitelisted modifier poolSupportedAndWhitelisted(IConverterAnchor _poolAnchor) { _poolSupported(_poolAnchor); _poolWhitelisted(_poolAnchor); _; } // error message binary size optimization function _poolSupported(IConverterAnchor _poolAnchor) internal view { require(settings.isPoolSupported(_poolAnchor), "ERR_POOL_NOT_SUPPORTED"); } // error message binary size optimization function _poolWhitelisted(IConverterAnchor _poolAnchor) internal view { require(settings.isPoolWhitelisted(_poolAnchor), "ERR_POOL_NOT_WHITELISTED"); } // error message binary size optimization function verifyEthAmount(uint256 _value) internal view { require(msg.value == _value, "ERR_ETH_AMOUNT_MISMATCH"); } /** * @dev accept ETH * used when removing liquidity from ETH converters */ receive() external payable updatingLiquidityOnly() {} /** * @dev transfers the ownership of the store * can only be called by the contract owner * * @param _newOwner the new owner of the store */ function transferStoreOwnership(address _newOwner) external ownerOnly { store.transferOwnership(_newOwner); } /** * @dev accepts the ownership of the store * can only be called by the contract owner */ function acceptStoreOwnership() external ownerOnly { store.acceptOwnership(); } /** * @dev transfers the ownership of the wallet * can only be called by the contract owner * * @param _newOwner the new owner of the wallet */ function transferWalletOwnership(address _newOwner) external ownerOnly { wallet.transferOwnership(_newOwner); } /** * @dev accepts the ownership of the wallet * can only be called by the contract owner */ function acceptWalletOwnership() external ownerOnly { wallet.acceptOwnership(); } /** * @dev migrates all funds from the store to the wallet * @dev migrates system balances from the store to the system-store * @dev migrates minted amounts from the settings to the system-store */ function migrateData() external { // save local copies of storage variables address storeAddress = address(store); address walletAddress = address(wallet); IERC20Token networkTokenLocal = networkToken; address[] memory poolWhitelist = settings.poolWhitelist(); for (uint256 i = 0; i < poolWhitelist.length; i++) { IERC20Token poolToken = IERC20Token(poolWhitelist[i]); store.withdrawTokens(poolToken, walletAddress, poolToken.balanceOf(storeAddress)); uint256 systemBalance = store.systemBalance(poolToken); systemStore.incSystemBalance(poolToken, systemBalance); store.decSystemBalance(poolToken, systemBalance); uint256 networkTokensMinted = settings.networkTokensMinted(IConverterAnchor(address(poolToken))); systemStore.incNetworkTokensMinted(IConverterAnchor(address(poolToken)), networkTokensMinted); settings.decNetworkTokensMinted(IConverterAnchor(address(poolToken)), networkTokensMinted); } store.withdrawTokens(networkTokenLocal, walletAddress, networkTokenLocal.balanceOf(storeAddress)); } /** * @dev sets the events subscriber */ function setEventsSubscriber(ILiquidityProtectionEventsSubscriber _eventsSubscriber) external ownerOnly validAddress(address(_eventsSubscriber)) notThis(address(_eventsSubscriber)) { emit EventSubscriberUpdated(eventsSubscriber, _eventsSubscriber); eventsSubscriber = _eventsSubscriber; } /** * @dev adds protected liquidity to a pool for a specific recipient * also mints new governance tokens for the caller if the caller adds network tokens * * @param _owner protected liquidity owner * @param _poolAnchor anchor of the pool * @param _reserveToken reserve token to add to the pool * @param _amount amount of tokens to add to the pool * @return new protected liquidity id */ function addLiquidityFor( address _owner, IConverterAnchor _poolAnchor, IERC20Token _reserveToken, uint256 _amount ) external payable override protected validAddress(_owner) poolSupportedAndWhitelisted(_poolAnchor) greaterThanZero(_amount) returns (uint256) { return addLiquidity(_owner, _poolAnchor, _reserveToken, _amount); } /** * @dev adds protected liquidity to a pool * also mints new governance tokens for the caller if the caller adds network tokens * * @param _poolAnchor anchor of the pool * @param _reserveToken reserve token to add to the pool * @param _amount amount of tokens to add to the pool * @return new protected liquidity id */ function addLiquidity( IConverterAnchor _poolAnchor, IERC20Token _reserveToken, uint256 _amount ) external payable override protected poolSupportedAndWhitelisted(_poolAnchor) greaterThanZero(_amount) returns (uint256) { return addLiquidity(msg.sender, _poolAnchor, _reserveToken, _amount); } /** * @dev adds protected liquidity to a pool for a specific recipient * also mints new governance tokens for the caller if the caller adds network tokens * * @param _owner protected liquidity owner * @param _poolAnchor anchor of the pool * @param _reserveToken reserve token to add to the pool * @param _amount amount of tokens to add to the pool * @return new protected liquidity id */ function addLiquidity( address _owner, IConverterAnchor _poolAnchor, IERC20Token _reserveToken, uint256 _amount ) private returns (uint256) { // save a local copy of `networkToken` IERC20Token networkTokenLocal = networkToken; if (_reserveToken == networkTokenLocal) { verifyEthAmount(0); return addNetworkTokenLiquidity(_owner, _poolAnchor, networkTokenLocal, _amount); } // verify that ETH was passed with the call if needed verifyEthAmount(_reserveToken == ETH_RESERVE_ADDRESS ? _amount : 0); return addBaseTokenLiquidity(_owner, _poolAnchor, _reserveToken, networkTokenLocal, _amount); } /** * @dev adds protected network token liquidity to a pool * also mints new governance tokens for the caller * * @param _owner protected liquidity owner * @param _poolAnchor anchor of the pool * @param _networkToken the network reserve token of the pool * @param _amount amount of tokens to add to the pool * @return new protected liquidity id */ function addNetworkTokenLiquidity( address _owner, IConverterAnchor _poolAnchor, IERC20Token _networkToken, uint256 _amount ) internal returns (uint256) { IDSToken poolToken = IDSToken(address(_poolAnchor)); // get the rate between the pool token and the reserve Fraction memory poolRate = poolTokenRate(poolToken, _networkToken); // calculate the amount of pool tokens based on the amount of reserve tokens uint256 poolTokenAmount = _amount.mul(poolRate.d).div(poolRate.n); // remove the pool tokens from the system's ownership (will revert if not enough tokens are available) systemStore.decSystemBalance(poolToken, poolTokenAmount); // add protected liquidity for the recipient uint256 id = addProtectedLiquidity(_owner, poolToken, _networkToken, poolTokenAmount, _amount); // burns the network tokens from the caller. we need to transfer the tokens to the contract itself, since only // token holders can burn their tokens safeTransferFrom(_networkToken, msg.sender, address(this), _amount); burnNetworkTokens(_poolAnchor, _amount); // mint governance tokens to the recipient govTokenGovernance.mint(_owner, _amount); return id; } /** * @dev adds protected base token liquidity to a pool * * @param _owner protected liquidity owner * @param _poolAnchor anchor of the pool * @param _baseToken the base reserve token of the pool * @param _networkToken the network reserve token of the pool * @param _amount amount of tokens to add to the pool * @return new protected liquidity id */ function addBaseTokenLiquidity( address _owner, IConverterAnchor _poolAnchor, IERC20Token _baseToken, IERC20Token _networkToken, uint256 _amount ) internal returns (uint256) { IDSToken poolToken = IDSToken(address(_poolAnchor)); // get the reserve balances ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolAnchor))); (uint256 reserveBalanceBase, uint256 reserveBalanceNetwork) = converterReserveBalances(converter, _baseToken, _networkToken); require(reserveBalanceNetwork >= settings.minNetworkTokenLiquidityForMinting(), "ERR_NOT_ENOUGH_LIQUIDITY"); // calculate and mint the required amount of network tokens for adding liquidity uint256 newNetworkLiquidityAmount = _amount.mul(reserveBalanceNetwork).div(reserveBalanceBase); // verify network token minting limit uint256 mintingLimit = settings.networkTokenMintingLimits(_poolAnchor); if (mintingLimit == 0) { mintingLimit = settings.defaultNetworkTokenMintingLimit(); } uint256 newNetworkTokensMinted = systemStore.networkTokensMinted(_poolAnchor).add(newNetworkLiquidityAmount); require(newNetworkTokensMinted <= mintingLimit, "ERR_MAX_AMOUNT_REACHED"); // issue new network tokens to the system mintNetworkTokens(address(this), _poolAnchor, newNetworkLiquidityAmount); // transfer the base tokens from the caller and approve the converter ensureAllowance(_networkToken, address(converter), newNetworkLiquidityAmount); if (_baseToken != ETH_RESERVE_ADDRESS) { safeTransferFrom(_baseToken, msg.sender, address(this), _amount); ensureAllowance(_baseToken, address(converter), _amount); } // add liquidity addLiquidity(converter, _baseToken, _networkToken, _amount, newNetworkLiquidityAmount, msg.value); // transfer the new pool tokens to the wallet uint256 poolTokenAmount = poolToken.balanceOf(address(this)); safeTransfer(poolToken, address(wallet), poolTokenAmount); // the system splits the pool tokens with the caller // increase the system's pool token balance and add protected liquidity for the caller systemStore.incSystemBalance(poolToken, poolTokenAmount - poolTokenAmount / 2); // account for rounding errors return addProtectedLiquidity(_owner, poolToken, _baseToken, poolTokenAmount / 2, _amount); } /** * @dev returns the single-side staking limits of a given pool * * @param _poolAnchor anchor of the pool * @return maximum amount of base tokens that can be single-side staked in the pool * @return maximum amount of network tokens that can be single-side staked in the pool */ function poolAvailableSpace(IConverterAnchor _poolAnchor) external view poolSupportedAndWhitelisted(_poolAnchor) returns (uint256, uint256) { IERC20Token networkTokenLocal = networkToken; return ( baseTokenAvailableSpace(_poolAnchor, networkTokenLocal), networkTokenAvailableSpace(_poolAnchor, networkTokenLocal) ); } /** * @dev returns the base-token staking limits of a given pool * * @param _poolAnchor anchor of the pool * @return maximum amount of base tokens that can be single-side staked in the pool */ function baseTokenAvailableSpace(IConverterAnchor _poolAnchor) external view poolSupportedAndWhitelisted(_poolAnchor) returns (uint256) { return baseTokenAvailableSpace(_poolAnchor, networkToken); } /** * @dev returns the network-token staking limits of a given pool * * @param _poolAnchor anchor of the pool * @return maximum amount of network tokens that can be single-side staked in the pool */ function networkTokenAvailableSpace(IConverterAnchor _poolAnchor) external view poolSupportedAndWhitelisted(_poolAnchor) returns (uint256) { return networkTokenAvailableSpace(_poolAnchor, networkToken); } /** * @dev returns the base-token staking limits of a given pool * * @param _poolAnchor anchor of the pool * @param _networkToken the network token * @return maximum amount of base tokens that can be single-side staked in the pool */ function baseTokenAvailableSpace(IConverterAnchor _poolAnchor, IERC20Token _networkToken) internal view returns (uint256) { // get the pool converter ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolAnchor))); // get the base token IERC20Token baseToken = converterOtherReserve(converter, _networkToken); // get the reserve balances (uint256 reserveBalanceBase, uint256 reserveBalanceNetwork) = converterReserveBalances(converter, baseToken, _networkToken); // get the network token minting limit uint256 mintingLimit = settings.networkTokenMintingLimits(_poolAnchor); if (mintingLimit == 0) { mintingLimit = settings.defaultNetworkTokenMintingLimit(); } // get the amount of network tokens already minted for the pool uint256 networkTokensMinted = systemStore.networkTokensMinted(_poolAnchor); // get the amount of network tokens which can minted for the pool uint256 networkTokensCanBeMinted = MathEx.max(mintingLimit, networkTokensMinted) - networkTokensMinted; // return the maximum amount of base token liquidity that can be single-sided staked in the pool return networkTokensCanBeMinted.mul(reserveBalanceBase).div(reserveBalanceNetwork); } /** * @dev returns the network-token staking limits of a given pool * * @param _poolAnchor anchor of the pool * @param _networkToken the network token * @return maximum amount of network tokens that can be single-side staked in the pool */ function networkTokenAvailableSpace(IConverterAnchor _poolAnchor, IERC20Token _networkToken) internal view returns (uint256) { // get the pool token IDSToken poolToken = IDSToken(address(_poolAnchor)); // get the pool token rate Fraction memory poolRate = poolTokenRate(poolToken, _networkToken); // return the maximum amount of network token liquidity that can be single-sided staked in the pool return systemStore.systemBalance(poolToken).mul(poolRate.n).add(poolRate.n).sub(1).div(poolRate.d); } /** * @dev returns the expected/actual amounts the provider will receive for removing liquidity * it's also possible to provide the remove liquidity time to get an estimation * for the return at that given point * * @param _id protected liquidity id * @param _portion portion of liquidity to remove, in PPM * @param _removeTimestamp time at which the liquidity is removed * @return expected return amount in the reserve token * @return actual return amount in the reserve token * @return compensation in the network token */ function removeLiquidityReturn( uint256 _id, uint32 _portion, uint256 _removeTimestamp ) external view validPortion(_portion) returns ( uint256, uint256, uint256 ) { ProtectedLiquidity memory liquidity = protectedLiquidity(_id); // verify input require(liquidity.provider != address(0), "ERR_INVALID_ID"); require(_removeTimestamp >= liquidity.timestamp, "ERR_INVALID_TIMESTAMP"); // calculate the portion of the liquidity to remove if (_portion != PPM_RESOLUTION) { liquidity.poolAmount = liquidity.poolAmount.mul(_portion) / PPM_RESOLUTION; liquidity.reserveAmount = liquidity.reserveAmount.mul(_portion) / PPM_RESOLUTION; } // get the various rates between the reserves upon adding liquidity and now PackedRates memory packedRates = packRates( liquidity.poolToken, liquidity.reserveToken, liquidity.reserveRateN, liquidity.reserveRateD, false ); uint256 targetAmount = removeLiquidityTargetAmount( liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount, packedRates, liquidity.timestamp, _removeTimestamp ); // for network token, the return amount is identical to the target amount if (liquidity.reserveToken == networkToken) { return (targetAmount, targetAmount, 0); } // handle base token return // calculate the amount of pool tokens required for liquidation // note that the amount is doubled since it's not possible to liquidate one reserve only Fraction memory poolRate = poolTokenRate(liquidity.poolToken, liquidity.reserveToken); uint256 poolAmount = targetAmount.mul(poolRate.d).div(poolRate.n / 2); // limit the amount of pool tokens by the amount the system/caller holds uint256 availableBalance = systemStore.systemBalance(liquidity.poolToken).add(liquidity.poolAmount); poolAmount = poolAmount > availableBalance ? availableBalance : poolAmount; // calculate the base token amount received by liquidating the pool tokens // note that the amount is divided by 2 since the pool amount represents both reserves uint256 baseAmount = poolAmount.mul(poolRate.n / 2).div(poolRate.d); uint256 networkAmount = getNetworkCompensation(targetAmount, baseAmount, packedRates); return (targetAmount, baseAmount, networkAmount); } /** * @dev removes protected liquidity from a pool * also burns governance tokens from the caller if the caller removes network tokens * * @param _id id in the caller's list of protected liquidity * @param _portion portion of liquidity to remove, in PPM */ function removeLiquidity(uint256 _id, uint32 _portion) external override protected validPortion(_portion) { removeLiquidity(msg.sender, _id, _portion); } /** * @dev removes protected liquidity from a pool * also burns governance tokens from the caller if the caller removes network tokens * * @param _provider protected liquidity provider * @param _id id in the caller's list of protected liquidity * @param _portion portion of liquidity to remove, in PPM */ function removeLiquidity( address payable _provider, uint256 _id, uint32 _portion ) internal { ProtectedLiquidity memory liquidity = protectedLiquidity(_id, _provider); // save a local copy of `networkToken` IERC20Token networkTokenLocal = networkToken; // verify that the pool is whitelisted _poolWhitelisted(liquidity.poolToken); // verify that the protected liquidity is not removed on the same block in which it was added require(liquidity.timestamp < time(), "ERR_TOO_EARLY"); if (_portion == PPM_RESOLUTION) { // notify event subscribers if (address(eventsSubscriber) != address(0)) { eventsSubscriber.onRemovingLiquidity( _id, _provider, liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount ); } // remove the protected liquidity from the provider store.removeProtectedLiquidity(_id); } else { // remove a portion of the protected liquidity from the provider uint256 fullPoolAmount = liquidity.poolAmount; uint256 fullReserveAmount = liquidity.reserveAmount; liquidity.poolAmount = liquidity.poolAmount.mul(_portion) / PPM_RESOLUTION; liquidity.reserveAmount = liquidity.reserveAmount.mul(_portion) / PPM_RESOLUTION; // notify event subscribers if (address(eventsSubscriber) != address(0)) { eventsSubscriber.onRemovingLiquidity( _id, _provider, liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount ); } store.updateProtectedLiquidityAmounts( _id, fullPoolAmount - liquidity.poolAmount, fullReserveAmount - liquidity.reserveAmount ); } // update the statistics stats.decreaseTotalAmounts( liquidity.provider, liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount ); // update last liquidity removal checkpoint lastRemoveCheckpointStore.addCheckpoint(_provider); // add the pool tokens to the system systemStore.incSystemBalance(liquidity.poolToken, liquidity.poolAmount); // if removing network token liquidity, burn the governance tokens from the caller. we need to transfer the // tokens to the contract itself, since only token holders can burn their tokens if (liquidity.reserveToken == networkTokenLocal) { safeTransferFrom(govToken, _provider, address(this), liquidity.reserveAmount); govTokenGovernance.burn(liquidity.reserveAmount); } // get the various rates between the reserves upon adding liquidity and now PackedRates memory packedRates = packRates( liquidity.poolToken, liquidity.reserveToken, liquidity.reserveRateN, liquidity.reserveRateD, true ); // get the target token amount uint256 targetAmount = removeLiquidityTargetAmount( liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount, packedRates, liquidity.timestamp, time() ); // remove network token liquidity if (liquidity.reserveToken == networkTokenLocal) { // mint network tokens for the caller and lock them mintNetworkTokens(address(wallet), liquidity.poolToken, targetAmount); lockTokens(_provider, targetAmount); return; } // remove base token liquidity // calculate the amount of pool tokens required for liquidation // note that the amount is doubled since it's not possible to liquidate one reserve only Fraction memory poolRate = poolTokenRate(liquidity.poolToken, liquidity.reserveToken); uint256 poolAmount = targetAmount.mul(poolRate.d).div(poolRate.n / 2); // limit the amount of pool tokens by the amount the system holds uint256 systemBalance = systemStore.systemBalance(liquidity.poolToken); poolAmount = poolAmount > systemBalance ? systemBalance : poolAmount; // withdraw the pool tokens from the wallet systemStore.decSystemBalance(liquidity.poolToken, poolAmount); wallet.withdrawTokens(liquidity.poolToken, address(this), poolAmount); // remove liquidity removeLiquidity(liquidity.poolToken, poolAmount, liquidity.reserveToken, networkTokenLocal); // transfer the base tokens to the caller uint256 baseBalance; if (liquidity.reserveToken == ETH_RESERVE_ADDRESS) { baseBalance = address(this).balance; _provider.transfer(baseBalance); } else { baseBalance = liquidity.reserveToken.balanceOf(address(this)); safeTransfer(liquidity.reserveToken, _provider, baseBalance); } // compensate the caller with network tokens if still needed uint256 delta = getNetworkCompensation(targetAmount, baseBalance, packedRates); if (delta > 0) { // check if there's enough network token balance, otherwise mint more uint256 networkBalance = networkTokenLocal.balanceOf(address(this)); if (networkBalance < delta) { networkTokenGovernance.mint(address(this), delta - networkBalance); } // lock network tokens for the caller safeTransfer(networkTokenLocal, address(wallet), delta); lockTokens(_provider, delta); } // if the contract still holds network tokens, burn them uint256 networkBalance = networkTokenLocal.balanceOf(address(this)); if (networkBalance > 0) { burnNetworkTokens(liquidity.poolToken, networkBalance); } } /** * @dev returns the amount the provider will receive for removing liquidity * it's also possible to provide the remove liquidity rate & time to get an estimation * for the return at that given point * * @param _poolToken pool token * @param _reserveToken reserve token * @param _poolAmount pool token amount when the liquidity was added * @param _reserveAmount reserve token amount that was added * @param _packedRates see `struct PackedRates` * @param _addTimestamp time at which the liquidity was added * @param _removeTimestamp time at which the liquidity is removed * @return amount received for removing liquidity */ function removeLiquidityTargetAmount( IDSToken _poolToken, IERC20Token _reserveToken, uint256 _poolAmount, uint256 _reserveAmount, PackedRates memory _packedRates, uint256 _addTimestamp, uint256 _removeTimestamp ) internal view returns (uint256) { // get the rate between the pool token and the reserve token Fraction memory poolRate = poolTokenRate(_poolToken, _reserveToken); // get the rate between the reserves upon adding liquidity and now Fraction memory addSpotRate = Fraction({ n: _packedRates.addSpotRateN, d: _packedRates.addSpotRateD }); Fraction memory removeSpotRate = Fraction({ n: _packedRates.removeSpotRateN, d: _packedRates.removeSpotRateD }); Fraction memory removeAverageRate = Fraction({ n: _packedRates.removeAverageRateN, d: _packedRates.removeAverageRateD }); // calculate the protected amount of reserve tokens plus accumulated fee before compensation uint256 total = protectedAmountPlusFee(_poolAmount, poolRate, addSpotRate, removeSpotRate); // calculate the impermanent loss Fraction memory loss = impLoss(addSpotRate, removeAverageRate); // calculate the protection level Fraction memory level = protectionLevel(_addTimestamp, _removeTimestamp); // calculate the compensation amount return compensationAmount(_reserveAmount, MathEx.max(_reserveAmount, total), loss, level); } /** * @dev allows the caller to claim network token balance that is no longer locked * note that the function can revert if the range is too large * * @param _startIndex start index in the caller's list of locked balances * @param _endIndex end index in the caller's list of locked balances (exclusive) */ function claimBalance(uint256 _startIndex, uint256 _endIndex) external protected { // get the locked balances from the store (uint256[] memory amounts, uint256[] memory expirationTimes) = store.lockedBalanceRange(msg.sender, _startIndex, _endIndex); uint256 totalAmount = 0; uint256 length = amounts.length; assert(length == expirationTimes.length); // reverse iteration since we're removing from the list for (uint256 i = length; i > 0; i--) { uint256 index = i - 1; if (expirationTimes[index] > time()) { continue; } // remove the locked balance item store.removeLockedBalance(msg.sender, _startIndex + index); totalAmount = totalAmount.add(amounts[index]); } if (totalAmount > 0) { // transfer the tokens to the caller in a single call wallet.withdrawTokens(networkToken, msg.sender, totalAmount); } } /** * @dev returns the ROI for removing liquidity in the current state after providing liquidity with the given args * the function assumes full protection is in effect * return value is in PPM and can be larger than PPM_RESOLUTION for positive ROI, 1M = 0% ROI * * @param _poolToken pool token * @param _reserveToken reserve token * @param _reserveAmount reserve token amount that was added * @param _poolRateN rate of 1 pool token in reserve token units when the liquidity was added (numerator) * @param _poolRateD rate of 1 pool token in reserve token units when the liquidity was added (denominator) * @param _reserveRateN rate of 1 reserve token in the other reserve token units when the liquidity was added (numerator) * @param _reserveRateD rate of 1 reserve token in the other reserve token units when the liquidity was added (denominator) * @return ROI in PPM */ function poolROI( IDSToken _poolToken, IERC20Token _reserveToken, uint256 _reserveAmount, uint256 _poolRateN, uint256 _poolRateD, uint256 _reserveRateN, uint256 _reserveRateD ) external view returns (uint256) { // calculate the amount of pool tokens based on the amount of reserve tokens uint256 poolAmount = _reserveAmount.mul(_poolRateD).div(_poolRateN); // get the various rates between the reserves upon adding liquidity and now PackedRates memory packedRates = packRates(_poolToken, _reserveToken, _reserveRateN, _reserveRateD, false); // get the current return uint256 protectedReturn = removeLiquidityTargetAmount( _poolToken, _reserveToken, poolAmount, _reserveAmount, packedRates, time().sub(settings.maxProtectionDelay()), time() ); // calculate the ROI as the ratio between the current fully protected return and the initial amount return protectedReturn.mul(PPM_RESOLUTION).div(_reserveAmount); } /** * @dev adds protected liquidity for the caller to the store * * @param _provider protected liquidity provider * @param _poolToken pool token * @param _reserveToken reserve token * @param _poolAmount amount of pool tokens to protect * @param _reserveAmount amount of reserve tokens to protect * @return new protected liquidity id */ function addProtectedLiquidity( address _provider, IDSToken _poolToken, IERC20Token _reserveToken, uint256 _poolAmount, uint256 _reserveAmount ) internal returns (uint256) { // notify event subscribers if (address(eventsSubscriber) != address(0)) { eventsSubscriber.onAddingLiquidity(_provider, _poolToken, _reserveToken, _poolAmount, _reserveAmount); } Fraction memory rate = reserveTokenAverageRate(_poolToken, _reserveToken, true); stats.increaseTotalAmounts(_provider, _poolToken, _reserveToken, _poolAmount, _reserveAmount); stats.addProviderPool(_provider, _poolToken); return store.addProtectedLiquidity( _provider, _poolToken, _reserveToken, _poolAmount, _reserveAmount, rate.n, rate.d, time() ); } /** * @dev locks network tokens for the provider and emits the tokens locked event * * @param _provider tokens provider * @param _amount amount of network tokens */ function lockTokens(address _provider, uint256 _amount) internal { uint256 expirationTime = time().add(settings.lockDuration()); store.addLockedBalance(_provider, _amount, expirationTime); } /** * @dev returns the rate of 1 pool token in reserve token units * * @param _poolToken pool token * @param _reserveToken reserve token */ function poolTokenRate(IDSToken _poolToken, IERC20Token _reserveToken) internal view virtual returns (Fraction memory) { // get the pool token supply uint256 poolTokenSupply = _poolToken.totalSupply(); // get the reserve balance IConverter converter = IConverter(payable(ownedBy(_poolToken))); uint256 reserveBalance = converter.getConnectorBalance(_reserveToken); // for standard pools, 50% of the pool supply value equals the value of each reserve return Fraction({ n: reserveBalance.mul(2), d: poolTokenSupply }); } /** * @dev returns the average rate of 1 reserve token in the other reserve token units * * @param _poolToken pool token * @param _reserveToken reserve token * @param _validateAverageRate true to validate the average rate; false otherwise */ function reserveTokenAverageRate( IDSToken _poolToken, IERC20Token _reserveToken, bool _validateAverageRate ) internal view returns (Fraction memory) { (, , uint256 averageRateN, uint256 averageRateD) = reserveTokenRates(_poolToken, _reserveToken, _validateAverageRate); return Fraction(averageRateN, averageRateD); } /** * @dev returns the spot rate and average rate of 1 reserve token in the other reserve token units * * @param _poolToken pool token * @param _reserveToken reserve token * @param _validateAverageRate true to validate the average rate; false otherwise */ function reserveTokenRates( IDSToken _poolToken, IERC20Token _reserveToken, bool _validateAverageRate ) internal view returns ( uint256, uint256, uint256, uint256 ) { ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolToken))); IERC20Token otherReserve = converterOtherReserve(converter, _reserveToken); (uint256 spotRateN, uint256 spotRateD) = converterReserveBalances(converter, otherReserve, _reserveToken); (uint256 averageRateN, uint256 averageRateD) = converter.recentAverageRate(_reserveToken); require( !_validateAverageRate || averageRateInRange( spotRateN, spotRateD, averageRateN, averageRateD, settings.averageRateMaxDeviation() ), "ERR_INVALID_RATE" ); return (spotRateN, spotRateD, averageRateN, averageRateD); } /** * @dev returns the various rates between the reserves * * @param _poolToken pool token * @param _reserveToken reserve token * @param _addSpotRateN add spot rate numerator * @param _addSpotRateD add spot rate denominator * @param _validateAverageRate true to validate the average rate; false otherwise * @return see `struct PackedRates` */ function packRates( IDSToken _poolToken, IERC20Token _reserveToken, uint256 _addSpotRateN, uint256 _addSpotRateD, bool _validateAverageRate ) internal view returns (PackedRates memory) { (uint256 removeSpotRateN, uint256 removeSpotRateD, uint256 removeAverageRateN, uint256 removeAverageRateD) = reserveTokenRates(_poolToken, _reserveToken, _validateAverageRate); require( (_addSpotRateN <= MAX_UINT128 && _addSpotRateD <= MAX_UINT128) && (removeSpotRateN <= MAX_UINT128 && removeSpotRateD <= MAX_UINT128) && (removeAverageRateN <= MAX_UINT128 && removeAverageRateD <= MAX_UINT128), "ERR_INVALID_RATE" ); return PackedRates({ addSpotRateN: uint128(_addSpotRateN), addSpotRateD: uint128(_addSpotRateD), removeSpotRateN: uint128(removeSpotRateN), removeSpotRateD: uint128(removeSpotRateD), removeAverageRateN: uint128(removeAverageRateN), removeAverageRateD: uint128(removeAverageRateD) }); } /** * @dev returns whether or not the deviation of the average rate from the spot rate is within range * for example, if the maximum permitted deviation is 5%, then return `95/100 <= average/spot <= 100/95` * * @param _spotRateN spot rate numerator * @param _spotRateD spot rate denominator * @param _averageRateN average rate numerator * @param _averageRateD average rate denominator * @param _maxDeviation the maximum permitted deviation of the average rate from the spot rate */ function averageRateInRange( uint256 _spotRateN, uint256 _spotRateD, uint256 _averageRateN, uint256 _averageRateD, uint32 _maxDeviation ) internal pure returns (bool) { uint256 ppmDelta = PPM_RESOLUTION - _maxDeviation; uint256 min = _spotRateN.mul(_averageRateD).mul(ppmDelta).mul(ppmDelta); uint256 mid = _spotRateD.mul(_averageRateN).mul(ppmDelta).mul(PPM_RESOLUTION); uint256 max = _spotRateN.mul(_averageRateD).mul(PPM_RESOLUTION).mul(PPM_RESOLUTION); return min <= mid && mid <= max; } /** * @dev utility to add liquidity to a converter * * @param _converter converter * @param _reserveToken1 reserve token 1 * @param _reserveToken2 reserve token 2 * @param _reserveAmount1 reserve amount 1 * @param _reserveAmount2 reserve amount 2 * @param _value ETH amount to add */ function addLiquidity( ILiquidityPoolConverter _converter, IERC20Token _reserveToken1, IERC20Token _reserveToken2, uint256 _reserveAmount1, uint256 _reserveAmount2, uint256 _value ) internal { // ensure that the contract can receive ETH updatingLiquidity = true; IERC20Token[] memory reserveTokens = new IERC20Token[](2); uint256[] memory amounts = new uint256[](2); reserveTokens[0] = _reserveToken1; reserveTokens[1] = _reserveToken2; amounts[0] = _reserveAmount1; amounts[1] = _reserveAmount2; _converter.addLiquidity{ value: _value }(reserveTokens, amounts, 1); // ensure that the contract can receive ETH updatingLiquidity = false; } /** * @dev utility to remove liquidity from a converter * * @param _poolToken pool token of the converter * @param _poolAmount amount of pool tokens to remove * @param _reserveToken1 reserve token 1 * @param _reserveToken2 reserve token 2 */ function removeLiquidity( IDSToken _poolToken, uint256 _poolAmount, IERC20Token _reserveToken1, IERC20Token _reserveToken2 ) internal { ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolToken))); // ensure that the contract can receive ETH updatingLiquidity = true; IERC20Token[] memory reserveTokens = new IERC20Token[](2); uint256[] memory minReturns = new uint256[](2); reserveTokens[0] = _reserveToken1; reserveTokens[1] = _reserveToken2; minReturns[0] = 1; minReturns[1] = 1; converter.removeLiquidity(_poolAmount, reserveTokens, minReturns); // ensure that the contract can receive ETH updatingLiquidity = false; } /** * @dev returns a protected liquidity from the store * * @param _id protected liquidity id * @return protected liquidity */ function protectedLiquidity(uint256 _id) internal view returns (ProtectedLiquidity memory) { ProtectedLiquidity memory liquidity; ( liquidity.provider, liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount, liquidity.reserveRateN, liquidity.reserveRateD, liquidity.timestamp ) = store.protectedLiquidity(_id); return liquidity; } /** * @dev returns a protected liquidity from the store * * @param _id protected liquidity id * @param _provider authorized provider * @return protected liquidity */ function protectedLiquidity(uint256 _id, address _provider) internal view returns (ProtectedLiquidity memory) { ProtectedLiquidity memory liquidity = protectedLiquidity(_id); require(liquidity.provider == _provider, "ERR_ACCESS_DENIED"); return liquidity; } /** * @dev returns the protected amount of reserve tokens plus accumulated fee before compensation * * @param _poolAmount pool token amount when the liquidity was added * @param _poolRate rate of 1 pool token in the related reserve token units * @param _addRate rate of 1 reserve token in the other reserve token units when the liquidity was added * @param _removeRate rate of 1 reserve token in the other reserve token units when the liquidity is removed * @return protected amount of reserve tokens plus accumulated fee = sqrt(_removeRate / _addRate) * _poolRate * _poolAmount */ function protectedAmountPlusFee( uint256 _poolAmount, Fraction memory _poolRate, Fraction memory _addRate, Fraction memory _removeRate ) internal pure returns (uint256) { uint256 n = MathEx.ceilSqrt(_addRate.d.mul(_removeRate.n)).mul(_poolRate.n); uint256 d = MathEx.floorSqrt(_addRate.n.mul(_removeRate.d)).mul(_poolRate.d); uint256 x = n * _poolAmount; if (x / n == _poolAmount) { return x / d; } (uint256 hi, uint256 lo) = n > _poolAmount ? (n, _poolAmount) : (_poolAmount, n); (uint256 p, uint256 q) = MathEx.reducedRatio(hi, d, MAX_UINT256 / lo); uint256 min = (hi / d).mul(lo); if (q > 0) { return MathEx.max(min, (p * lo) / q); } return min; } /** * @dev returns the impermanent loss incurred due to the change in rates between the reserve tokens * * @param _prevRate previous rate between the reserves * @param _newRate new rate between the reserves * @return impermanent loss (as a ratio) */ function impLoss(Fraction memory _prevRate, Fraction memory _newRate) internal pure returns (Fraction memory) { uint256 ratioN = _newRate.n.mul(_prevRate.d); uint256 ratioD = _newRate.d.mul(_prevRate.n); uint256 prod = ratioN * ratioD; uint256 root = prod / ratioN == ratioD ? MathEx.floorSqrt(prod) : MathEx.floorSqrt(ratioN) * MathEx.floorSqrt(ratioD); uint256 sum = ratioN.add(ratioD); // the arithmetic below is safe because `x + y >= sqrt(x * y) * 2` if (sum % 2 == 0) { sum /= 2; return Fraction({ n: sum - root, d: sum }); } return Fraction({ n: sum - root * 2, d: sum }); } /** * @dev returns the protection level based on the timestamp and protection delays * * @param _addTimestamp time at which the liquidity was added * @param _removeTimestamp time at which the liquidity is removed * @return protection level (as a ratio) */ function protectionLevel(uint256 _addTimestamp, uint256 _removeTimestamp) internal view returns (Fraction memory) { uint256 timeElapsed = _removeTimestamp.sub(_addTimestamp); uint256 minProtectionDelay = settings.minProtectionDelay(); uint256 maxProtectionDelay = settings.maxProtectionDelay(); if (timeElapsed < minProtectionDelay) { return Fraction({ n: 0, d: 1 }); } if (timeElapsed >= maxProtectionDelay) { return Fraction({ n: 1, d: 1 }); } return Fraction({ n: timeElapsed, d: maxProtectionDelay }); } /** * @dev returns the compensation amount based on the impermanent loss and the protection level * * @param _amount protected amount in units of the reserve token * @param _total amount plus fee in units of the reserve token * @param _loss protection level (as a ratio between 0 and 1) * @param _level impermanent loss (as a ratio between 0 and 1) * @return compensation amount */ function compensationAmount( uint256 _amount, uint256 _total, Fraction memory _loss, Fraction memory _level ) internal pure returns (uint256) { uint256 levelN = _level.n.mul(_amount); uint256 levelD = _level.d; uint256 maxVal = MathEx.max(MathEx.max(levelN, levelD), _total); (uint256 lossN, uint256 lossD) = MathEx.reducedRatio(_loss.n, _loss.d, MAX_UINT256 / maxVal); return _total.mul(lossD.sub(lossN)).div(lossD).add(lossN.mul(levelN).div(lossD.mul(levelD))); } function getNetworkCompensation( uint256 _targetAmount, uint256 _baseAmount, PackedRates memory _packedRates ) internal view returns (uint256) { if (_targetAmount <= _baseAmount) { return 0; } // calculate the delta in network tokens uint256 delta = (_targetAmount - _baseAmount).mul(_packedRates.removeAverageRateN).div(_packedRates.removeAverageRateD); // the delta might be very small due to precision loss // in which case no compensation will take place (gas optimization) if (delta >= settings.minNetworkCompensation()) { return delta; } return 0; } /** * @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't. * note that we use the non standard erc-20 interface in which `approve` has no return value so that * this function will work for both standard and non standard tokens * * @param _token token to check the allowance in * @param _spender approved address * @param _value allowance amount */ function ensureAllowance( IERC20Token _token, address _spender, uint256 _value ) private { uint256 allowance = _token.allowance(address(this), _spender); if (allowance < _value) { if (allowance > 0) safeApprove(_token, _spender, 0); safeApprove(_token, _spender, _value); } } // utility to mint network tokens function mintNetworkTokens( address _owner, IConverterAnchor _poolAnchor, uint256 _amount ) private { networkTokenGovernance.mint(_owner, _amount); systemStore.incNetworkTokensMinted(_poolAnchor, _amount); } // utility to burn network tokens function burnNetworkTokens(IConverterAnchor _poolAnchor, uint256 _amount) private { networkTokenGovernance.burn(_amount); systemStore.decNetworkTokensMinted(_poolAnchor, _amount); } // utility to get the reserve balances function converterReserveBalances( IConverter _converter, IERC20Token _reserveToken1, IERC20Token _reserveToken2 ) private view returns (uint256, uint256) { return (_converter.getConnectorBalance(_reserveToken1), _converter.getConnectorBalance(_reserveToken2)); } // utility to get the other reserve function converterOtherReserve(IConverter _converter, IERC20Token _thisReserve) private view returns (IERC20Token) { IERC20Token otherReserve = _converter.connectorTokens(0); return otherReserve != _thisReserve ? otherReserve : _converter.connectorTokens(1); } // utility to get the owner function ownedBy(IOwned _owned) private view returns (address) { return _owned.owner(); } }
returns the rate of 1 pool token in reserve token units _poolToken pool token _reserveToken reserve token/ get the pool token supply get the reserve balance for standard pools, 50% of the pool supply value equals the value of each reserve
function poolTokenRate(IDSToken _poolToken, IERC20Token _reserveToken) internal view virtual returns (Fraction memory) { uint256 poolTokenSupply = _poolToken.totalSupply(); IConverter converter = IConverter(payable(ownedBy(_poolToken))); uint256 reserveBalance = converter.getConnectorBalance(_reserveToken); }
2,294,296
// SPDX-License-Identifier: MIT License pragma solidity ^0.6.0; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // interface for the uniswap oracle interface IUniswapOracle { function changeInterval(uint256 seconds_) external; function update() external; function consult(address token, uint amountIn) external view returns (uint amountOut); } // interface for the oneToken interface OneToken { function getOneTokenUsd() external view returns (uint256); } /// @title An overcollateralized stablecoin using LINK /// @author Masanobu Fukuoka contract oneLINK is ERC20("oneLINK", "oneLINK"), Ownable, ReentrancyGuard { using SafeMath for uint256; uint256 constant public MAX_RESERVE_RATIO = 100 * 10 ** 9; // At 100% reserve ratio, each oneLINK is backed 1-to-1 by $1 of existing stable coins uint256 private constant DECIMALS = 9; uint256 public lastRefreshReserve; // The last time the reserve ratio was updated by the contract uint256 public minimumRefreshTime; // The time between reserve ratio refreshes address public stimulus; // oneLINK builds a stimulus fund in LINK. uint256 public stimulusDecimals; // used to calculate oracle rate of Uniswap Pair // We get the price of LINK from Chainlink! Thanks chainLink! Hopefully, the chainLink // will provide Oracle prices for oneLINK, oneLINK, etc in the future. For now, we will get those // from the ichi.farm exchange which uses Uniswap contracts. AggregatorV3Interface internal chainlinkStimulusOracle; AggregatorV3Interface internal ethPrice; address public oneTokenOracle; // oracle for the oneLINK stable coin address public stimulusOracle; // oracle for a stimulus cryptocurrency that isn't on chainLink bool public chainLink; // true means it is a chainLink oracle // Only governance should cause the coin to go fully agorithmic by changing the minimum reserve // ratio. For now, we will set a conservative minimum reserve ratio. uint256 public MIN_RESERVE_RATIO; uint256 public MIN_DELAY; // Makes sure that you can't send coins to a 0 address and prevents coins from being sent to the // contract address. I want to protect your funds! modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } uint256 private _totalSupply; mapping(address => uint256) private _oneBalances; mapping(address => uint256) private _lastCall; // used as a record to prevent flash loan attacks mapping (address => mapping (address => uint256)) private _allowedOne; // allowance to spend one address public wethAddress; // used for uniswap oracle consults address public ethUsdcUniswapOracle; // used to get the base price of USDC and ETH address public gov; // who has admin rights over certain functions address public pendingGov; // allows you to transfer the governance to a different user - they must accept it! uint256 public reserveStepSize; // step size of update of reserve rate (e.g. 5 * 10 ** 8 = 0.5%) uint256 public reserveRatio; // a number between 0 and 100 * 10 ** 9. // 0 = 0% // 100 * 10 ** 9 = 100% // map of acceptable collaterals mapping (address => bool) public acceptedCollateral; mapping (address => uint256) public collateralMintFee; // minting fee for different collaterals (100 * 10 ** 9 = 100% fee) address[] public collateralArray; // array of collateral - used to iterate while updating certain things like oracle intervals for TWAP // modifier to allow auto update of TWAP oracle prices // also updates reserves rate programatically modifier updateProtocol() { if (address(oneTokenOracle) != address(0)) { // only update if stimulusOracle is set if (!chainLink) IUniswapOracle(stimulusOracle).update(); // this is always updated because we always need stablecoin oracle price IUniswapOracle(oneTokenOracle).update(); for (uint i = 0; i < collateralArray.length; i++){ if (acceptedCollateral[collateralArray[i]] && !oneCoinCollateralOracle[collateralArray[i]]) IUniswapOracle(collateralOracle[collateralArray[i]]).update(); } // update reserve ratio if enough time has passed if (block.timestamp - lastRefreshReserve >= minimumRefreshTime) { // $Z / 1 one token if (getOneTokenUsd() > 1 * 10 ** 9) { setReserveRatio(reserveRatio.sub(reserveStepSize)); } else { setReserveRatio(reserveRatio.add(reserveStepSize)); } lastRefreshReserve = block.timestamp; } } _; } // events for off-chain record keeping event NewPendingGov(address oldPendingGov, address newPendingGov); event NewGov(address oldGov, address newGov); event NewReserveRate(uint256 reserveRatio); event Mint(address stimulus, address receiver, address collateral, uint256 collateralAmount, uint256 stimulusAmount, uint256 oneAmount); event Withdraw(address stimulus, address receiver, address collateral, uint256 collateralAmount, uint256 stimulusAmount, uint256 oneAmount); event NewMinimumRefreshTime(uint256 minimumRefreshTime); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data); modifier onlyIchiGov() { require(msg.sender == gov, "ACCESS: only Ichi governance"); _; } bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); // shortcut for calling transfer mapping (address => uint256) public collateralDecimals; // needed to be able to convert from different collaterals mapping (address => bool) public oneCoinCollateralOracle; // if true, we query the one token contract's usd price mapping (address => bool) public previouslySeenCollateral; // used to allow users to withdraw collateral, even if the collateral has since been deprecated // previouslySeenCollateral lets the contract know if a collateral has been used before - this also // prevents attacks where uses add a custom address as collateral, but that custom address is actually // their own malicious smart contract. Read peckshield blog for more info. mapping (address => address) public collateralOracle; // address of the Collateral-LINK Uniswap Price // default to 0 uint256 public mintFee; uint256 public withdrawFee; // fee to charge when minting oneLINK - this will go into collateral event MintFee(uint256 fee_); // fee to charge when redeeming oneLINK - this will go into collateral event WithdrawFee(uint256 fee_); // set governance access to only oneLINK - LINK pool multisig (elected after rewards) modifier linkLPGov() { require(msg.sender == lpGov, "ACCESS: only linkLP governance"); _; } address public lpGov; address public pendingLPGov; event NewPendingLPGov(address oldPendingLPGov, address newPendingLPGov); event NewLPGov(address oldLPGov, address newLPGov); event NewMintFee(address collateral, uint256 oldFee, uint256 newFee); mapping (address => uint256) private _burnedStablecoin; // maps user to burned oneLINK // important: make sure changeInterval is a function to allow the interval of update to change function addCollateral(address collateral_, uint256 collateralDecimal_, address oracleAddress_, bool oneCoinOracle) external linkLPGov { // only add collateral once if (!previouslySeenCollateral[collateral_]) collateralArray.push(collateral_); previouslySeenCollateral[collateral_] = true; acceptedCollateral[collateral_] = true; oneCoinCollateralOracle[collateral_] = oneCoinOracle; collateralDecimals[collateral_] = collateralDecimal_; collateralOracle[collateral_] = oracleAddress_; collateralMintFee[collateral_] = 0; } function setCollateralMintFee(address collateral_, uint256 fee_) external linkLPGov { require(acceptedCollateral[collateral_], "invalid collateral"); require(fee_ <= 100 * 10 ** 9, "Fee must be valid"); emit NewMintFee(collateral_, collateralMintFee[collateral_], fee_); collateralMintFee[collateral_] = fee_; } // step size = how much the reserve rate updates per update cycle function setReserveStepSize(uint256 stepSize_) external linkLPGov { reserveStepSize = stepSize_; } // changes the oracle for a given collaterarl function setCollateralOracle(address collateral_, address oracleAddress_, bool oneCoinOracle_) external linkLPGov { require(acceptedCollateral[collateral_], "invalid collateral"); oneCoinCollateralOracle[collateral_] = oneCoinOracle_; collateralOracle[collateral_] = oracleAddress_; } // removes a collateral from minting. Still allows withdrawals however function removeCollateral(address collateral_) external linkLPGov { acceptedCollateral[collateral_] = false; } // used for querying function getBurnedStablecoin(address _user) public view returns (uint256) { return _burnedStablecoin[_user]; } // returns 10 ** 9 price of collateral function getCollateralUsd(address collateral_) public view returns (uint256) { require(previouslySeenCollateral[collateral_], "must be an existing collateral"); if (oneCoinCollateralOracle[collateral_]) return OneToken(collateral_).getOneTokenUsd(); uint256 ethUsdcTWAP = IUniswapOracle(ethUsdcUniswapOracle).consult(wethAddress, 1 * 10 ** 18); // 1 ETH = X USDC (10 ^ 6 decimals) return ethUsdcTWAP.mul(10 ** 3).mul(10 ** 9).div((IUniswapOracle(collateralOracle[collateral_]).consult(wethAddress, 10 ** 18)).mul(10 ** 9).div(10 ** collateralDecimals[collateral_])); } function globalCollateralValue() public view returns (uint256) { uint256 totalCollateralUsd = 0; for (uint i = 0; i < collateralArray.length; i++){ // Exclude null addresses if (collateralArray[i] != address(0)){ totalCollateralUsd += IERC20(collateralArray[i]).balanceOf(address(this)).mul(10 ** 9).div(10 ** collateralDecimals[collateralArray[i]]).mul(getCollateralUsd(collateralArray[i])).div(10 ** 9); // add stablecoin balance } } return totalCollateralUsd; } // return price of oneLINK in 10 ** 9 decimal function getOneTokenUsd() public view returns (uint256) { uint256 oneTokenPrice = IUniswapOracle(oneTokenOracle).consult(stimulus, 10 ** stimulusDecimals); // X one tokens (10 ** 9) / 1 stimulus token uint256 stimulusTWAP = getStimulusOracle(); // $Y / 1 stimulus (10 ** 9) uint256 oneTokenUsd = stimulusTWAP.mul(10 ** 9).div(oneTokenPrice); // 10 ** 9 decimals return oneTokenUsd; } /** * @return The total number of oneLINK. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public override view returns (uint256) { return _oneBalances[who]; } function setChainLinkStimulusOracle(address oracle_) external linkLPGov returns (bool) { chainlinkStimulusOracle = AggregatorV3Interface(oracle_); chainLink = true; return true; } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public override validRecipient(to) updateProtocol() returns (bool) { _oneBalances[msg.sender] = _oneBalances[msg.sender].sub(value); _oneBalances[to] = _oneBalances[to].add(value); emit Transfer(msg.sender, to, value); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public override view returns (uint256) { return _allowedOne[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public override validRecipient(to) updateProtocol() returns (bool) { _allowedOne[from][msg.sender] = _allowedOne[from][msg.sender].sub(value); _oneBalances[from] = _oneBalances[from].sub(value); _oneBalances[to] = _oneBalances[to].add(value); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public override validRecipient(spender) updateProtocol() returns (bool) { _allowedOne[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) { _allowedOne[msg.sender][spender] = _allowedOne[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedOne[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) { uint256 oldValue = _allowedOne[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedOne[msg.sender][spender] = 0; } else { _allowedOne[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedOne[msg.sender][spender]); return true; } function setOneOracle(address oracle_) external linkLPGov returns (bool) { oneTokenOracle = oracle_; return true; } function setEthUsdcUniswapOracle(address oracle_) external linkLPGov returns (bool) { ethUsdcUniswapOracle = oracle_; return true; } function setStimulusUniswapOracle(address oracle_) external linkLPGov returns (bool) { stimulusOracle = oracle_; chainLink = false; return true; } // oracle rate is 10 ** 9 decimals // returns $Z / Stimulus function getStimulusOracle() public view returns (uint256) { if (chainLink) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = chainlinkStimulusOracle.latestRoundData(); require(timeStamp > 0, "Rounds not complete"); return uint256(price).mul(10); // 10 ** 9 price } else { // stimulusTWAP has `stimulusDecimals` decimals uint256 stimulusTWAP = IUniswapOracle(stimulusOracle).consult(wethAddress, 1 * 10 ** 18); // 1 ETH = X Stimulus, or X Stimulus / ETH uint256 ethUsdcTWAP = IUniswapOracle(ethUsdcUniswapOracle).consult(wethAddress, 1 * 10 ** 18); // 1 ETH = X USDC // X USDC / 1 ETH * (1 ETH / x Stimulus) = Y USDC / Stimulus return ethUsdcTWAP.mul(10 ** 3).mul(10 ** stimulusDecimals).div(stimulusTWAP); // 10 ** 9 price } } // minimum amount of block time (seconds) required for an update in reserve ratio function setMinimumRefreshTime(uint256 val_) external linkLPGov returns (bool) { require(val_ != 0, "minimum refresh time must be valid"); minimumRefreshTime = val_; // change collateral array for (uint i = 0; i < collateralArray.length; i++){ if (acceptedCollateral[collateralArray[i]] && !oneCoinCollateralOracle[collateralArray[i]]) IUniswapOracle(collateralOracle[collateralArray[i]]).changeInterval(val_); } IUniswapOracle(ethUsdcUniswapOracle).changeInterval(val_); // stimulus and oneToken oracle update IUniswapOracle(oneTokenOracle).changeInterval(val_); if (!chainLink) IUniswapOracle(stimulusOracle).changeInterval(val_); // change all the oracles (collateral, stimulus, oneToken) emit NewMinimumRefreshTime(val_); return true; } constructor( uint256 reserveRatio_, address stimulus_, uint256 stimulusDecimals_, address wethAddress_, address ethOracleChainLink_, address ethUsdcUniswap_ ) public { _setupDecimals(uint8(9)); stimulus = stimulus_; minimumRefreshTime = 3600 * 1; // 1 hour by default stimulusDecimals = stimulusDecimals_; reserveStepSize = 2 * 10 ** 8; // 0.2% by default ethPrice = AggregatorV3Interface(ethOracleChainLink_); ethUsdcUniswapOracle = ethUsdcUniswap_; MIN_RESERVE_RATIO = 90 * 10 ** 9; wethAddress = wethAddress_; MIN_DELAY = 3; // 3 blocks withdrawFee = 1 * 10 ** 8; // 0.1% fee at first, remains in collateral gov = msg.sender; lpGov = msg.sender; reserveRatio = reserveRatio_; _totalSupply = 10 ** 9; _oneBalances[msg.sender] = 10 ** 9; emit Transfer(address(0x0), msg.sender, 10 ** 9); } function setMinimumReserveRatio(uint256 val_) external linkLPGov { MIN_RESERVE_RATIO = val_; } function setMinimumDelay(uint256 val_) external linkLPGov { MIN_DELAY = val_; } // LP pool governance ==================================== function setPendingLPGov(address pendingLPGov_) external linkLPGov { address oldPendingLPGov = pendingLPGov; pendingLPGov = pendingLPGov_; emit NewPendingLPGov(oldPendingLPGov, pendingLPGov_); } function acceptLPGov() external { require(msg.sender == pendingLPGov, "!pending"); address oldLPGov = lpGov; // that lpGov = pendingLPGov; pendingLPGov = address(0); emit NewGov(oldLPGov, lpGov); } // over-arching protocol level governance =============== function setPendingGov(address pendingGov_) external onlyIchiGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } function acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } // ====================================================== // calculates how much you will need to send in order to mint oneLINK, depending on current market prices + reserve ratio // oneAmount: the amount of oneLINK you want to mint // collateral: the collateral you want to use to pay // also works in the reverse direction, i.e. how much collateral + stimulus to receive when you burn One function consultOneDeposit(uint256 oneAmount, address collateral) public view returns (uint256, uint256) { require(oneAmount != 0, "must use valid oneAmount"); require(acceptedCollateral[collateral], "must be an accepted collateral"); // convert to correct decimals for collateral uint256 collateralAmount = oneAmount.mul(reserveRatio).div(MAX_RESERVE_RATIO).mul(10 ** collateralDecimals[collateral]).div(10 ** DECIMALS); collateralAmount = collateralAmount.mul(10 ** 9).div(getCollateralUsd(collateral)); if (address(oneTokenOracle) == address(0)) return (collateralAmount, 0); uint256 stimulusUsd = getStimulusOracle(); // 10 ** 9 uint256 stimulusAmountInOneStablecoin = oneAmount.mul(MAX_RESERVE_RATIO.sub(reserveRatio)).div(MAX_RESERVE_RATIO); uint256 stimulusAmount = stimulusAmountInOneStablecoin.mul(10 ** 9).div(stimulusUsd).mul(10 ** stimulusDecimals).div(10 ** DECIMALS); // must be 10 ** stimulusDecimals return (collateralAmount, stimulusAmount); } function consultOneWithdraw(uint256 oneAmount, address collateral) public view returns (uint256, uint256) { require(oneAmount != 0, "must use valid oneAmount"); require(previouslySeenCollateral[collateral], "must be an accepted collateral"); uint256 collateralAmount = oneAmount.sub(oneAmount.mul(withdrawFee).div(100 * 10 ** DECIMALS)).mul(10 ** collateralDecimals[collateral]).div(10 ** DECIMALS); collateralAmount = collateralAmount.mul(10 ** 9).div(getCollateralUsd(collateral)); return (collateralAmount, 0); } // @title: deposit collateral + stimulus token // collateral: address of the collateral to deposit (USDC, DAI, TUSD, etc) function mint( uint256 oneAmount, address collateral ) public payable nonReentrant { require(acceptedCollateral[collateral], "must be an accepted collateral"); require(oneAmount != 0, "must mint non-zero amount"); // wait 3 blocks to avoid flash loans require((_lastCall[msg.sender] + MIN_DELAY) <= block.number, "action too soon - please wait a few more blocks"); // validate input amounts are correct (uint256 collateralAmount, uint256 stimulusAmount) = consultOneDeposit(oneAmount, collateral); require(collateralAmount <= IERC20(collateral).balanceOf(msg.sender), "sender has insufficient collateral balance"); require(stimulusAmount <= IERC20(stimulus).balanceOf(msg.sender), "sender has insufficient stimulus balance"); // checks passed, so transfer tokens SafeERC20.safeTransferFrom(IERC20(collateral), msg.sender, address(this), collateralAmount); SafeERC20.safeTransferFrom(IERC20(stimulus), msg.sender, address(this), stimulusAmount); oneAmount = oneAmount.sub(oneAmount.mul(mintFee).div(100 * 10 ** DECIMALS)); // apply mint fee oneAmount = oneAmount.sub(oneAmount.mul(collateralMintFee[collateral]).div(100 * 10 ** DECIMALS)); // apply collateral fee _totalSupply = _totalSupply.add(oneAmount); _oneBalances[msg.sender] = _oneBalances[msg.sender].add(oneAmount); emit Transfer(address(0x0), msg.sender, oneAmount); _lastCall[msg.sender] = block.number; emit Mint(stimulus, msg.sender, collateral, collateralAmount, stimulusAmount, oneAmount); } // fee_ should be 10 ** 9 decimals (e.g. 10% = 10 * 10 ** 9) function editMintFee(uint256 fee_) external onlyIchiGov { require(fee_ <= 100 * 10 ** 9, "Fee must be valid"); mintFee = fee_; emit MintFee(fee_); } // fee_ should be 10 ** 9 decimals (e.g. 10% = 10 * 10 ** 9) function editWithdrawFee(uint256 fee_) external onlyIchiGov { withdrawFee = fee_; emit WithdrawFee(fee_); } /// burns stablecoin and increments _burnedStablecoin mapping for user /// user can claim collateral in a 2nd step below function withdraw( uint256 oneAmount, address collateral ) public nonReentrant updateProtocol() { require(oneAmount != 0, "must withdraw non-zero amount"); require(oneAmount <= _oneBalances[msg.sender], "insufficient balance"); require(previouslySeenCollateral[collateral], "must be an existing collateral"); require((_lastCall[msg.sender] + MIN_DELAY) <= block.number, "action too soon - please wait a few blocks"); // burn oneAmount _totalSupply = _totalSupply.sub(oneAmount); _oneBalances[msg.sender] = _oneBalances[msg.sender].sub(oneAmount); _burnedStablecoin[msg.sender] = _burnedStablecoin[msg.sender].add(oneAmount); _lastCall[msg.sender] = block.number; emit Transfer(msg.sender, address(0x0), oneAmount); } // 2nd step for withdrawal of collateral // this 2 step withdrawal is important for prevent flash-loan style attacks // flash-loan style attacks try to use loops/complex arbitrage strategies to // drain collateral so adding a 2-step process prevents any potential attacks // because all flash-loans must be repaid within 1 tx and 1 block /// @notice If you are interested, I would recommend reading: https://slowmist.medium.com/ /// also https://cryptobriefing.com/50-million-lost-the-top-19-defi-cryptocurrency-hacks-2020/ function withdrawFinal(address collateral, uint256 amount) public nonReentrant updateProtocol() { require(previouslySeenCollateral[collateral], "must be an existing collateral"); require((_lastCall[msg.sender] + MIN_DELAY) <= block.number, "action too soon - please wait a few blocks"); uint256 oneAmount = _burnedStablecoin[msg.sender]; require(oneAmount != 0, "insufficient oneLINK to redeem"); require(amount <= oneAmount, "insufficient oneLINK to redeem"); _burnedStablecoin[msg.sender] = _burnedStablecoin[msg.sender].sub(amount); // send collateral - fee (convert to collateral decimals too) uint256 collateralAmount = amount.sub(amount.mul(withdrawFee).div(100 * 10 ** DECIMALS)).mul(10 ** collateralDecimals[collateral]).div(10 ** DECIMALS); collateralAmount = collateralAmount.mul(10 ** 9).div(getCollateralUsd(collateral)); uint256 stimulusAmount = 0; // check enough reserves - don't want to burn one coin if we cannot fulfill withdrawal require(collateralAmount <= IERC20(collateral).balanceOf(address(this)), "insufficient collateral reserves - try another collateral"); SafeERC20.safeTransfer(IERC20(collateral), msg.sender, collateralAmount); _lastCall[msg.sender] = block.number; emit Withdraw(stimulus, msg.sender, collateral, collateralAmount, stimulusAmount, amount); } // internal function used to set the reserve ratio of the token // must be between MIN / MAX Reserve Ratio, which are constants // cannot be 0 function setReserveRatio(uint256 newRatio_) internal { require(newRatio_ >= 0, "positive reserve ratio"); if (newRatio_ <= MAX_RESERVE_RATIO && newRatio_ >= MIN_RESERVE_RATIO) { reserveRatio = newRatio_; emit NewReserveRate(reserveRatio); } } /// @notice easy function transfer ETH (not WETH) function safeTransferETH(address to, uint value) public linkLPGov { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'ETH_TRANSFER_FAILED'); } /// @notice easy funtion to move stimulus to a new location // location: address to send to // amount: amount of stimulus to send (use full decimals) function moveStimulus( address location, uint256 amount ) public linkLPGov { SafeERC20.safeTransfer(IERC20(stimulus), location, amount); } // can execute any abstract transaction on this smart contrat // target: address / smart contract you are interracting with // value: msg.value (amount of eth in WEI you are sending. Most of the time it is 0) // signature: the function signature (name of the function and the types of the arguments). // for example: "transfer(address,uint256)", or "approve(address,uint256)" // data: abi-encodeded byte-code of the parameter values you are sending. See "./encode.js" for Ether.js library function to make this easier function executeTransaction(address target, uint value, string memory signature, bytes memory data) public payable linkLPGov returns (bytes memory) { bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call.value(value)(callData); require(success, "oneLINK::executeTransaction: Transaction execution reverted."); return returnData; } }
easy function transfer ETH (not WETH)
function safeTransferETH(address to, uint value) public linkLPGov { require(success, 'ETH_TRANSFER_FAILED'); }
12,765,769
/** *Submitted for verification at Etherscan.io on 2018-07-03 */ pragma solidity 0.4.18; // File: contracts/ERC20Interface.sol // https://github.com/ethereum/EIPs/issues/20 interface ERC20 { function totalSupply() public view returns (uint supply); function balanceOf(address _owner) public view returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint remaining); function decimals() public view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } // File: contracts/KyberNetworkInterface.sol /// @title Kyber Network interface interface KyberNetworkInterface { function maxGasPrice() public view returns(uint); function getUserCapInWei(address user) public view returns(uint); function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint); function enabled() public view returns(bool); function info(bytes32 id) public view returns(uint); function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) public view returns (uint expectedRate, uint slippageRate); function tradeWithHint(address trader, ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId, bytes hint) public payable returns(uint); } // File: contracts/KyberNetworkProxyInterface.sol /// @title Kyber Network interface interface KyberNetworkProxyInterface { function maxGasPrice() public view returns(uint); function getUserCapInWei(address user) public view returns(uint); function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint); function enabled() public view returns(bool); function info(bytes32 id) public view returns(uint); function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) public view returns (uint expectedRate, uint slippageRate); function tradeWithHint(ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId, bytes hint) public payable returns(uint); } // File: contracts/SimpleNetworkInterface.sol /// @title simple interface for Kyber Network interface SimpleNetworkInterface { function swapTokenToToken(ERC20 src, uint srcAmount, ERC20 dest, uint minConversionRate) public returns(uint); function swapEtherToToken(ERC20 token, uint minConversionRate) public payable returns(uint); function swapTokenToEther(ERC20 token, uint srcAmount, uint minConversionRate) public returns(uint); } // File: contracts/Utils.sol /// @title Kyber constants contract contract Utils { ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); uint constant internal PRECISION = (10**18); uint constant internal MAX_QTY = (10**28); // 10B tokens uint constant internal MAX_RATE = (PRECISION * 10**6); // up to 1M tokens per ETH uint constant internal MAX_DECIMALS = 18; uint constant internal ETH_DECIMALS = 18; mapping(address=>uint) internal decimals; function setDecimals(ERC20 token) internal { if (token == ETH_TOKEN_ADDRESS) decimals[token] = ETH_DECIMALS; else decimals[token] = token.decimals(); } function getDecimals(ERC20 token) internal view returns(uint) { if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access uint tokenDecimals = decimals[token]; // technically, there might be token with decimals 0 // moreover, very possible that old tokens have decimals 0 // these tokens will just have higher gas fees. if(tokenDecimals == 0) return token.decimals(); return tokenDecimals; } function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) { require(srcQty <= MAX_QTY); require(rate <= MAX_RATE); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION; } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals))); } } function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) { require(dstQty <= MAX_QTY); require(rate <= MAX_RATE); //source quantity is rounded up. to avoid dest quantity being too low. uint numerator; uint denominator; if (srcDecimals >= dstDecimals) { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals))); denominator = rate; } else { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); numerator = (PRECISION * dstQty); denominator = (rate * (10**(dstDecimals - srcDecimals))); } return (numerator + denominator - 1) / denominator; //avoid rounding down errors } } // File: contracts/Utils2.sol contract Utils2 is Utils { /// @dev get the balance of a user. /// @param token The token type /// @return The balance function getBalance(ERC20 token, address user) public view returns(uint) { if (token == ETH_TOKEN_ADDRESS) return user.balance; else return token.balanceOf(user); } function getDecimalsSafe(ERC20 token) internal returns(uint) { if (decimals[token] == 0) { setDecimals(token); } return decimals[token]; } function calcDestAmount(ERC20 src, ERC20 dest, uint srcAmount, uint rate) internal view returns(uint) { return calcDstQty(srcAmount, getDecimals(src), getDecimals(dest), rate); } function calcSrcAmount(ERC20 src, ERC20 dest, uint destAmount, uint rate) internal view returns(uint) { return calcSrcQty(destAmount, getDecimals(src), getDecimals(dest), rate); } function calcRateFromQty(uint srcAmount, uint destAmount, uint srcDecimals, uint dstDecimals) internal pure returns(uint) { require(srcAmount <= MAX_QTY); require(destAmount <= MAX_QTY); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount)); } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount); } } } // File: contracts/PermissionGroups.sol contract PermissionGroups { address public admin; address public pendingAdmin; mapping(address=>bool) internal operators; mapping(address=>bool) internal alerters; address[] internal operatorsGroup; address[] internal alertersGroup; uint constant internal MAX_GROUP_SIZE = 50; function PermissionGroups() public { admin = msg.sender; } modifier onlyAdmin() { require(msg.sender == admin); _; } modifier onlyOperator() { require(operators[msg.sender]); _; } modifier onlyAlerter() { require(alerters[msg.sender]); _; } function getOperators () external view returns(address[]) { return operatorsGroup; } function getAlerters () external view returns(address[]) { return alertersGroup; } event TransferAdminPending(address pendingAdmin); /** * @dev Allows the current admin to set the pendingAdmin address. * @param newAdmin The address to transfer ownership to. */ function transferAdmin(address newAdmin) public onlyAdmin { require(newAdmin != address(0)); TransferAdminPending(pendingAdmin); pendingAdmin = newAdmin; } /** * @dev Allows the current admin to set the admin in one tx. Useful initial deployment. * @param newAdmin The address to transfer ownership to. */ function transferAdminQuickly(address newAdmin) public onlyAdmin { require(newAdmin != address(0)); TransferAdminPending(newAdmin); AdminClaimed(newAdmin, admin); admin = newAdmin; } event AdminClaimed( address newAdmin, address previousAdmin); /** * @dev Allows the pendingAdmin address to finalize the change admin process. */ function claimAdmin() public { require(pendingAdmin == msg.sender); AdminClaimed(pendingAdmin, admin); admin = pendingAdmin; pendingAdmin = address(0); } event AlerterAdded (address newAlerter, bool isAdd); function addAlerter(address newAlerter) public onlyAdmin { require(!alerters[newAlerter]); // prevent duplicates. require(alertersGroup.length < MAX_GROUP_SIZE); AlerterAdded(newAlerter, true); alerters[newAlerter] = true; alertersGroup.push(newAlerter); } function removeAlerter (address alerter) public onlyAdmin { require(alerters[alerter]); alerters[alerter] = false; for (uint i = 0; i < alertersGroup.length; ++i) { if (alertersGroup[i] == alerter) { alertersGroup[i] = alertersGroup[alertersGroup.length - 1]; alertersGroup.length--; AlerterAdded(alerter, false); break; } } } event OperatorAdded(address newOperator, bool isAdd); function addOperator(address newOperator) public onlyAdmin { require(!operators[newOperator]); // prevent duplicates. require(operatorsGroup.length < MAX_GROUP_SIZE); OperatorAdded(newOperator, true); operators[newOperator] = true; operatorsGroup.push(newOperator); } function removeOperator (address operator) public onlyAdmin { require(operators[operator]); operators[operator] = false; for (uint i = 0; i < operatorsGroup.length; ++i) { if (operatorsGroup[i] == operator) { operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1]; operatorsGroup.length -= 1; OperatorAdded(operator, false); break; } } } } // File: contracts/Withdrawable.sol /** * @title Contracts that should be able to recover tokens or ethers * @author Ilan Doron * @dev This allows to recover any tokens or Ethers received in a contract. * This will prevent any accidental loss of tokens. */ contract Withdrawable is PermissionGroups { event TokenWithdraw(ERC20 token, uint amount, address sendTo); /** * @dev Withdraw all ERC20 compatible tokens * @param token ERC20 The address of the token contract */ function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin { require(token.transfer(sendTo, amount)); TokenWithdraw(token, amount, sendTo); } event EtherWithdraw(uint amount, address sendTo); /** * @dev Withdraw Ethers */ function withdrawEther(uint amount, address sendTo) external onlyAdmin { sendTo.transfer(amount); EtherWithdraw(amount, sendTo); } } // File: contracts/KyberNetworkProxy.sol //////////////////////////////////////////////////////////////////////////////////////////////////////// /// @title Kyber Network proxy for main contract contract KyberNetworkProxy is KyberNetworkProxyInterface, SimpleNetworkInterface, Withdrawable, Utils2 { KyberNetworkInterface public kyberNetworkContract; function KyberNetworkProxy(address _admin) public { require(_admin != address(0)); admin = _admin; } /// @notice use token address ETH_TOKEN_ADDRESS for ether /// @dev makes a trade between src and dest token and send dest token to destAddress /// @param src Src token /// @param srcAmount amount of src tokens /// @param dest Destination token /// @param destAddress Address to send tokens to /// @param maxDestAmount A limit on the amount of dest tokens /// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled. /// @param walletId is the wallet ID to send part of the fees /// @return amount of actual dest tokens function trade( ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId ) public payable returns(uint) { bytes memory hint; return tradeWithHint( src, srcAmount, dest, destAddress, maxDestAmount, minConversionRate, walletId, hint ); } /// @dev makes a trade between src and dest token and send dest tokens to msg sender /// @param src Src token /// @param srcAmount amount of src tokens /// @param dest Destination token /// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled. /// @return amount of actual dest tokens function swapTokenToToken( ERC20 src, uint srcAmount, ERC20 dest, uint minConversionRate ) public returns(uint) { bytes memory hint; return tradeWithHint( src, srcAmount, dest, msg.sender, MAX_QTY, minConversionRate, 0, hint ); } /// @dev makes a trade from Ether to token. Sends token to msg sender /// @param token Destination token /// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled. /// @return amount of actual dest tokens function swapEtherToToken(ERC20 token, uint minConversionRate) public payable returns(uint) { bytes memory hint; return tradeWithHint( ETH_TOKEN_ADDRESS, msg.value, token, msg.sender, MAX_QTY, minConversionRate, 0, hint ); } /// @dev makes a trade from token to Ether, sends Ether to msg sender /// @param token Src token /// @param srcAmount amount of src tokens /// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled. /// @return amount of actual dest tokens function swapTokenToEther(ERC20 token, uint srcAmount, uint minConversionRate) public returns(uint) { bytes memory hint; return tradeWithHint( token, srcAmount, ETH_TOKEN_ADDRESS, msg.sender, MAX_QTY, minConversionRate, 0, hint ); } struct UserBalance { uint srcBalance; uint destBalance; } event ExecuteTrade(address indexed trader, ERC20 src, ERC20 dest, uint actualSrcAmount, uint actualDestAmount); /// @notice use token address ETH_TOKEN_ADDRESS for ether /// @dev makes a trade between src and dest token and send dest token to destAddress /// @param src Src token /// @param srcAmount amount of src tokens /// @param dest Destination token /// @param destAddress Address to send tokens to /// @param maxDestAmount A limit on the amount of dest tokens /// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled. /// @param walletId is the wallet ID to send part of the fees /// @param hint will give hints for the trade. /// @return amount of actual dest tokens function tradeWithHint( ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId, bytes hint ) public payable returns(uint) { require(src == ETH_TOKEN_ADDRESS || msg.value == 0); UserBalance memory userBalanceBefore; userBalanceBefore.srcBalance = getBalance(src, msg.sender); userBalanceBefore.destBalance = getBalance(dest, destAddress); if (src == ETH_TOKEN_ADDRESS) { userBalanceBefore.srcBalance += msg.value; } else { require(src.transferFrom(msg.sender, kyberNetworkContract, srcAmount)); } uint reportedDestAmount = kyberNetworkContract.tradeWithHint.value(msg.value)( msg.sender, src, srcAmount, dest, destAddress, maxDestAmount, minConversionRate, walletId, hint ); TradeOutcome memory tradeOutcome = calculateTradeOutcome( userBalanceBefore.srcBalance, userBalanceBefore.destBalance, src, dest, destAddress ); require(reportedDestAmount == tradeOutcome.userDeltaDestAmount); require(tradeOutcome.userDeltaDestAmount <= maxDestAmount); require(tradeOutcome.actualRate >= minConversionRate); ExecuteTrade(msg.sender, src, dest, tradeOutcome.userDeltaSrcAmount, tradeOutcome.userDeltaDestAmount); return tradeOutcome.userDeltaDestAmount; } event KyberNetworkSet(address newNetworkContract, address oldNetworkContract); function setKyberNetworkContract(KyberNetworkInterface _kyberNetworkContract) public onlyAdmin { require(_kyberNetworkContract != address(0)); KyberNetworkSet(_kyberNetworkContract, kyberNetworkContract); kyberNetworkContract = _kyberNetworkContract; } function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) public view returns(uint expectedRate, uint slippageRate) { return kyberNetworkContract.getExpectedRate(src, dest, srcQty); } function getUserCapInWei(address user) public view returns(uint) { return kyberNetworkContract.getUserCapInWei(user); } function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint) { return kyberNetworkContract.getUserCapInTokenWei(user, token); } function maxGasPrice() public view returns(uint) { return kyberNetworkContract.maxGasPrice(); } function enabled() public view returns(bool) { return kyberNetworkContract.enabled(); } function info(bytes32 field) public view returns(uint) { return kyberNetworkContract.info(field); } struct TradeOutcome { uint userDeltaSrcAmount; uint userDeltaDestAmount; uint actualRate; } function calculateTradeOutcome (uint srcBalanceBefore, uint destBalanceBefore, ERC20 src, ERC20 dest, address destAddress) internal returns(TradeOutcome outcome) { uint userSrcBalanceAfter; uint userDestBalanceAfter; userSrcBalanceAfter = getBalance(src, msg.sender); userDestBalanceAfter = getBalance(dest, destAddress); //protect from underflow require(userDestBalanceAfter > destBalanceBefore); require(srcBalanceBefore > userSrcBalanceAfter); outcome.userDeltaDestAmount = userDestBalanceAfter - destBalanceBefore; outcome.userDeltaSrcAmount = srcBalanceBefore - userSrcBalanceAfter; outcome.actualRate = calcRateFromQty( outcome.userDeltaSrcAmount, outcome.userDeltaDestAmount, getDecimalsSafe(src), getDecimalsSafe(dest) ); } }
makes a trade between src and dest token and send dest tokens to msg sender src Src token srcAmount amount of src tokens dest Destination token minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled. return amount of actual dest tokens
function swapTokenToToken( ERC20 src, uint srcAmount, ERC20 dest, uint minConversionRate ) public returns(uint) { bytes memory hint; return tradeWithHint( src, srcAmount, dest, msg.sender, MAX_QTY, minConversionRate, 0, hint ); }
950,346
pragma solidity ^0.4.26; contract TomoGame { function payoutBet(uint256 betData, uint256 entropy) public view returns (uint256, uint16, uint256); } contract TomoCasinoGames { uint8 constant MAXIMUM_RUNNING_GAMES = 100; // EVM BLOCKHASH opcode can query no further than 256 blocks into the // past. Given that settleBet uses block hash of placeBet as one of // complementary entropy sources, we cannot process bets older than this // threshold. On rare occasions tomodice's croupier may fail to invoke // settleBet in this timespan due to technical issues or extreme Tomochain // congestion; such bets can be refunded via invoking refundBet. uint constant BET_EXPIRATION_BLOCKS = 250; address[MAXIMUM_RUNNING_GAMES] public gameContracts; // Sicbo // blk#00 -> blk#23: place bet (45s) // blk#25 -> blk#27: settle bet (use blockhashes of 3 blocks #21 and #22 and #23) // blk#27 -> blk#30: shows result uint32[MAXIMUM_RUNNING_GAMES] public gameStartBlocks; // starting block for round 0 uint32[MAXIMUM_RUNNING_GAMES] public gameSettledBlocks; // block number used to settleBet (less than gameRoutine) uint32[MAXIMUM_RUNNING_GAMES] public gameRoutines; // number of block for one round - set 0 to disable // Player balances mapping(address => uint256) public balances; // Croupier accounts. mapping(address => bool) public croupiers; // Standard contract ownership transfer. address public owner; address private nextOwner; event Deposit(address indexed player, uint256 amount, uint256 balance); event Withdraw(address indexed player, uint256 amount, uint256 balance); event SetBalance(address indexed player, uint256 balance); event Bet(address indexed player, uint8 gameId, uint32 round, uint16 betNumber, uint256 amount, uint256 payment, uint256 balance); event DepositFund(address indexed depositor, uint256 amount); event WithdrawFund(address indexed beneficiary, uint256 amount); // Constructor constructor () public { owner = msg.sender; } // Standard modifier on methods invokable only by contract owner. modifier onlyOwner { require(msg.sender == owner, "OnlyOwner methods called by non-owner."); _; } // Standard modifier on methods invokable only by contract owner. modifier onlyCroupier { require(croupiers[msg.sender], "OnlyCroupier methods called by non-croupier."); _; } // Standard contract ownership transfer implementation, function approveNextOwner(address _nextOwner) external onlyOwner { require(_nextOwner != owner, "Cannot approve current owner."); nextOwner = _nextOwner; } function acceptNextOwner() external { require(msg.sender == nextOwner, "Can only accept preapproved new owner."); owner = nextOwner; } // Set/unset the croupier address. function setCroupier(address croupier, bool croupierStatus) external onlyOwner { croupiers[croupier] = croupierStatus; } // user's deposit function() external payable { balances[msg.sender] = safeAdd(balances[msg.sender], msg.value); emit Deposit(msg.sender, msg.value, balances[msg.sender]); } function withdraw(address beneficiary, uint256 amount) external onlyOwner { require(balances[beneficiary] >= amount, "Exceed balance."); balances[beneficiary] = safeSub(balances[beneficiary], amount); require(beneficiary.send(amount), "Sending failed"); emit Withdraw(beneficiary, amount, balances[beneficiary]); } // Banker deposits fund. Do not increase the sender's balance. function depositFund() external payable { emit DepositFund(msg.sender, msg.value); } function setBalance(address player, uint256 newBalance) external onlyOwner { balances[player] = newBalance; emit SetBalance(player, newBalance); } function setGameInfo(uint8 gameId, address gameContract, uint32 gameStartBlock, uint32 gameSettledBlock, uint32 gameRoutine) external onlyOwner { require(gameId >= 0 && gameId < MAXIMUM_RUNNING_GAMES, "gameId not in range."); gameContracts[gameId] = gameContract; gameStartBlocks[gameId] = gameStartBlock; gameSettledBlocks[gameId] = gameSettledBlock; gameRoutines[gameId] = gameRoutine; } // Contract may be destroyed only when there are no ongoing bets, // either settled or refunded. All funds are transferred to contract owner. function kill() external onlyOwner { selfdestruct(owner); } // This is the method used to settle 99% of the time. To process a bet with "commit" (sent to player), // settleBet should supply a "reveal" number that would Keccak256-hash to // "commit". "blockHash" is the block hash of placeBet block as seen by croupier; it // is additionally asserted to prevent changing the bet outcomes on Tomochain reorgs. function settleBets(uint8 gameId, uint32 round, uint16 numBets, address[] players, uint256[] bets) external onlyCroupier { uint32 settledBlockNumber = gameStartBlocks[gameId] + round * gameRoutines[gameId] + gameSettledBlocks[gameId]; require(block.number > settledBlockNumber + 2, "settleBet too early."); require(block.number <= settledBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); bytes32 sha3BlockHashes = keccak256(abi.encodePacked(blockhash(settledBlockNumber), blockhash(settledBlockNumber + 1), blockhash(settledBlockNumber + 2))); settleBetsCommon(gameId, round, numBets, players, bets, (uint256) (sha3BlockHashes)); } // This is the method used to settle 0.1% of bets left with passed blockHash seen by croupier // It needs player to trust croupier and can only be executed after between [BET_EXPIRATION_BLOCKS, 100 * BET_EXPIRATION_BLOCKS] function settlesBetLate(uint8 gameId, uint32 round, uint16 numBets, address[] players, uint256[] bets, uint256 entropyBlockHashes) external onlyCroupier { require(block.number >= gameStartBlocks[gameId] + (round + 1) * gameRoutines[gameId] + BET_EXPIRATION_BLOCKS, "block.number needs to be after BET_EXPIRATION_BLOCKS"); settleBetsCommon(gameId, round, numBets, players, bets, entropyBlockHashes); } function settleBetsCommon(uint8 gameId, uint32 round, uint16 numBets, address[] memory players, uint256[] memory bets, uint256 entropyBlockHashes) private { require(players.length == numBets, "players.length must equal to numBets."); require(bets.length == numBets, "bets.length must equal to numBets."); address gameContract = gameContracts[gameId]; uint16 i; for (i = 0; i < numBets; i++) { address player = players[i]; payoutBet(gameId, round, gameContract, player, bets[i], entropyBlockHashes); } } event Payout(uint256 betData, uint256 entropy); function payoutBet(uint8 gameId, uint32 round, address gameContract, address player, uint256 betData, uint256 entropyBlockHashes) private { emit Payout(betData, entropyBlockHashes); uint256 amount; uint16 betNumber; uint256 payMultipler; (amount, betNumber, payMultipler) = TomoGame(gameContract).payoutBet(betData, entropyBlockHashes); uint256 payment; if (payMultipler > 0) { payment = safeMul(amount, payMultipler); balances[player] = safeAdd(balances[player], payment); } balances[player] = safeSub(balances[player], amount); emit Bet(player, gameId, round, betNumber, amount, payment, balances[player]); } event EmergencyERC20Drain(address token, address owner, uint256 amount); // owner can drain tokens that are sent here by mistake function emergencyERC20Drain(ERC20 token, uint amount) external onlyOwner { emit EmergencyERC20Drain(address(token), owner, amount); token.transfer(owner, amount); } function safeMul(uint a, uint b) private pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) private pure returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) private pure returns (uint) { uint c = a + b; assert(c >= a && c >= b); return c; } } contract ERC20 { function transfer(address _to, uint256 _value) public returns (bool); }
This is the method used to settle 99% of the time. To process a bet with "commit" (sent to player), settleBet should supply a "reveal" number that would Keccak256-hash to "commit". "blockHash" is the block hash of placeBet block as seen by croupier; it is additionally asserted to prevent changing the bet outcomes on Tomochain reorgs.
function settleBets(uint8 gameId, uint32 round, uint16 numBets, address[] players, uint256[] bets) external onlyCroupier { uint32 settledBlockNumber = gameStartBlocks[gameId] + round * gameRoutines[gameId] + gameSettledBlocks[gameId]; require(block.number > settledBlockNumber + 2, "settleBet too early."); require(block.number <= settledBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); bytes32 sha3BlockHashes = keccak256(abi.encodePacked(blockhash(settledBlockNumber), blockhash(settledBlockNumber + 1), blockhash(settledBlockNumber + 2))); settleBetsCommon(gameId, round, numBets, players, bets, (uint256) (sha3BlockHashes)); }
922,464
./full_match/80001/0x5828C287320288e130740ed538f3852fAD13995D/sources/contracts/oracles/template/OracleManagerFixedEpoch.sol
TODO: make name of this function more descriptive and aligned! TODO: should we not be passing around epoch indexes rather than timestamps? TODO: make naming more clear by specifying renaming 'currentEpochTimestamp' to 'currentEpochStartTimestamp'
function updateCurrentEpochTimestamp(uint32 lastEpochTimestamp) public view virtual returns (uint32 currentEpochTimestamp, uint32 numberOfEpochsSinceLastEpoch) { currentEpochTimestamp = uint32(getEpochStartTimestamp()); numberOfEpochsSinceLastEpoch = uint32( (currentEpochTimestamp - lastEpochTimestamp) / EPOCH_LENGTH ); }
846,061
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface IToken { function balanceOf(address tokenOwner) external view returns (uint256 balance); function transfer(address to, uint256 tokens) external returns (bool success); function approve(address spender, uint256 tokens) external returns (bool success); function transferFrom( address from, address to, uint256 tokens ) external returns (bool success); function burn(uint256 amount) external; } interface CudlFinance { function claimMiningRewards(uint256 nftId) external; function buyAccesory(uint256 nftId, uint256 id) external; function itemPrice(uint256 itemId) external view returns (uint256); function lastTimeMined(uint256 petId) external view returns (uint256); } interface IERC721 { function safeTransferFrom( address from, address to, uint256 tokenId ) external; } contract Lottery { using SafeMath for uint256; CudlFinance public immutable cudlFinance; IToken public immutable cudl; uint256 public food; uint256 public nftOriginId; mapping(uint256 => address[]) public players; mapping(uint256 => mapping(address => uint256)) public ticketsByPlayers; uint256 public currentPet = 0; uint256 public currentRound = 0; uint256 public end = 0; uint256 public start = 0; uint256 public randomBlockSize = 3; address winner1; address winner2; address winner3; address winner4; address public owner; // overflow uint256 public MAX_INT = 2**256 - 1; event LotteryStarted( uint256 round, uint256 start, uint256 end, uint256 petId, uint256 foodId ); event LotteryEnded( uint256 round, uint256 petId, uint256 cudlPrize, address winner1, address winner2, address winner3, address winner4 ); event LotteryTicketBought(address participant, uint256 tickets); constructor() public { cudlFinance = CudlFinance(0x9c10AeD865b63f0A789ae64041581EAc63458209); cudl = IToken(0xeCD20F0EBC3dA5E514b4454E3dc396E7dA18cA6A); owner = msg.sender; } function startLottery( uint256 _food, uint256 _days, uint256 _petId, uint256 _nftOriginId ) external { require(msg.sender == owner, "!owner"); food = _food; currentRound = currentRound + 1; end = now + _days * 1 days; start = now; cudl.approve(address(cudlFinance), MAX_INT); currentPet = _petId; nftOriginId = _nftOriginId; emit LotteryStarted(currentRound, start, end, currentPet, food); } function getInfos(address player) public view returns ( uint256 _participants, uint256 _end, uint256 _start, uint256 _cudlSize, uint256 _food, uint256 _currentPet, uint256 _foodPrice, uint256 _ownerTickets, uint256 _currentRound ) { _participants = players[currentRound].length; _end = end; _start = start; _cudlSize = cudl.balanceOf(address(this)); _food = food; _currentPet = currentPet; _foodPrice = cudlFinance.itemPrice(food); _ownerTickets = ticketsByPlayers[currentRound][player]; _currentRound = currentRound; } function buyTicket(address _player) external { require(start != 0, "The lottery did not start yet"); if (now > end) { endLottery(); return; } uint256 lastTimeMined = cudlFinance.lastTimeMined(currentPet); uint8 tickets = 1; require( cudl.transferFrom( msg.sender, address(this), cudlFinance.itemPrice(food) ) ); cudlFinance.buyAccesory(currentPet, food); // We mine if possible, the person that get the feeding transaction gets an extra ticket if (lastTimeMined + 1 days < now) { cudlFinance.claimMiningRewards(currentPet); tickets = 2; } for (uint256 i = 0; i < tickets; i++) { players[currentRound].push(_player); ticketsByPlayers[currentRound][_player] = ticketsByPlayers[currentRound][_player] + 1; } emit LotteryTicketBought(_player, tickets); } function endLottery() public { require(now > end && end != 0); uint256 cudlBalance = cudl.balanceOf(address(this)); end = 0; start = 0; // pick first winner (the vNFT) winner1 = players[currentRound][ randomNumber(block.number, players[currentRound].length) ]; IERC721(0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69).safeTransferFrom( address(this), winner1, nftOriginId ); // pick second winner (50% cudl) winner2 = players[currentRound][ randomNumber(block.number - 1, players[currentRound].length) ]; require(cudl.transfer(winner2, cudlBalance.mul(37).div(100))); // pick third winner (25% cudl) winner3 = players[currentRound][ randomNumber(block.number - 3, players[currentRound].length) ]; require(cudl.transfer(winner3, cudlBalance.mul(19).div(100))); // pick fourth winner (25% cudl) winner4 = players[currentRound][ randomNumber(block.number - 4, players[currentRound].length) ]; require(cudl.transfer(winner4, cudlBalance.mul(19).div(100))); //burn the leftover (25%) cudl.burn(cudl.balanceOf(address(this))); emit LotteryEnded( currentRound, currentPet, cudlBalance, winner1, winner2, winner3, winner4 ); } /* generates a number from 0 to 2^n based on the last n blocks */ function randomNumber(uint256 seed, uint256 max) public view returns (uint256 _randomNumber) { uint256 n = 0; for (uint256 i = 0; i < randomBlockSize; i++) { if ( uint256( keccak256( abi.encodePacked(blockhash(block.number - i - 1), seed) ) ) % 2 == 0 ) n += 2**i; } return n % max; } }
pick first winner (the vNFT) pick second winner (50% cudl) pick third winner (25% cudl) pick fourth winner (25% cudl)burn the leftover (25%)
function endLottery() public { require(now > end && end != 0); uint256 cudlBalance = cudl.balanceOf(address(this)); end = 0; start = 0; winner1 = players[currentRound][ randomNumber(block.number, players[currentRound].length) ]; IERC721(0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69).safeTransferFrom( address(this), winner1, nftOriginId ); winner2 = players[currentRound][ randomNumber(block.number - 1, players[currentRound].length) ]; require(cudl.transfer(winner2, cudlBalance.mul(37).div(100))); winner3 = players[currentRound][ randomNumber(block.number - 3, players[currentRound].length) ]; require(cudl.transfer(winner3, cudlBalance.mul(19).div(100))); winner4 = players[currentRound][ randomNumber(block.number - 4, players[currentRound].length) ]; require(cudl.transfer(winner4, cudlBalance.mul(19).div(100))); cudl.burn(cudl.balanceOf(address(this))); emit LotteryEnded( currentRound, currentPet, cudlBalance, winner1, winner2, winner3, winner4 ); }
13,831,845
./partial_match/4/0x3346Db7F33DF0196D073A79e60c2c0E975152164/sources/Dotc.sol
只能由第一轮或第二轮仲裁合同调整保证金 @_who == 1 扣除商家的保证金,@_who == 2 扣除用户的保证金,
function setComp( uint256 i, uint256 _who, uint256 _comp) external { require(Tima <= sub(block.timestamp, users[i].tima) && (users[i].timc == 0 || users[i].pau == 1 || users[i].pau == 2) , "Dotc/not-arbtime"); require(users[i].mma >0, "Dotc/mar-not"); require(_who == 1 || _who == 2, "Dotc/who-invite"); require(arbone == msg.sender || arbtwo == msg.sender, "Dotc/not-invite"); comp[i] = _comp ; who[i] = _who ; users[i].timo = 3 ; }
8,508,942
./full_match/97/0xb0b2dD90491Bc9091604793321b98aC863dE8C0C/sources/project_/contracts/CollectionMethods.sol
Repays the withdrawn validator funds and transfers back token on full repayment. _tokenId The Id of the token. _erc20Contract The address of the funds to be repaid. _amount The amount to be repaid./ Send payment to the Pool
function Repay( uint256 _tokenId, address _erc20Contract, uint256 _amount ) external nonReentrant { require(NFTowner[_tokenId] == msg.sender); require(erc20Balances[_tokenId][_erc20Contract] != 0); require(_amount <= withdrawnAmount[_tokenId]); require( IERC20(_erc20Contract).transferFrom( msg.sender, address(this), _amount ), "failed" ); withdrawnAmount[_tokenId] -= _amount; if (withdrawnAmount[_tokenId] == 0) { ERC721Upgradeable(address(this)).safeTransferFrom( address(this), msg.sender, _tokenId ); } emit ValidatorFundsRepayed( msg.sender, _tokenId, _erc20Contract, _amount ); }
3,282,901
/** *Submitted for verification at Etherscan.io on 2022-02-20 */ // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success,) = recipient.call{value : amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value : value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // File: @openzeppelin/contracts/utils/cryptography/draft-EIP712.sol // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) pragma solidity ^0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; address private immutable _CACHED_THIS; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // File: hardhat/console.sol 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)); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: erc721a/contracts/ERC721A.sol // Creator: Chiru Labs pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error BurnedQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); 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 override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _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 { _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 { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: @openzeppelin/contracts/finance/PaymentSplitter.sol // OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol) pragma solidity ^0.8.0; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/WhiteList.sol pragma solidity ^0.8.0; contract WhiteList is Ownable, EIP712 { bytes32 constant public MINT_CALL_HASH_TYPE = keccak256("mint(address receiver)"); address public whitelistSigner; constructor() EIP712("WWCWhiteList", "1") {} function setWhitelistSigner(address _address) external onlyOwner { whitelistSigner = _address; } function recoverSigner(address sender, bytes memory signature) public view returns (address) { return ECDSA.recover(getDigest(sender), signature); } function getDigest(address sender) public view returns (bytes32) { bytes32 messageDigest = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", ECDSA.toTypedDataHash(_domainSeparatorV4(), keccak256(abi.encode(MINT_CALL_HASH_TYPE, sender)) ))); return messageDigest; } modifier isUserWhileList(address sender, bytes memory signature) { require(recoverSigner(sender, signature) == whitelistSigner , "User is not on whitelist" ); _; } function getDomainSeparatorV4() external view onlyOwner returns (bytes32) { return _domainSeparatorV4(); } } // File: contracts/PreSales.sol pragma solidity ^0.8.0; contract PreSales is Ownable { uint256 public preSalesStartTime; uint256 public preSalesEndTime; modifier isPreSalesActive() { require( isPreSalesActivated(), "PreSalesActivation: Sale is not activated" ); _; } constructor() { //20 Feb 2022 09:00:00 EST == 20 Feb 2022 11:00:00 GMT at this site https://www.epochconverter.com/ preSalesStartTime = 1645365600; //20 Feb 2022 20:59:59 EST == 20 Feb 2022 22:59:59 GMT at this site https://www.epochconverter.com/ preSalesEndTime = 1645408799; } function isPreSalesActivated() public view returns (bool) { return preSalesStartTime > 0 && preSalesEndTime > 0 && block.timestamp >= preSalesStartTime && block.timestamp <= preSalesEndTime; } // 1645365600: start time at 20 Feb 2022 09:00:00 EST in seconds // 1645408799: end time at 20 Feb 2022 20:59:59 EST in seconds function setPreSalesTime(uint256 _startTime, uint256 _endTime) external onlyOwner { require( _endTime >= _startTime, "PreSalesActivation: End time should be later than start time" ); preSalesStartTime = _startTime; preSalesEndTime = _endTime; } } // File: contracts/PublicSales.sol pragma solidity ^0.8.0; contract PublicSales is Ownable { uint256 public publicSalesStartTime; modifier isPublicSalesActive() { require( isPublicSalesActivated(), "PublicSalesActivation: Sale is not activated" ); _; } constructor() { //20 Feb 2022 23:00:00 GMT == 20 Feb 2022 21:00:00 GMT at this site https://www.epochconverter.com/ publicSalesStartTime = 1645408800; } function isPublicSalesActivated() public view returns (bool) { return publicSalesStartTime > 0 && block.timestamp >= publicSalesStartTime; } // 1644069600: start time at 05 Feb 2022 (2 PM UTC+0) in seconds function setPublicSalesTime(uint256 _startTime) external onlyOwner { publicSalesStartTime = _startTime; } } // File: contracts/WWC.sol //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract TestWarriors is Ownable, PublicSales, PreSales, WhiteList, ERC721A, PaymentSplitter { //FOR PRODUCTION uint256 public constant TOTAL_MAX_QTY = 2222; uint256 public constant GIFT_MAX_QTY = 122; uint256 public constant SALES_MAX_QTY = TOTAL_MAX_QTY - GIFT_MAX_QTY; uint256 public constant PRESALES_MAX_QTY = 2100; uint256 public constant PRE_SALES_PRICE = 0.006 ether; uint256 public constant PUBLIC_SALES_PRICE = 0.0065 ether; uint256 public constant MAX_QTY_PER_MINTER = 4; uint256 public constant MAX_QTY_PER_MINT = 4; uint256 public constant MAX_QTY_PER_MINTER_PRE_SALES = 4; address[] private addressList = [0xD5cB70f89b90D6D494051C9ee5e1FCfF25D23490]; uint256[] private shareList = [100]; uint256 public preSalesMintedQty = 0; uint256 public publicSalesMintedQty = 0; uint256 public giftedQty = 0; mapping(address => uint256) public preSalesMinterToTokenQty; mapping(address => uint256) public publicSalesMinterToTokenQty; bool public canRenounceOwnership = false; bool public paused = true; bool public revealed = false; string private baseTokenURI; string private notRevealedUri; constructor(string memory _notRevealedUri) ERC721A("TestWarriors", "WWC") PaymentSplitter(addressList, shareList) { notRevealedUri = _notRevealedUri; } function getPrice() public view returns (uint256) { if (isPublicSalesActivated()) { return PUBLIC_SALES_PRICE; } return PRE_SALES_PRICE; } function preSalesMint( uint256 _mintQty, bytes memory signature ) external payable isPreSalesActive isUserWhileList(msg.sender, signature) { require( preSalesMintedQty + publicSalesMintedQty + _mintQty <= TOTAL_MAX_QTY, "Exceed sales max limit" ); require( preSalesMintedQty + _mintQty <= PRESALES_MAX_QTY, "Exceed pre-sales max limit" ); require( preSalesMinterToTokenQty[msg.sender] + _mintQty <= MAX_QTY_PER_MINTER_PRE_SALES, "Exceed signed quantity" ); require(tx.origin == msg.sender, "CONTRACTS_NOT_ALLOWED_TO_MINT"); require(!paused, "The contract is paused!"); require(msg.value >= _mintQty * getPrice(), "Incorrect ETH"); preSalesMinterToTokenQty[msg.sender] += _mintQty; preSalesMintedQty += _mintQty; _safeMint(msg.sender, _mintQty); } function publicSalesMint(uint256 _mintQty) external payable isPublicSalesActive { require( preSalesMintedQty + publicSalesMintedQty + _mintQty <= SALES_MAX_QTY, "Exceed sales max limit" ); require(_mintQty <= MAX_QTY_PER_MINT, "Exceed max mint per mint."); require( publicSalesMinterToTokenQty[msg.sender] + _mintQty <= MAX_QTY_PER_MINTER, "Exceed max mint per minter" ); require(tx.origin == msg.sender, "CONTRACTS_NOT_ALLOWED_TO_MINT"); require(!paused, "The contract is paused!"); require(msg.value >= _mintQty * getPrice(), "Incorrect ETH"); publicSalesMinterToTokenQty[msg.sender] += _mintQty; publicSalesMintedQty += _mintQty; _safeMint(msg.sender, _mintQty); } function gift(address[] calldata receivers) external onlyOwner { require( giftedQty + receivers.length <= GIFT_MAX_QTY, "Exceed gift max limit" ); giftedQty += receivers.length; for (uint256 i = 0; i < receivers.length; i++) { _safeMint(receivers[i], 1); } } function setNotRevealedURI(string memory _notRevealedURI) external onlyOwner { notRevealedUri = _notRevealedURI; } function setBaseTokenURI(string memory _baseTokenURI) external onlyOwner { baseTokenURI = _baseTokenURI; } function _baseURI() internal view override virtual returns (string memory) { return baseTokenURI; } function setRevealed(bool _state) external onlyOwner { revealed = _state; } function setPaused(bool _state) external onlyOwner { paused = _state; } function setCanRenounceOwnership(bool _state) external onlyOwner { canRenounceOwnership = _state; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (!revealed) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, Strings.toString(tokenId))) : ""; } function renounceOwnership() override public onlyOwner { require(canRenounceOwnership, "Not the time to Renounce Ownership"); _transferOwnership(address(0)); } function withdraw() public payable onlyOwner { (bool success,) = payable(msg.sender).call{value : address(this).balance}(""); require(success); } function withdrawSplit() public onlyOwner { for (uint256 i = 0; i < addressList.length; i++) { address payable wallet = payable(addressList[i]); release(wallet); } } }
1645365600: start time at 20 Feb 2022 09:00:00 EST in seconds 1645408799: end time at 20 Feb 2022 20:59:59 EST in seconds
function setPreSalesTime(uint256 _startTime, uint256 _endTime) external onlyOwner { require( _endTime >= _startTime, "PreSalesActivation: End time should be later than start time" ); preSalesStartTime = _startTime; preSalesEndTime = _endTime; }
6,319,354
./partial_match/8453/0xCD9C9b40D757b56359e19563203D3bc64089638d/sources/contracts/past-versions/PublicLockV13.sol
Allows a lock manager to add or remove an event hook/
function setEventHooks( address _onKeyPurchaseHook, address _onKeyCancelHook, address _onValidKeyHook, address _onTokenURIHook, address _onKeyTransferHook, address _onKeyExtendHook, address _onKeyGrantHook ) external { _onlyLockManager(); if (_onKeyPurchaseHook != address(0) && !_onKeyPurchaseHook.isContract()) { revert INVALID_HOOK(0); } if (_onKeyCancelHook != address(0) && !_onKeyCancelHook.isContract()) { revert INVALID_HOOK(1); } if (_onValidKeyHook != address(0) && !_onValidKeyHook.isContract()) { revert INVALID_HOOK(2); } if (_onTokenURIHook != address(0) && !_onTokenURIHook.isContract()) { revert INVALID_HOOK(3); } if (_onKeyTransferHook != address(0) && !_onKeyTransferHook.isContract()) { revert INVALID_HOOK(4); } if (_onKeyExtendHook != address(0) && !_onKeyExtendHook.isContract()) { revert INVALID_HOOK(5); } if (_onKeyGrantHook != address(0) && !_onKeyGrantHook.isContract()) { revert INVALID_HOOK(6); } onKeyPurchaseHook = ILockKeyPurchaseHook(_onKeyPurchaseHook); onKeyCancelHook = ILockKeyCancelHook(_onKeyCancelHook); onTokenURIHook = ILockTokenURIHook(_onTokenURIHook); onValidKeyHook = ILockValidKeyHook(_onValidKeyHook); onKeyTransferHook = ILockKeyTransferHook(_onKeyTransferHook); onKeyExtendHook = ILockKeyExtendHook(_onKeyExtendHook); onKeyGrantHook = ILockKeyGrantHook(_onKeyGrantHook); emit EventHooksUpdated( _onKeyPurchaseHook, _onKeyCancelHook, _onValidKeyHook, _onTokenURIHook, _onKeyTransferHook, _onKeyExtendHook, _onKeyGrantHook ); }
16,778,746
pragma solidity ^0.5.0; import "./SampleToken.sol"; import "./MultiOwnable.sol"; contract BYODex is MultiOwnable { using SafeMath for uint256; //TODO: //events SampleToken public token; //how many tokens for one ether, e.g. 900 uint256 public buyRate; //how many tokens for one ether, e.g. 1000 uint256 public sellRate; bool public isTradingPaused; constructor(SampleToken _token, uint256 _buyRate, uint256 _sellRate) public { require(_buyRate < _sellRate, "buyRate should be smaller then sellRate"); token = _token; buyRate = _buyRate; sellRate = _sellRate; isTradingPaused = false; } function () external payable { //to allow ether deposits //event? } function buyTokens(uint256 _expectedBuyRate) public payable { require(!isTradingPaused, "trading is paused"); //to prevent unexpected changes of rate require(_expectedBuyRate == buyRate, "the buyRate is different from expected"); require(msg.value > 0, "must be sending non zero eth value"); uint256 totalTokens = msg.value.mul(buyRate).mul(10**uint256(token.decimals())).div(10**uint256(18)); require(token.transfer(msg.sender, totalTokens), "failed to transfer tokens to user"); } //needs approval function sellTokens(uint256 _expectedSellRate, uint256 _tokenAmount) public { require(!isTradingPaused, "trading is paused"); //to prevent unexpected changes of rate require(_expectedSellRate == sellRate, "the sellRate is different from expected"); require(token.transferFrom(msg.sender, address(this), _tokenAmount), "could not transfer tokens, no allowance?"); uint256 totalEth = _tokenAmount.mul(10**uint256(18)).div(10**uint256(token.decimals())).div(sellRate); msg.sender.transfer(totalEth); } function updateRates(uint256 _buyRate, uint256 _sellRate) public anyOwner { require(_buyRate <= _sellRate, "buyRate should not be greater then sellRate"); buyRate = _buyRate; sellRate = _sellRate; } function withdrawTokens(uint256 _tokenAmount) public anyOwner { require(token.transfer(msg.sender, _tokenAmount), "token withdrawal failed"); } function withdrawEther(uint256 _ethAmount) public anyOwner { msg.sender.transfer(_ethAmount); } function pauseTrading() public anyOwner { require(!isTradingPaused, "trading has been paused already"); isTradingPaused = true; } function resumeTrading() public anyOwner { require(isTradingPaused, "trading has resumed already"); isTradingPaused = false; } //convenience function, checks the current token balance of this exchange instance function tokenBalance() external view returns (uint256) { return token.balanceOf(address(this)); } }
to prevent unexpected changes of rate
function buyTokens(uint256 _expectedBuyRate) public payable { require(!isTradingPaused, "trading is paused"); require(_expectedBuyRate == buyRate, "the buyRate is different from expected"); require(msg.value > 0, "must be sending non zero eth value"); uint256 totalTokens = msg.value.mul(buyRate).mul(10**uint256(token.decimals())).div(10**uint256(18)); require(token.transfer(msg.sender, totalTokens), "failed to transfer tokens to user"); }
12,684,277
./full_match/1/0x0Eb638648207D00b9025684d13B1cB53806deBe4/sources/contracts/NIL.sol
this method is responsible for taking all fee, if takeFee is true only whitelisted accounts buy or sender can trade
function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!canTrade) { if (!(whitelist[sender] || whitelist[recipient])) { require(sender == owner()); } } if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); }
2,980,760
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./AMM.sol"; import "../lib/CappedPool.sol"; import "../lib/CombinedActionsGuard.sol"; import "../interfaces/IPriceProvider.sol"; import "../interfaces/IIVProvider.sol"; import "../interfaces/IBlackScholes.sol"; import "../interfaces/IIVGuesser.sol"; import "../interfaces/IPodOption.sol"; import "../interfaces/IOptionAMMPool.sol"; import "../interfaces/IFeePool.sol"; import "../interfaces/IConfigurationManager.sol"; import "../interfaces/IEmergencyStop.sol"; import "../interfaces/IFeePoolBuilder.sol"; import "../options/rewards/AaveIncentives.sol"; /** * Represents an Option specific single-sided AMM. * * The tokenA MUST be an PodOption contract implementation. * The tokenB is preferable to be an stable asset such as DAI or USDC. * * There are 4 external contracts used by this contract: * * - priceProvider: responsible for the the spot price of the option's underlying asset. * - priceMethod: responsible for the current price of the option itself. * - impliedVolatility: responsible for one of the priceMethod inputs: * implied Volatility * - feePoolA and feePoolB: responsible for handling Liquidity providers fees. */ contract OptionAMMPool is AMM, IOptionAMMPool, CappedPool, CombinedActionsGuard, ReentrancyGuard, AaveIncentives { using SafeMath for uint256; uint256 public constant PRICING_DECIMALS = 18; uint256 private constant _SECONDS_IN_A_YEAR = 31536000; uint256 private constant _ORACLE_IV_WEIGHT = 3; uint256 private constant _POOL_IV_WEIGHT = 1; // External Contracts /** * @notice store globally accessed configurations */ IConfigurationManager public immutable configurationManager; /** * @notice responsible for handling Liquidity providers fees of the token A */ IFeePool public immutable feePoolA; /** * @notice responsible for handling Liquidity providers fees of the token B */ IFeePool public immutable feePoolB; // Option Info struct PriceProperties { uint256 expiration; uint256 startOfExerciseWindow; uint256 strikePrice; address underlyingAsset; IPodOption.OptionType optionType; uint256 currentIV; int256 riskFree; uint256 initialIVGuess; } /** * @notice priceProperties are all information needed to handle the price discovery method * most of the properties will be used by getABPrice */ PriceProperties public priceProperties; event TradeInfo(uint256 spotPrice, uint256 newIV); constructor( address _optionAddress, address _stableAsset, uint256 _initialIV, IConfigurationManager _configurationManager, IFeePoolBuilder _feePoolBuilder ) public AMM(_optionAddress, _stableAsset) CappedPool(_configurationManager) AaveIncentives(_configurationManager) { require( IPodOption(_optionAddress).exerciseType() == IPodOption.ExerciseType.EUROPEAN, "Pool: invalid exercise type" ); feePoolA = _feePoolBuilder.buildFeePool(_stableAsset, 10, 3, address(this)); feePoolB = _feePoolBuilder.buildFeePool(_stableAsset, 10, 3, address(this)); priceProperties.currentIV = _initialIV; priceProperties.initialIVGuess = _initialIV; priceProperties.underlyingAsset = IPodOption(_optionAddress).underlyingAsset(); priceProperties.expiration = IPodOption(_optionAddress).expiration(); priceProperties.startOfExerciseWindow = IPodOption(_optionAddress).startOfExerciseWindow(); priceProperties.optionType = IPodOption(_optionAddress).optionType(); uint256 strikePrice = IPodOption(_optionAddress).strikePrice(); uint256 strikePriceDecimals = IPodOption(_optionAddress).strikePriceDecimals(); require(strikePriceDecimals <= PRICING_DECIMALS, "Pool: invalid strikePrice unit"); require(tokenBDecimals() <= PRICING_DECIMALS, "Pool: invalid tokenB unit"); uint256 strikePriceWithRightDecimals = strikePrice.mul(10**(PRICING_DECIMALS - strikePriceDecimals)); priceProperties.strikePrice = strikePriceWithRightDecimals; configurationManager = IConfigurationManager(_configurationManager); } /** * @notice addLiquidity in any proportion of tokenA or tokenB * * @dev This function can only be called before option expiration * * @param amountOfA amount of TokenA to add * @param amountOfB amount of TokenB to add * @param owner address of the account that will have ownership of the liquidity */ function addLiquidity( uint256 amountOfA, uint256 amountOfB, address owner ) external override capped(tokenB(), amountOfB) { require(msg.sender == configurationManager.getOptionHelper() || msg.sender == owner, "AMM: invalid sender"); _nonCombinedActions(); _beforeStartOfExerciseWindow(); _emergencyStopCheck(); _addLiquidity(amountOfA, amountOfB, owner); _emitTradeInfo(); } /** * @notice removeLiquidity in any proportion of tokenA or tokenB * * @param amountOfA amount of TokenA to add * @param amountOfB amount of TokenB to add */ function removeLiquidity(uint256 amountOfA, uint256 amountOfB) external override nonReentrant { _nonCombinedActions(); _emergencyStopCheck(); _removeLiquidity(amountOfA, amountOfB); _emitTradeInfo(); } /** * @notice withdrawRewards claims reward from Aave and send to admin * @dev should only be called by the admin power * */ function withdrawRewards() external override { require(msg.sender == configurationManager.owner(), "not owner"); address[] memory assets = new address[](1); assets[0] = this.tokenB(); _claimRewards(assets); address rewardAsset = _parseAddressFromUint(configurationManager.getParameter("REWARD_ASSET")); uint256 rewardsToSend = _rewardBalance(); IERC20(rewardAsset).safeTransfer(msg.sender, rewardsToSend); } /** * @notice tradeExactAInput msg.sender is able to trade exact amount of token A in exchange for minimum * amount of token B and send the tokens B to the owner. After that, this function also updates the * priceProperties.* currentIV * * @dev initialIVGuess is a parameter for gas saving costs purpose. Instead of calculating the new implied volatility * out of thin ar, caller can help the Numeric Method achieve the result in less iterations with this parameter. * In order to know which guess the caller should use, call the getOptionTradeDetailsExactAInput first. * * @param exactAmountAIn exact amount of A token that will be transfer from msg.sender * @param minAmountBOut minimum acceptable amount of token B to transfer to owner * @param owner the destination address that will receive the token B * @param initialIVGuess The first guess that the Numeric Method (getPutIV / getCallIV) should use */ function tradeExactAInput( uint256 exactAmountAIn, uint256 minAmountBOut, address owner, uint256 initialIVGuess ) external override nonReentrant returns (uint256) { _nonCombinedActions(); _beforeStartOfExerciseWindow(); _emergencyStopCheck(); priceProperties.initialIVGuess = initialIVGuess; uint256 amountBOut = _tradeExactAInput(exactAmountAIn, minAmountBOut, owner); _emitTradeInfo(); return amountBOut; } /** * @notice _tradeExactAOutput owner is able to receive exact amount of token A in exchange of a max * acceptable amount of token B transfer from the msg.sender. After that, this function also updates * the priceProperties.currentIV * * @dev initialIVGuess is a parameter for gas saving costs purpose. Instead of calculating the new implied volatility * out of thin ar, caller can help the Numeric Method achieve the result in less iterations with this parameter. * In order to know which guess the caller should use, call the getOptionTradeDetailsExactAOutput first. * * @param exactAmountAOut exact amount of token A that will be transfer to owner * @param maxAmountBIn maximum acceptable amount of token B to transfer from msg.sender * @param owner the destination address that will receive the token A * @param initialIVGuess The first guess that the Numeric Method (getPutIV / getCallIV) should use */ function tradeExactAOutput( uint256 exactAmountAOut, uint256 maxAmountBIn, address owner, uint256 initialIVGuess ) external override nonReentrant returns (uint256) { _nonCombinedActions(); _beforeStartOfExerciseWindow(); _emergencyStopCheck(); priceProperties.initialIVGuess = initialIVGuess; uint256 amountBIn = _tradeExactAOutput(exactAmountAOut, maxAmountBIn, owner); _emitTradeInfo(); return amountBIn; } /** * @notice _tradeExactBInput msg.sender is able to trade exact amount of token B in exchange for minimum * amount of token A sent to the owner. After that, this function also updates the priceProperties.currentIV * * @dev initialIVGuess is a parameter for gas saving costs purpose. Instead of calculating the new implied volatility * out of thin ar, caller can help the Numeric Method achieve the result ini less iterations with this parameter. * In order to know which guess the caller should use, call the getOptionTradeDetailsExactBInput first. * * @param exactAmountBIn exact amount of token B that will be transfer from msg.sender * @param minAmountAOut minimum acceptable amount of token A to transfer to owner * @param owner the destination address that will receive the token A * @param initialIVGuess The first guess that the Numeric Method (getPutIV / getCallIV) should use */ function tradeExactBInput( uint256 exactAmountBIn, uint256 minAmountAOut, address owner, uint256 initialIVGuess ) external override nonReentrant returns (uint256) { _nonCombinedActions(); _beforeStartOfExerciseWindow(); _emergencyStopCheck(); priceProperties.initialIVGuess = initialIVGuess; uint256 amountAOut = _tradeExactBInput(exactAmountBIn, minAmountAOut, owner); _emitTradeInfo(); return amountAOut; } /** * @notice _tradeExactBOutput owner is able to receive exact amount of token B in exchange of a max * acceptable amount of token A transfer from msg.sender. After that, this function also updates the * priceProperties.currentIV * * @dev initialIVGuess is a parameter for gas saving costs purpose. Instead of calculating the new implied volatility * out of thin ar, caller can help the Numeric Method achieve the result ini less iterations with this parameter. * In order to know which guess the caller should use, call the getOptionTradeDetailsExactBOutput first. * * @param exactAmountBOut exact amount of token B that will be transfer to owner * @param maxAmountAIn maximum acceptable amount of token A to transfer from msg.sender * @param owner the destination address that will receive the token B * @param initialIVGuess The first guess that the Numeric Method (getPutIV / getCallIV) should use */ function tradeExactBOutput( uint256 exactAmountBOut, uint256 maxAmountAIn, address owner, uint256 initialIVGuess ) external override nonReentrant returns (uint256) { _nonCombinedActions(); _beforeStartOfExerciseWindow(); _emergencyStopCheck(); priceProperties.initialIVGuess = initialIVGuess; uint256 amountAIn = _tradeExactBOutput(exactAmountBOut, maxAmountAIn, owner); _emitTradeInfo(); return amountAIn; } /** * @notice getRemoveLiquidityAmounts external function that returns the available for rescue * amounts of token A, and token B based on the original position * * @param percentA percent of exposition of Token A to be removed * @param percentB percent of exposition of Token B to be removed * @param user Opening Value Factor by the moment of the deposit * * @return withdrawAmountA the total amount of token A that will be rescued * @return withdrawAmountB the total amount of token B that will be rescued plus fees */ function getRemoveLiquidityAmounts( uint256 percentA, uint256 percentB, address user ) external override view returns (uint256 withdrawAmountA, uint256 withdrawAmountB) { (uint256 poolWithdrawAmountA, uint256 poolWithdrawAmountB) = _getRemoveLiquidityAmounts( percentA, percentB, user ); (uint256 feeSharesA, uint256 feeSharesB) = _getAmountOfFeeShares(percentA, percentB, user); uint256 feesWithdrawAmountA = 0; uint256 feesWithdrawAmountB = 0; if (feeSharesA > 0) { (, feesWithdrawAmountA) = feePoolA.getWithdrawAmount(user, feeSharesA); } if (feeSharesB > 0) { (, feesWithdrawAmountB) = feePoolB.getWithdrawAmount(user, feeSharesB); } withdrawAmountA = poolWithdrawAmountA; withdrawAmountB = poolWithdrawAmountB.add(feesWithdrawAmountA).add(feesWithdrawAmountB); return (withdrawAmountA, withdrawAmountB); } /** * @notice getABPrice This function wll call internal function _getABPrice that will calculate the * calculate the ABPrice based on current market conditions. It calculates only the unit price AB, not taking in * consideration the slippage. * * @return ABPrice ABPrice is the unit price AB. Meaning how many units of B, buys 1 unit of A */ function getABPrice() external override view returns (uint256 ABPrice) { return _getABPrice(); } /** * @notice getAdjustedIV This function will return the adjustedIV, which is an average * between the pool IV and an external oracle IV * * @return adjustedIV The average between pool's IV and external oracle IV */ function getAdjustedIV() external override view returns (uint256 adjustedIV) { return _getAdjustedIV(tokenA(), priceProperties.currentIV); } /** * @notice getOptionTradeDetailsExactAInput view function that simulates a trade, in order the preview * the amountBOut, the new implied volatility, that will be used as the initialIVGuess if caller wants to perform * a trade in sequence. Also returns the amount of Fees that will be payed to liquidity pools A and B. * * @param exactAmountAIn amount of token A that will by transfer from msg.sender to the pool * * @return amountBOut amount of B in exchange of the exactAmountAIn * @return newIV the new implied volatility that this trade will result * @return feesTokenA amount of fees of collected by token A * @return feesTokenB amount of fees of collected by token B */ function getOptionTradeDetailsExactAInput(uint256 exactAmountAIn) external override view returns ( uint256 amountBOut, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB ) { return _getOptionTradeDetailsExactAInput(exactAmountAIn); } /** * @notice getOptionTradeDetailsExactAOutput view function that simulates a trade, in order the preview * the amountBIn, the new implied volatility, that will be used as the initialIVGuess if caller wants to perform * a trade in sequence. Also returns the amount of Fees that will be payed to liquidity pools A and B. * * @param exactAmountAOut amount of token A that will by transfer from pool to the msg.sender/owner * * @return amountBIn amount of B that will be transfer from msg.sender to the pool * @return newIV the new implied volatility that this trade will result * @return feesTokenA amount of fees of collected by token A * @return feesTokenB amount of fees of collected by token B */ function getOptionTradeDetailsExactAOutput(uint256 exactAmountAOut) external override view returns ( uint256 amountBIn, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB ) { return _getOptionTradeDetailsExactAOutput(exactAmountAOut); } /** * @notice getOptionTradeDetailsExactBInput view function that simulates a trade, in order the preview * the amountAOut, the new implied volatility, that will be used as the initialIVGuess if caller wants to perform * a trade in sequence. Also returns the amount of Fees that will be payed to liquidity pools A and B. * * @param exactAmountBIn amount of token B that will by transfer from msg.sender to the pool * * @return amountAOut amount of A that will be transfer from contract to owner * @return newIV the new implied volatility that this trade will result * @return feesTokenA amount of fees of collected by token A * @return feesTokenB amount of fees of collected by token B */ function getOptionTradeDetailsExactBInput(uint256 exactAmountBIn) external override view returns ( uint256 amountAOut, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB ) { return _getOptionTradeDetailsExactBInput(exactAmountBIn); } /** * @notice getOptionTradeDetailsExactBOutput view function that simulates a trade, in order the preview * the amountAIn, the new implied volatility, that will be used as the initialIVGuess if caller wants to perform * a trade in sequence. Also returns the amount of Fees that will be payed to liquidity pools A and B. * * @param exactAmountBOut amount of token B that will by transfer from pool to the msg.sender/owner * * @return amountAIn amount of A that will be transfer from msg.sender to the pool * @return newIV the new implied volatility that this trade will result * @return feesTokenA amount of fees of collected by token A * @return feesTokenB amount of fees of collected by token B */ function getOptionTradeDetailsExactBOutput(uint256 exactAmountBOut) external override view returns ( uint256 amountAIn, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB ) { return _getOptionTradeDetailsExactBOutput(exactAmountBOut); } function _getOptionTradeDetailsExactAInput(uint256 exactAmountAIn) internal view returns ( uint256, uint256, uint256, uint256 ) { (uint256 newABPrice, uint256 spotPrice, uint256 timeToMaturity) = _getPriceDetails(); if (newABPrice == 0) { return (0, 0, 0, 0); } (uint256 poolAmountA, uint256 poolAmountB) = _getPoolAmounts(newABPrice); uint256 amountBOutPool = _getAmountBOutPool(exactAmountAIn, poolAmountA, poolAmountB); uint256 newTargetABPrice = _getNewTargetPrice(newABPrice, exactAmountAIn, amountBOutPool, TradeDirection.AB); // Prevents the pool to sell an option under the minimum target price, // because it causes an infinite loop when trying to calculate newIV if (!_isValidTargetPrice(newTargetABPrice, spotPrice)) { return (0, 0, 0, 0); } uint256 newIV = _getNewIV(newTargetABPrice, spotPrice, timeToMaturity); uint256 feesTokenA = feePoolA.getCollectable(amountBOutPool, poolAmountB); uint256 feesTokenB = feePoolB.getCollectable(amountBOutPool, poolAmountB); uint256 amountBOutUser = amountBOutPool.sub(feesTokenA).sub(feesTokenB); return (amountBOutUser, newIV, feesTokenA, feesTokenB); } function _getOptionTradeDetailsExactAOutput(uint256 exactAmountAOut) internal view returns ( uint256, uint256, uint256, uint256 ) { (uint256 newABPrice, uint256 spotPrice, uint256 timeToMaturity) = _getPriceDetails(); if (newABPrice == 0) { return (0, 0, 0, 0); } (uint256 poolAmountA, uint256 poolAmountB) = _getPoolAmounts(newABPrice); uint256 amountBInPool = _getAmountBInPool(exactAmountAOut, poolAmountA, poolAmountB); uint256 newTargetABPrice = _getNewTargetPrice(newABPrice, exactAmountAOut, amountBInPool, TradeDirection.BA); uint256 feesTokenA = feePoolA.getCollectable(amountBInPool, poolAmountB); uint256 feesTokenB = feePoolB.getCollectable(amountBInPool, poolAmountB); uint256 amountBInUser = amountBInPool.add(feesTokenA).add(feesTokenB); uint256 newIV = _getNewIV(newTargetABPrice, spotPrice, timeToMaturity); return (amountBInUser, newIV, feesTokenA, feesTokenB); } function _getOptionTradeDetailsExactBInput(uint256 exactAmountBIn) internal view returns ( uint256, uint256, uint256, uint256 ) { (uint256 newABPrice, uint256 spotPrice, uint256 timeToMaturity) = _getPriceDetails(); if (newABPrice == 0) { return (0, 0, 0, 0); } (uint256 poolAmountA, uint256 poolAmountB) = _getPoolAmounts(newABPrice); uint256 feesTokenA = feePoolA.getCollectable(exactAmountBIn, poolAmountB); uint256 feesTokenB = feePoolB.getCollectable(exactAmountBIn, poolAmountB); uint256 totalFees = feesTokenA.add(feesTokenB); uint256 poolBIn = exactAmountBIn.sub(totalFees); uint256 amountAOutPool = _getAmountAOutPool(poolBIn, poolAmountA, poolAmountB); uint256 newTargetABPrice = _getNewTargetPrice(newABPrice, amountAOutPool, poolBIn, TradeDirection.BA); uint256 newIV = _getNewIV(newTargetABPrice, spotPrice, timeToMaturity); return (amountAOutPool, newIV, feesTokenA, feesTokenB); } function _getOptionTradeDetailsExactBOutput(uint256 exactAmountBOut) internal view returns ( uint256, uint256, uint256, uint256 ) { (uint256 newABPrice, uint256 spotPrice, uint256 timeToMaturity) = _getPriceDetails(); if (newABPrice == 0) { return (0, 0, 0, 0); } (uint256 poolAmountA, uint256 poolAmountB) = _getPoolAmounts(newABPrice); uint256 feesTokenA = feePoolA.getCollectable(exactAmountBOut, poolAmountB); uint256 feesTokenB = feePoolB.getCollectable(exactAmountBOut, poolAmountB); uint256 totalFees = feesTokenA.add(feesTokenB); uint256 poolBOut = exactAmountBOut.add(totalFees); uint256 amountAInPool = _getAmountAInPool(poolBOut, poolAmountA, poolAmountB); uint256 newTargetABPrice = _getNewTargetPrice(newABPrice, amountAInPool, poolBOut, TradeDirection.AB); // Prevents the pool to sell an option under the minimum target price, // because it causes an infinite loop when trying to calculate newIV if (!_isValidTargetPrice(newTargetABPrice, spotPrice)) { return (0, 0, 0, 0); } uint256 newIV = _getNewIV(newTargetABPrice, spotPrice, timeToMaturity); return (amountAInPool, newIV, feesTokenA, feesTokenB); } function _getPriceDetails() internal view returns ( uint256, uint256, uint256 ) { uint256 timeToMaturity = _getTimeToMaturityInYears(); if (timeToMaturity == 0) { return (0, 0, 0); } uint256 spotPrice = _getSpotPrice(priceProperties.underlyingAsset, PRICING_DECIMALS); uint256 adjustedIV = _getAdjustedIV(tokenA(), priceProperties.currentIV); IBlackScholes pricingMethod = IBlackScholes(configurationManager.getPricingMethod()); uint256 newABPrice; if (priceProperties.optionType == IPodOption.OptionType.PUT) { newABPrice = pricingMethod.getPutPrice( spotPrice, priceProperties.strikePrice, adjustedIV, timeToMaturity, priceProperties.riskFree ); } else { newABPrice = pricingMethod.getCallPrice( spotPrice, priceProperties.strikePrice, adjustedIV, timeToMaturity, priceProperties.riskFree ); } if (newABPrice == 0) { return (0, spotPrice, timeToMaturity); } uint256 newABPriceWithDecimals = newABPrice.div(10**(PRICING_DECIMALS.sub(tokenBDecimals()))); return (newABPriceWithDecimals, spotPrice, timeToMaturity); } /** * @dev returns maturity in years with 18 decimals */ function _getTimeToMaturityInYears() internal view returns (uint256) { if (block.timestamp >= priceProperties.expiration) { return 0; } return priceProperties.expiration.sub(block.timestamp).mul(10**PRICING_DECIMALS).div(_SECONDS_IN_A_YEAR); } function _getPoolAmounts(uint256 newABPrice) internal view returns (uint256 poolAmountA, uint256 poolAmountB) { (uint256 totalAmountA, uint256 totalAmountB) = _getPoolBalances(); if (newABPrice != 0) { poolAmountA = _min(totalAmountA, totalAmountB.mul(10**uint256(tokenADecimals())).div(newABPrice)); poolAmountB = _min(totalAmountB, totalAmountA.mul(newABPrice).div(10**uint256(tokenADecimals()))); } return (poolAmountA, poolAmountB); } function _getABPrice() internal override view returns (uint256) { (uint256 newABPrice, , ) = _getPriceDetails(); return newABPrice; } function _getSpotPrice(address asset, uint256 decimalsOutput) internal view returns (uint256) { IPriceProvider priceProvider = IPriceProvider(configurationManager.getPriceProvider()); uint256 spotPrice = priceProvider.getAssetPrice(asset); uint256 spotPriceDecimals = priceProvider.getAssetDecimals(asset); uint256 diffDecimals; uint256 spotPriceWithRightPrecision; if (decimalsOutput <= spotPriceDecimals) { diffDecimals = spotPriceDecimals.sub(decimalsOutput); spotPriceWithRightPrecision = spotPrice.div(10**diffDecimals); } else { diffDecimals = decimalsOutput.sub(spotPriceDecimals); spotPriceWithRightPrecision = spotPrice.mul(10**diffDecimals); } return spotPriceWithRightPrecision; } function _getOracleIV(address optionAddress) internal view returns (uint256 normalizedOracleIV) { IIVProvider ivProvider = IIVProvider(configurationManager.getIVProvider()); (, , uint256 oracleIV, uint256 ivDecimals) = ivProvider.getIV(optionAddress); uint256 diffDecimals; if (ivDecimals <= PRICING_DECIMALS) { diffDecimals = PRICING_DECIMALS.sub(ivDecimals); } else { diffDecimals = ivDecimals.sub(PRICING_DECIMALS); } return oracleIV.div(10**diffDecimals); } function _getAdjustedIV(address optionAddress, uint256 currentIV) internal view returns (uint256 adjustedIV) { uint256 oracleIV = _getOracleIV(optionAddress); adjustedIV = _ORACLE_IV_WEIGHT.mul(oracleIV).add(_POOL_IV_WEIGHT.mul(currentIV)).div( _POOL_IV_WEIGHT + _ORACLE_IV_WEIGHT ); } function _getNewIV( uint256 newTargetABPrice, uint256 spotPrice, uint256 timeToMaturity ) internal view returns (uint256) { uint256 newTargetABPriceWithDecimals = newTargetABPrice.mul(10**(PRICING_DECIMALS.sub(tokenBDecimals()))); uint256 newIV; IIVGuesser ivGuesser = IIVGuesser(configurationManager.getIVGuesser()); if (priceProperties.optionType == IPodOption.OptionType.PUT) { (newIV, ) = ivGuesser.getPutIV( newTargetABPriceWithDecimals, priceProperties.initialIVGuess, spotPrice, priceProperties.strikePrice, timeToMaturity, priceProperties.riskFree ); } else { (newIV, ) = ivGuesser.getCallIV( newTargetABPriceWithDecimals, priceProperties.initialIVGuess, spotPrice, priceProperties.strikePrice, timeToMaturity, priceProperties.riskFree ); } return newIV; } /** * @dev After it gets the unit BlackScholes price, it applies slippage based on the minimum available in the pool * (returned by the _getPoolAmounts()) and the product constant curve. * @param amountBOutPool The exact amount of tokenB will leave the pool * @param poolAmountA The amount of A available for trade * @param poolAmountB The amount of B available for trade * @return amountAInPool The amount of tokenA(options) will enter the pool */ function _getAmountAInPool( uint256 amountBOutPool, uint256 poolAmountA, uint256 poolAmountB ) internal pure returns (uint256 amountAInPool) { uint256 productConstant = poolAmountA.mul(poolAmountB); require(amountBOutPool < poolAmountB, "AMM: insufficient liquidity"); amountAInPool = productConstant.div(poolAmountB.sub(amountBOutPool)).sub(poolAmountA); } /** * @dev After it gets the unit BlackScholes price, it applies slippage based on the minimum available in the pool * (returned by the _getPoolAmounts()) and the product constant curve. * @param amountBInPool The exact amount of tokenB will enter the pool * @param poolAmountA The amount of A available for trade * @param poolAmountB The amount of B available for trade * @return amountAOutPool The amount of tokenA(options) will leave the pool */ function _getAmountAOutPool( uint256 amountBInPool, uint256 poolAmountA, uint256 poolAmountB ) internal pure returns (uint256 amountAOutPool) { uint256 productConstant = poolAmountA.mul(poolAmountB); amountAOutPool = poolAmountA.sub(productConstant.div(poolAmountB.add(amountBInPool))); } /** * @dev After it gets the unit BlackScholes price, it applies slippage based on the minimum available in the pool * (returned by the _getPoolAmounts()) and the product constant curve. * @param amountAOutPool The amount of tokenA(options) will leave the pool * @param poolAmountA The amount of A available for trade * @param poolAmountB The amount of B available for trade * @return amountBInPool The amount of tokenB will enter the pool */ function _getAmountBInPool( uint256 amountAOutPool, uint256 poolAmountA, uint256 poolAmountB ) internal pure returns (uint256 amountBInPool) { uint256 productConstant = poolAmountA.mul(poolAmountB); require(amountAOutPool < poolAmountA, "AMM: insufficient liquidity"); amountBInPool = productConstant.div(poolAmountA.sub(amountAOutPool)).sub(poolAmountB); } /** * @dev After it gets the unit BlackScholes price, it applies slippage based on the minimum available in the pool * (returned by the _getPoolAmounts()) and the product constant curve. * @param amountAInPool The exact amount of tokenA(options) will enter the pool * @param poolAmountA The amount of A available for trade * @param poolAmountB The amount of B available for trade * @return amountBOutPool The amount of tokenB will leave the pool */ function _getAmountBOutPool( uint256 amountAInPool, uint256 poolAmountA, uint256 poolAmountB ) internal pure returns (uint256 amountBOutPool) { uint256 productConstant = poolAmountA.mul(poolAmountB); amountBOutPool = poolAmountB.sub(productConstant.div(poolAmountA.add(amountAInPool))); } /** * @dev Based on the tokensA and tokensB leaving or entering the pool, it is possible to calculate the new option * target price. That price will be used later to update the currentIV. * @param newABPrice calculated Black Scholes unit price (how many units of tokenB, to buy 1 tokenA(option)) * @param amountA The amount of tokenA that will leave or enter the pool * @param amountB TThe amount of tokenB that will leave or enter the pool * @param tradeDirection The trade direction, if it is AB, means that tokenA will enter, and tokenB will leave. * @return newTargetPrice The new unit target price (how many units of tokenB, to buy 1 tokenA(option)) */ function _getNewTargetPrice( uint256 newABPrice, uint256 amountA, uint256 amountB, TradeDirection tradeDirection ) internal view returns (uint256 newTargetPrice) { (uint256 poolAmountA, uint256 poolAmountB) = _getPoolAmounts(newABPrice); if (tradeDirection == TradeDirection.AB) { newTargetPrice = poolAmountB.sub(amountB).mul(10**uint256(tokenADecimals())).div(poolAmountA.add(amountA)); } else { newTargetPrice = poolAmountB.add(amountB).mul(10**uint256(tokenADecimals())).div(poolAmountA.sub(amountA)); } } function _getTradeDetailsExactAInput(uint256 exactAmountAIn) internal override returns (TradeDetails memory) { (uint256 amountBOut, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB) = _getOptionTradeDetailsExactAInput( exactAmountAIn ); TradeDetails memory tradeDetails = TradeDetails(amountBOut, feesTokenA, feesTokenB, abi.encodePacked(newIV)); return tradeDetails; } function _getTradeDetailsExactAOutput(uint256 exactAmountAOut) internal override returns (TradeDetails memory) { (uint256 amountBIn, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB) = _getOptionTradeDetailsExactAOutput( exactAmountAOut ); TradeDetails memory tradeDetails = TradeDetails(amountBIn, feesTokenA, feesTokenB, abi.encodePacked(newIV)); return tradeDetails; } function _getTradeDetailsExactBInput(uint256 exactAmountBIn) internal override returns (TradeDetails memory) { (uint256 amountAOut, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB) = _getOptionTradeDetailsExactBInput( exactAmountBIn ); TradeDetails memory tradeDetails = TradeDetails(amountAOut, feesTokenA, feesTokenB, abi.encodePacked(newIV)); return tradeDetails; } function _getTradeDetailsExactBOutput(uint256 exactAmountBOut) internal override returns (TradeDetails memory) { (uint256 amountAIn, uint256 newIV, uint256 feesTokenA, uint256 feesTokenB) = _getOptionTradeDetailsExactBOutput( exactAmountBOut ); TradeDetails memory tradeDetails = TradeDetails(amountAIn, feesTokenA, feesTokenB, abi.encodePacked(newIV)); return tradeDetails; } /** * @dev If a option is ITM, either PUTs or CALLs, the minimum price that it would cost is the difference between * the spot price and strike price. If the target price after applying slippage is above this minimum, the function * returns true. * @param newTargetPrice the new ABPrice after slippage (how many units of tokenB, to buy 1 option) * @param spotPrice current underlying asset spot price during this transaction * @return true if is a valid target price (above the minimum) */ function _isValidTargetPrice(uint256 newTargetPrice, uint256 spotPrice) internal view returns (bool) { if (priceProperties.optionType == IPodOption.OptionType.PUT) { if (spotPrice < priceProperties.strikePrice) { return newTargetPrice > priceProperties.strikePrice.sub(spotPrice).div(10**PRICING_DECIMALS.sub(tokenBDecimals())); } } else { if (spotPrice > priceProperties.strikePrice) { return newTargetPrice > spotPrice.sub(priceProperties.strikePrice).div(10**PRICING_DECIMALS.sub(tokenBDecimals())); } } return true; } function _onAddLiquidity(UserDepositSnapshot memory _userDepositSnapshot, address owner) internal override { uint256 currentQuotesA = feePoolA.sharesOf(owner); uint256 currentQuotesB = feePoolB.sharesOf(owner); uint256 amountOfQuotesAToAdd = 0; uint256 amountOfQuotesBToAdd = 0; uint256 totalQuotesA = _userDepositSnapshot.tokenABalance.mul(10**FIMP_DECIMALS).div(_userDepositSnapshot.fImp); if (totalQuotesA > currentQuotesA) { amountOfQuotesAToAdd = totalQuotesA.sub(currentQuotesA); } uint256 totalQuotesB = _userDepositSnapshot.tokenBBalance.mul(10**FIMP_DECIMALS).div(_userDepositSnapshot.fImp); if (totalQuotesB > currentQuotesB) { amountOfQuotesBToAdd = totalQuotesB.sub(currentQuotesB); } feePoolA.mint(owner, amountOfQuotesAToAdd); feePoolB.mint(owner, amountOfQuotesBToAdd); } function _onRemoveLiquidity( uint256 percentA, uint256 percentB, address owner ) internal override { (uint256 amountOfSharesAToRemove, uint256 amountOfSharesBToRemove) = _getAmountOfFeeShares( percentA, percentB, owner ); if (amountOfSharesAToRemove > 0) { feePoolA.withdraw(owner, amountOfSharesAToRemove); } if (amountOfSharesBToRemove > 0) { feePoolB.withdraw(owner, amountOfSharesBToRemove); } } function _getAmountOfFeeShares( uint256 percentA, uint256 percentB, address owner ) internal view returns (uint256, uint256) { uint256 currentSharesA = feePoolA.sharesOf(owner); uint256 currentSharesB = feePoolB.sharesOf(owner); uint256 amountOfSharesAToRemove = currentSharesA.mul(percentA).div(PERCENT_PRECISION); uint256 amountOfSharesBToRemove = currentSharesB.mul(percentB).div(PERCENT_PRECISION); return (amountOfSharesAToRemove, amountOfSharesBToRemove); } function _onTrade(TradeDetails memory tradeDetails) internal override { uint256 newIV = abi.decode(tradeDetails.params, (uint256)); priceProperties.currentIV = newIV; IERC20(tokenB()).safeTransfer(address(feePoolA), tradeDetails.feesTokenA); IERC20(tokenB()).safeTransfer(address(feePoolB), tradeDetails.feesTokenB); } /** * @dev Check for functions which are only allowed to be executed * BEFORE start of exercise window. */ function _beforeStartOfExerciseWindow() internal view { require(block.timestamp < priceProperties.startOfExerciseWindow, "Pool: exercise window has started"); } function _emergencyStopCheck() private view { IEmergencyStop emergencyStop = IEmergencyStop(configurationManager.getEmergencyStop()); require( !emergencyStop.isStopped(address(this)) && !emergencyStop.isStopped(configurationManager.getPriceProvider()) && !emergencyStop.isStopped(configurationManager.getPricingMethod()), "Pool: Pool is stopped" ); } function _emitTradeInfo() private { uint256 spotPrice = _getSpotPrice(priceProperties.underlyingAsset, PRICING_DECIMALS); emit TradeInfo(spotPrice, priceProperties.currentIV); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../lib/RequiredDecimals.sol"; import "../interfaces/IAMM.sol"; /** * Represents a generalized contract for a single-sided AMM pair. * * That means is possible to add and remove liquidity in any proportion * at any time, even 0 in one of the sides. * * The AMM is constituted by 3 core functions: Add Liquidity, Remove liquidity and Trade. * * There are 4 possible trade types between the token pair (tokenA and tokenB): * * - ExactAInput: * tokenA as an exact Input, meaning that the output tokenB is variable. * it is important to have a slippage control of the minimum acceptable amount of tokenB in return * - ExactAOutput: * tokenA as an exact Output, meaning that the input tokenB is variable. * it is important to have a slippage control of the maximum acceptable amount of tokenB sent * - ExactBInput: * tokenB as an exact Input, meaning that the output tokenA is variable. * it is important to have a slippage control of the minimum acceptable amount of tokenA in return * - ExactBOutput: * tokenB as an exact Output, meaning that the input tokenA is variable. * it is important to have a slippage control of the maximum acceptable amount of tokenA sent * * Several functions are provided as virtual and must be overridden by the inheritor. * * - _getABPrice: * function that will return the tokenA:tokenB price relation. * How many units of tokenB in order to traded for 1 unit of tokenA. * This price is represented in the same tokenB number of decimals. * - _onAddLiquidity: * Executed after adding liquidity. Usually used for handling fees * - _onRemoveLiquidity: * Executed after removing liquidity. Usually used for handling fees * * Also, for which TradeType (E.g: ExactAInput) there are more two functions to override: * _getTradeDetails[$TradeType]: * This function is responsible to return the TradeDetails struct, that contains basically the amount * of the other token depending on the trade type. (E.g: ExactAInput => The TradeDetails will return the * amount of B output). * _onTrade[$TradeType]: * function that will be executed after UserDepositSnapshot updates and before * token transfers. Usually used for handling fees and updating state at the inheritor. * */ abstract contract AMM is IAMM, RequiredDecimals { using SafeERC20 for IERC20; using SafeMath for uint256; /** * @dev The initial value for deposit factor (Fimp) */ uint256 public constant INITIAL_FIMP = 10**27; /** * @notice The Fimp's precision (aka number of decimals) */ uint256 public constant FIMP_DECIMALS = 27; /** * @notice The percent's precision */ uint256 public constant PERCENT_PRECISION = 100; /** * @dev Address of the token A */ address private _tokenA; /** * @dev Address of the token B */ address private _tokenB; /** * @dev Token A number of decimals */ uint8 private _tokenADecimals; /** * @dev Token B number of decimals */ uint8 private _tokenBDecimals; /** * @notice The total balance of token A in the pool not counting the amortization */ uint256 public deamortizedTokenABalance; /** * @notice The total balance of token B in the pool not counting the amortization */ uint256 public deamortizedTokenBBalance; /** * @notice It contains the token A original balance, token B original balance, * and the Open Value Factor (Fimp) at the time of the deposit. */ struct UserDepositSnapshot { uint256 tokenABalance; uint256 tokenBBalance; uint256 fImp; } struct Mult { uint256 AA; // How much A Im getting for rescuing one A that i've deposited uint256 AB; // How much B Im getting for rescuing one A that i've deposited uint256 BA; // How much A Im getting for rescuing one B that i've deposited uint256 BB; // How much B Im getting for rescuing one B that i've deposited } struct TradeDetails { uint256 amount; uint256 feesTokenA; uint256 feesTokenB; bytes params; } /** * @dev Tracks the UserDepositSnapshot struct of each user. * It contains the token A original balance, token B original balance, * and the Open Value Factor (Fimp) at the time of the deposit. */ mapping(address => UserDepositSnapshot) private _userSnapshots; /** Events */ event AddLiquidity(address indexed caller, address indexed owner, uint256 amountA, uint256 amountB); event RemoveLiquidity(address indexed caller, uint256 amountA, uint256 amountB); event TradeExactAInput(address indexed caller, address indexed owner, uint256 exactAmountAIn, uint256 amountBOut); event TradeExactBInput(address indexed caller, address indexed owner, uint256 exactAmountBIn, uint256 amountAOut); event TradeExactAOutput(address indexed caller, address indexed owner, uint256 amountBIn, uint256 exactAmountAOut); event TradeExactBOutput(address indexed caller, address indexed owner, uint256 amountAIn, uint256 exactAmountBOut); constructor(address tokenA, address tokenB) public { require(Address.isContract(tokenA), "AMM: token a is not a contract"); require(Address.isContract(tokenB), "AMM: token b is not a contract"); require(tokenA != tokenB, "AMM: tokens must differ"); _tokenA = tokenA; _tokenB = tokenB; _tokenADecimals = tryDecimals(IERC20(tokenA)); _tokenBDecimals = tryDecimals(IERC20(tokenB)); } /** * @dev Returns the address for tokenA */ function tokenA() public override view returns (address) { return _tokenA; } /** * @dev Returns the address for tokenB */ function tokenB() public override view returns (address) { return _tokenB; } /** * @dev Returns the decimals for tokenA */ function tokenADecimals() public override view returns (uint8) { return _tokenADecimals; } /** * @dev Returns the decimals for tokenB */ function tokenBDecimals() public override view returns (uint8) { return _tokenBDecimals; } /** * @notice getPoolBalances external function that returns the current pool balance of token A and token B * * @return totalTokenA balanceOf this contract of token A * @return totalTokenB balanceOf this contract of token B */ function getPoolBalances() external view returns (uint256 totalTokenA, uint256 totalTokenB) { return _getPoolBalances(); } /** * @notice getUserDepositSnapshot external function that User original balance of token A, * token B and the Opening Value * * Factor (Fimp) at the moment of the liquidity added * * @param user address to check the balance info * * @return tokenAOriginalBalance balance of token A by the moment of deposit * @return tokenBOriginalBalance balance of token B by the moment of deposit * @return fImpUser value of the Opening Value Factor by the moment of the deposit */ function getUserDepositSnapshot(address user) external view returns ( uint256 tokenAOriginalBalance, uint256 tokenBOriginalBalance, uint256 fImpUser ) { return _getUserDepositSnapshot(user); } /** * @notice _addLiquidity in any proportion of tokenA or tokenB * * @dev The inheritor contract should implement _getABPrice and _onAddLiquidity functions * * @param amountOfA amount of TokenA to add * @param amountOfB amount of TokenB to add * @param owner address of the account that will have ownership of the liquidity */ function _addLiquidity( uint256 amountOfA, uint256 amountOfB, address owner ) internal { _isValidAddress(owner); // Get Pool Balances (uint256 totalTokenA, uint256 totalTokenB) = _getPoolBalances(); bool hasNoLiquidity = deamortizedTokenABalance == 0 && deamortizedTokenBBalance == 0; uint256 fImpOpening; uint256 userAmountToStoreTokenA = amountOfA; uint256 userAmountToStoreTokenB = amountOfB; if (hasNoLiquidity) { // In the first liquidity, is necessary add both tokens bool bothTokensHigherThanZero = amountOfA > 0 && amountOfB > 0; require(bothTokensHigherThanZero, "AMM: invalid first liquidity"); fImpOpening = INITIAL_FIMP; deamortizedTokenABalance = amountOfA; deamortizedTokenBBalance = amountOfB; } else { // Get ABPrice uint256 ABPrice = _getABPrice(); require(ABPrice > 0, "AMM: option price zero"); // Calculate the Pool's Value Factor (Fimp) fImpOpening = _getFImpOpening( totalTokenA, totalTokenB, ABPrice, deamortizedTokenABalance, deamortizedTokenBBalance ); (userAmountToStoreTokenA, userAmountToStoreTokenB) = _getUserBalanceToStore( amountOfA, amountOfB, fImpOpening, _userSnapshots[owner] ); // Update Deamortized Balance of the pool for each token; deamortizedTokenABalance = deamortizedTokenABalance.add(amountOfA.mul(10**FIMP_DECIMALS).div(fImpOpening)); deamortizedTokenBBalance = deamortizedTokenBBalance.add(amountOfB.mul(10**FIMP_DECIMALS).div(fImpOpening)); } // Update the User Balances for each token and with the Pool Factor previously calculated UserDepositSnapshot memory userDepositSnapshot = UserDepositSnapshot( userAmountToStoreTokenA, userAmountToStoreTokenB, fImpOpening ); _userSnapshots[owner] = userDepositSnapshot; _onAddLiquidity(_userSnapshots[owner], owner); // Update Total Balance of the pool for each token if (amountOfA > 0) { IERC20(_tokenA).safeTransferFrom(msg.sender, address(this), amountOfA); } if (amountOfB > 0) { IERC20(_tokenB).safeTransferFrom(msg.sender, address(this), amountOfB); } emit AddLiquidity(msg.sender, owner, amountOfA, amountOfB); } /** * @notice _removeLiquidity in any proportion of tokenA or tokenB * @dev The inheritor contract should implement _getABPrice and _onRemoveLiquidity functions * * @param percentA proportion of the exposition of the original tokenA that want to be removed * @param percentB proportion of the exposition of the original tokenB that want to be removed */ function _removeLiquidity(uint256 percentA, uint256 percentB) internal { (uint256 userTokenABalance, uint256 userTokenBBalance, uint256 userFImp) = _getUserDepositSnapshot(msg.sender); require(percentA <= 100 && percentB <= 100, "AMM: forbidden percent"); uint256 originalBalanceAToReduce = percentA.mul(userTokenABalance).div(PERCENT_PRECISION); uint256 originalBalanceBToReduce = percentB.mul(userTokenBBalance).div(PERCENT_PRECISION); // Get Pool Balances (uint256 totalTokenA, uint256 totalTokenB) = _getPoolBalances(); // Get ABPrice uint256 ABPrice = _getABPrice(); // Calculate the Pool's Value Factor (Fimp) uint256 fImpOpening = _getFImpOpening( totalTokenA, totalTokenB, ABPrice, deamortizedTokenABalance, deamortizedTokenBBalance ); // Calculate Multipliers Mult memory multipliers = _getMultipliers(totalTokenA, totalTokenB, fImpOpening); // Update User balance _userSnapshots[msg.sender].tokenABalance = userTokenABalance.sub(originalBalanceAToReduce); _userSnapshots[msg.sender].tokenBBalance = userTokenBBalance.sub(originalBalanceBToReduce); // Update deamortized balance deamortizedTokenABalance = deamortizedTokenABalance.sub( originalBalanceAToReduce.mul(10**FIMP_DECIMALS).div(userFImp) ); deamortizedTokenBBalance = deamortizedTokenBBalance.sub( originalBalanceBToReduce.mul(10**FIMP_DECIMALS).div(userFImp) ); // Calculate amount to send (uint256 withdrawAmountA, uint256 withdrawAmountB) = _getWithdrawAmounts( originalBalanceAToReduce, originalBalanceBToReduce, userFImp, multipliers ); if (withdrawAmountA > totalTokenA) { withdrawAmountA = totalTokenA; } if (withdrawAmountB > totalTokenB) { withdrawAmountB = totalTokenB; } _onRemoveLiquidity(percentA, percentB, msg.sender); // Transfers / Update if (withdrawAmountA > 0) { IERC20(_tokenA).safeTransfer(msg.sender, withdrawAmountA); } if (withdrawAmountB > 0) { IERC20(_tokenB).safeTransfer(msg.sender, withdrawAmountB); } emit RemoveLiquidity(msg.sender, withdrawAmountA, withdrawAmountB); } /** * @notice _tradeExactAInput msg.sender is able to trade exact amount of token A in exchange for minimum * amount of token B sent by the contract to the owner * @dev The inheritor contract should implement _getTradeDetailsExactAInput and _onTradeExactAInput functions * _getTradeDetailsExactAInput should return tradeDetails struct format * * @param exactAmountAIn exact amount of A token that will be transfer from msg.sender * @param minAmountBOut minimum acceptable amount of token B to transfer to owner * @param owner the destination address that will receive the token B */ function _tradeExactAInput( uint256 exactAmountAIn, uint256 minAmountBOut, address owner ) internal returns (uint256) { _isValidInput(exactAmountAIn); _isValidAddress(owner); TradeDetails memory tradeDetails = _getTradeDetailsExactAInput(exactAmountAIn); uint256 amountBOut = tradeDetails.amount; require(amountBOut > 0, "AMM: invalid amountBOut"); require(amountBOut >= minAmountBOut, "AMM: slippage not acceptable"); _onTrade(tradeDetails); IERC20(_tokenA).safeTransferFrom(msg.sender, address(this), exactAmountAIn); IERC20(_tokenB).safeTransfer(owner, amountBOut); emit TradeExactAInput(msg.sender, owner, exactAmountAIn, amountBOut); return amountBOut; } /** * @notice _tradeExactAOutput owner is able to receive exact amount of token A in exchange of a max * acceptable amount of token B sent by the msg.sender to the contract * * @dev The inheritor contract should implement _getTradeDetailsExactAOutput and _onTradeExactAOutput functions * _getTradeDetailsExactAOutput should return tradeDetails struct format * * @param exactAmountAOut exact amount of token A that will be transfer to owner * @param maxAmountBIn maximum acceptable amount of token B to transfer from msg.sender * @param owner the destination address that will receive the token A */ function _tradeExactAOutput( uint256 exactAmountAOut, uint256 maxAmountBIn, address owner ) internal returns (uint256) { _isValidInput(maxAmountBIn); _isValidAddress(owner); TradeDetails memory tradeDetails = _getTradeDetailsExactAOutput(exactAmountAOut); uint256 amountBIn = tradeDetails.amount; require(amountBIn > 0, "AMM: invalid amountBIn"); require(amountBIn <= maxAmountBIn, "AMM: slippage not acceptable"); _onTrade(tradeDetails); IERC20(_tokenB).safeTransferFrom(msg.sender, address(this), amountBIn); IERC20(_tokenA).safeTransfer(owner, exactAmountAOut); emit TradeExactAOutput(msg.sender, owner, amountBIn, exactAmountAOut); return amountBIn; } /** * @notice _tradeExactBInput msg.sender is able to trade exact amount of token B in exchange for minimum * amount of token A sent by the contract to the owner * * @dev The inheritor contract should implement _getTradeDetailsExactBInput and _onTradeExactBInput functions * _getTradeDetailsExactBInput should return tradeDetails struct format * * @param exactAmountBIn exact amount of token B that will be transfer from msg.sender * @param minAmountAOut minimum acceptable amount of token A to transfer to owner * @param owner the destination address that will receive the token A */ function _tradeExactBInput( uint256 exactAmountBIn, uint256 minAmountAOut, address owner ) internal returns (uint256) { _isValidInput(exactAmountBIn); _isValidAddress(owner); TradeDetails memory tradeDetails = _getTradeDetailsExactBInput(exactAmountBIn); uint256 amountAOut = tradeDetails.amount; require(amountAOut > 0, "AMM: invalid amountAOut"); require(amountAOut >= minAmountAOut, "AMM: slippage not acceptable"); _onTrade(tradeDetails); IERC20(_tokenB).safeTransferFrom(msg.sender, address(this), exactAmountBIn); IERC20(_tokenA).safeTransfer(owner, amountAOut); emit TradeExactBInput(msg.sender, owner, exactAmountBIn, amountAOut); return amountAOut; } /** * @notice _tradeExactBOutput owner is able to receive exact amount of token B from the contract in exchange of a * max acceptable amount of token A sent by the msg.sender to the contract. * * @dev The inheritor contract should implement _getTradeDetailsExactBOutput and _onTradeExactBOutput functions * _getTradeDetailsExactBOutput should return tradeDetails struct format * * @param exactAmountBOut exact amount of token B that will be transfer to owner * @param maxAmountAIn maximum acceptable amount of token A to transfer from msg.sender * @param owner the destination address that will receive the token B */ function _tradeExactBOutput( uint256 exactAmountBOut, uint256 maxAmountAIn, address owner ) internal returns (uint256) { _isValidInput(maxAmountAIn); _isValidAddress(owner); TradeDetails memory tradeDetails = _getTradeDetailsExactBOutput(exactAmountBOut); uint256 amountAIn = tradeDetails.amount; require(amountAIn > 0, "AMM: invalid amountAIn"); require(amountAIn <= maxAmountAIn, "AMM: slippage not acceptable"); _onTrade(tradeDetails); IERC20(_tokenA).safeTransferFrom(msg.sender, address(this), amountAIn); IERC20(_tokenB).safeTransfer(owner, exactAmountBOut); emit TradeExactBOutput(msg.sender, owner, amountAIn, exactAmountBOut); return amountAIn; } /** * @notice _getFImpOpening Auxiliary function that calculate the Opening Value Factor Fimp * * @param _totalTokenA total contract balance of token A * @param _totalTokenB total contract balance of token B * @param _ABPrice Unit price AB, meaning, how many units of token B could buy 1 unit of token A * @param _deamortizedTokenABalance contract deamortized balance of token A * @param _deamortizedTokenBBalance contract deamortized balance of token B * @return fImpOpening Opening Value Factor Fimp */ function _getFImpOpening( uint256 _totalTokenA, uint256 _totalTokenB, uint256 _ABPrice, uint256 _deamortizedTokenABalance, uint256 _deamortizedTokenBBalance ) internal view returns (uint256) { uint256 numerator; uint256 denominator; { numerator = _totalTokenA.mul(_ABPrice).div(10**uint256(_tokenADecimals)).add(_totalTokenB).mul( 10**FIMP_DECIMALS ); } { denominator = _deamortizedTokenABalance.mul(_ABPrice).div(10**uint256(_tokenADecimals)).add( _deamortizedTokenBBalance ); } return numerator.div(denominator); } /** * @notice _getPoolBalances external function that returns the current pool balance of token A and token B * * @return totalTokenA balanceOf this contract of token A * @return totalTokenB balanceOf this contract of token B */ function _getPoolBalances() internal view returns (uint256 totalTokenA, uint256 totalTokenB) { totalTokenA = IERC20(_tokenA).balanceOf(address(this)); totalTokenB = IERC20(_tokenB).balanceOf(address(this)); } /** * @notice _getUserDepositSnapshot internal function that User original balance of token A, * token B and the Opening Value * * Factor (Fimp) at the moment of the liquidity added * * @param user address of the user that want to check the balance * * @return tokenAOriginalBalance balance of token A by the moment of deposit * @return tokenBOriginalBalance balance of token B by the moment of deposit * @return fImpOriginal value of the Opening Value Factor by the moment of the deposit */ function _getUserDepositSnapshot(address user) internal view returns ( uint256 tokenAOriginalBalance, uint256 tokenBOriginalBalance, uint256 fImpOriginal ) { tokenAOriginalBalance = _userSnapshots[user].tokenABalance; tokenBOriginalBalance = _userSnapshots[user].tokenBBalance; fImpOriginal = _userSnapshots[user].fImp; } /** * @notice _getMultipliers internal function that calculate new multipliers based on the current pool position * * mAA => How much A the users can rescue for each A they deposited * mBA => How much A the users can rescue for each B they deposited * mBB => How much B the users can rescue for each B they deposited * mAB => How much B the users can rescue for each A they deposited * * @param totalTokenA balanceOf this contract of token A * @param totalTokenB balanceOf this contract of token B * @param fImpOpening current Open Value Factor * @return multipliers multiplier struct containing the 4 multipliers: mAA, mBA, mBB, mAB */ function _getMultipliers( uint256 totalTokenA, uint256 totalTokenB, uint256 fImpOpening ) internal view returns (Mult memory multipliers) { uint256 totalTokenAWithPrecision = totalTokenA.mul(10**FIMP_DECIMALS); uint256 totalTokenBWithPrecision = totalTokenB.mul(10**FIMP_DECIMALS); uint256 mAA = 0; uint256 mBB = 0; uint256 mAB = 0; uint256 mBA = 0; if (deamortizedTokenABalance > 0) { mAA = (_min(deamortizedTokenABalance.mul(fImpOpening), totalTokenAWithPrecision)).div( deamortizedTokenABalance ); } if (deamortizedTokenBBalance > 0) { mBB = (_min(deamortizedTokenBBalance.mul(fImpOpening), totalTokenBWithPrecision)).div( deamortizedTokenBBalance ); } if (mAA > 0) { mAB = totalTokenBWithPrecision.sub(mBB.mul(deamortizedTokenBBalance)).div(deamortizedTokenABalance); } if (mBB > 0) { mBA = totalTokenAWithPrecision.sub(mAA.mul(deamortizedTokenABalance)).div(deamortizedTokenBBalance); } multipliers = Mult(mAA, mAB, mBA, mBB); } /** * @notice _getRemoveLiquidityAmounts internal function of getRemoveLiquidityAmounts * * @param percentA percent of exposition A to be removed * @param percentB percent of exposition B to be removed * @param user address of the account that will be removed * * @return withdrawAmountA amount of token A that will be rescued * @return withdrawAmountB amount of token B that will be rescued */ function _getRemoveLiquidityAmounts( uint256 percentA, uint256 percentB, address user ) internal view returns (uint256 withdrawAmountA, uint256 withdrawAmountB) { (uint256 totalTokenA, uint256 totalTokenB) = _getPoolBalances(); (uint256 originalBalanceTokenA, uint256 originalBalanceTokenB, uint256 fImpOriginal) = _getUserDepositSnapshot( user ); uint256 originalBalanceAToReduce = percentA.mul(originalBalanceTokenA).div(PERCENT_PRECISION); uint256 originalBalanceBToReduce = percentB.mul(originalBalanceTokenB).div(PERCENT_PRECISION); bool hasNoLiquidity = totalTokenA == 0 && totalTokenB == 0; if (hasNoLiquidity) { return (0, 0); } uint256 ABPrice = _getABPrice(); uint256 fImpOpening = _getFImpOpening( totalTokenA, totalTokenB, ABPrice, deamortizedTokenABalance, deamortizedTokenBBalance ); Mult memory multipliers = _getMultipliers(totalTokenA, totalTokenB, fImpOpening); (withdrawAmountA, withdrawAmountB) = _getWithdrawAmounts( originalBalanceAToReduce, originalBalanceBToReduce, fImpOriginal, multipliers ); } /** * @notice _getWithdrawAmounts internal function of getRemoveLiquidityAmounts * * @param _originalBalanceAToReduce amount of original deposit of the token A * @param _originalBalanceBToReduce amount of original deposit of the token B * @param _userFImp Opening Value Factor by the moment of the deposit * * @return withdrawAmountA amount of token A that will be rescued * @return withdrawAmountB amount of token B that will be rescued */ function _getWithdrawAmounts( uint256 _originalBalanceAToReduce, uint256 _originalBalanceBToReduce, uint256 _userFImp, Mult memory multipliers ) internal pure returns (uint256 withdrawAmountA, uint256 withdrawAmountB) { if (_userFImp > 0) { withdrawAmountA = _originalBalanceAToReduce .mul(multipliers.AA) .add(_originalBalanceBToReduce.mul(multipliers.BA)) .div(_userFImp); withdrawAmountB = _originalBalanceBToReduce .mul(multipliers.BB) .add(_originalBalanceAToReduce.mul(multipliers.AB)) .div(_userFImp); } return (withdrawAmountA, withdrawAmountB); } /** * @notice _getUserBalanceToStore internal auxiliary function to help calculation the * tokenA and tokenB value that should be stored in UserDepositSnapshot struct * * @param amountOfA current deposit of the token A * @param amountOfB current deposit of the token B * @param fImpOpening Opening Value Factor by the moment of the deposit * * @return userToStoreTokenA amount of token A that will be stored * @return userToStoreTokenB amount of token B that will be stored */ function _getUserBalanceToStore( uint256 amountOfA, uint256 amountOfB, uint256 fImpOpening, UserDepositSnapshot memory userDepositSnapshot ) internal pure returns (uint256 userToStoreTokenA, uint256 userToStoreTokenB) { userToStoreTokenA = amountOfA; userToStoreTokenB = amountOfB; //Re-add Liquidity case if (userDepositSnapshot.fImp != 0) { userToStoreTokenA = userDepositSnapshot.tokenABalance.mul(fImpOpening).div(userDepositSnapshot.fImp).add( amountOfA ); userToStoreTokenB = userDepositSnapshot.tokenBBalance.mul(fImpOpening).div(userDepositSnapshot.fImp).add( amountOfB ); } } /** * @dev Returns the smallest of two numbers. */ function _min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function _getABPrice() internal virtual view returns (uint256 ABPrice); function _getTradeDetailsExactAInput(uint256 amountAIn) internal virtual returns (TradeDetails memory); function _getTradeDetailsExactAOutput(uint256 amountAOut) internal virtual returns (TradeDetails memory); function _getTradeDetailsExactBInput(uint256 amountBIn) internal virtual returns (TradeDetails memory); function _getTradeDetailsExactBOutput(uint256 amountBOut) internal virtual returns (TradeDetails memory); function _onTrade(TradeDetails memory tradeDetails) internal virtual; function _onRemoveLiquidity( uint256 percentA, uint256 percentB, address owner ) internal virtual; function _onAddLiquidity(UserDepositSnapshot memory userDepositSnapshot, address owner) internal virtual; function _isValidAddress(address recipient) private pure { require(recipient != address(0), "AMM: transfer to zero address"); } function _isValidInput(uint256 input) private pure { require(input > 0, "AMM: input should be greater than zero"); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/IConfigurationManager.sol"; import "../interfaces/ICapProvider.sol"; /** * @title CappedPool * @author Pods Finance * * @notice Controls a maximum cap for a guarded release */ abstract contract CappedPool { using SafeMath for uint256; IConfigurationManager private immutable _configurationManager; constructor(IConfigurationManager configurationManager) public { _configurationManager = configurationManager; } /** * @dev Modifier to stop transactions that exceed the cap */ modifier capped(address token, uint256 amountOfLiquidity) { uint256 cap = capSize(); if (cap > 0) { uint256 poolBalance = IERC20(token).balanceOf(address(this)); require(poolBalance.add(amountOfLiquidity) <= cap, "CappedPool: amount exceed cap"); } _; } /** * @dev Get the cap size */ function capSize() public view returns (uint256) { ICapProvider capProvider = ICapProvider(_configurationManager.getCapProvider()); return capProvider.getCap(address(this)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; contract CombinedActionsGuard { mapping(address => uint256) sessions; /** * @dev Prevents an address from calling more than one function that contains this * function in the same block */ function _nonCombinedActions() internal { require(sessions[tx.origin] != block.number, "CombinedActionsGuard: reentrant call"); sessions[tx.origin] = block.number; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IPriceProvider { function setAssetFeeds(address[] memory _assets, address[] memory _feeds) external; function updateAssetFeeds(address[] memory _assets, address[] memory _feeds) external; function removeAssetFeeds(address[] memory _assets) external; function getAssetPrice(address _asset) external view returns (uint256); function getAssetDecimals(address _asset) external view returns (uint8); function latestRoundData(address _asset) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function getPriceFeed(address _asset) external view returns (address); function updateMinUpdateInterval() external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IIVProvider { struct IVData { uint256 roundId; uint256 updatedAt; uint256 answer; uint8 decimals; } event UpdatedIV(address indexed option, uint256 roundId, uint256 updatedAt, uint256 answer, uint8 decimals); event UpdaterSet(address indexed admin, address indexed updater); function getIV(address option) external view returns ( uint256 roundId, uint256 updatedAt, uint256 answer, uint8 decimals ); function updateIV( address option, uint256 answer, uint8 decimals ) external; function setUpdater(address updater) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity >=0.6.12; interface IBlackScholes { function getCallPrice( uint256 spotPrice, uint256 strikePrice, uint256 sigma, uint256 time, int256 riskFree ) external view returns (uint256); function getPutPrice( uint256 spotPrice, uint256 strikePrice, uint256 sigma, uint256 time, int256 riskFree ) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IIVGuesser { function blackScholes() external view returns (address); function getPutIV( uint256 _targetPrice, uint256 _initialIVGuess, uint256 _spotPrice, uint256 _strikePrice, uint256 _timeToMaturity, int256 _riskFree ) external view returns (uint256, uint256); function getCallIV( uint256 _targetPrice, uint256 _initialIVGuess, uint256 _spotPrice, uint256 _strikePrice, uint256 _timeToMaturity, int256 _riskFree ) external view returns (uint256, uint256); function updateAcceptableRange() external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IPodOption is IERC20 { /** Enums */ // @dev 0 for Put, 1 for Call enum OptionType { PUT, CALL } // @dev 0 for European, 1 for American enum ExerciseType { EUROPEAN, AMERICAN } /** Events */ event Mint(address indexed minter, uint256 amount); event Unmint(address indexed minter, uint256 optionAmount, uint256 strikeAmount, uint256 underlyingAmount); event Exercise(address indexed exerciser, uint256 amount); event Withdraw(address indexed minter, uint256 strikeAmount, uint256 underlyingAmount); /** Functions */ /** * @notice Locks collateral and write option tokens. * * @dev The issued amount ratio is 1:1, i.e., 1 option token for 1 underlying token. * * The collateral could be the strike or the underlying asset depending on the option type: Put or Call, * respectively * * It presumes the caller has already called IERC20.approve() on the * strike/underlying token contract to move caller funds. * * Options can only be minted while the series is NOT expired. * * It is also important to notice that options will be sent back * to `msg.sender` and not the `owner`. This behavior is designed to allow * proxy contracts to mint on others behalf. The `owner` will be able to remove * the deposited collateral after series expiration or by calling unmint(), even * if a third-party minted options on its behalf. * * @param amountOfOptions The amount option tokens to be issued * @param owner Which address will be the owner of the options */ function mint(uint256 amountOfOptions, address owner) external; /** * @notice Allow option token holders to use them to exercise the amount of units * of the locked tokens for the equivalent amount of the exercisable assets. * * @dev It presumes the caller has already called IERC20.approve() exercisable asset * to move caller funds. * * On American options, this function can only called anytime before expiration. * For European options, this function can only be called during the exerciseWindow. * Meaning, after expiration and before the end of exercise window. * * @param amountOfOptions The amount option tokens to be exercised */ function exercise(uint256 amountOfOptions) external; /** * @notice After series expiration in case of American or after exercise window for European, * allow minters who have locked their collateral to withdraw them proportionally * to their minted options. * * @dev If assets had been exercised during the option series the minter may withdraw * the exercised assets or a combination of exercised and collateral. */ function withdraw() external; /** * @notice Unlocks collateral by burning option tokens. * * Options can only be burned while the series is NOT expired. * * @param amountOfOptions The amount option tokens to be burned */ function unmint(uint256 amountOfOptions) external; function optionType() external view returns (OptionType); function exerciseType() external view returns (ExerciseType); function underlyingAsset() external view returns (address); function underlyingAssetDecimals() external view returns (uint8); function strikeAsset() external view returns (address); function strikeAssetDecimals() external view returns (uint8); function strikePrice() external view returns (uint256); function strikePriceDecimals() external view returns (uint8); function expiration() external view returns (uint256); function startOfExerciseWindow() external view returns (uint256); function hasExpired() external view returns (bool); function isTradeWindow() external view returns (bool); function isExerciseWindow() external view returns (bool); function isWithdrawWindow() external view returns (bool); function strikeToTransfer(uint256 amountOfOptions) external view returns (uint256); function getSellerWithdrawAmounts(address owner) external view returns (uint256 strikeAmount, uint256 underlyingAmount); function underlyingReserves() external view returns (uint256); function strikeReserves() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "./IAMM.sol"; interface IOptionAMMPool is IAMM { // @dev 0 for when tokenA enter the pool and B leaving (A -> B) // and 1 for the opposite direction enum TradeDirection { AB, BA } function tradeExactAInput( uint256 exactAmountAIn, uint256 minAmountBOut, address owner, uint256 sigmaInitialGuess ) external returns (uint256); function tradeExactAOutput( uint256 exactAmountAOut, uint256 maxAmountBIn, address owner, uint256 sigmaInitialGuess ) external returns (uint256); function tradeExactBInput( uint256 exactAmountBIn, uint256 minAmountAOut, address owner, uint256 sigmaInitialGuess ) external returns (uint256); function tradeExactBOutput( uint256 exactAmountBOut, uint256 maxAmountAIn, address owner, uint256 sigmaInitialGuess ) external returns (uint256); function getOptionTradeDetailsExactAInput(uint256 exactAmountAIn) external view returns ( uint256 amountBOutput, uint256 newSigma, uint256 feesTokenA, uint256 feesTokenB ); function getOptionTradeDetailsExactAOutput(uint256 exactAmountAOut) external view returns ( uint256 amountBInput, uint256 newSigma, uint256 feesTokenA, uint256 feesTokenB ); function getOptionTradeDetailsExactBInput(uint256 exactAmountBIn) external view returns ( uint256 amountAOutput, uint256 newSigma, uint256 feesTokenA, uint256 feesTokenB ); function getOptionTradeDetailsExactBOutput(uint256 exactAmountBOut) external view returns ( uint256 amountAInput, uint256 newSigma, uint256 feesTokenA, uint256 feesTokenB ); function getRemoveLiquidityAmounts( uint256 percentA, uint256 percentB, address user ) external view returns (uint256 withdrawAmountA, uint256 withdrawAmountB); function getABPrice() external view returns (uint256); function getAdjustedIV() external view returns (uint256); function withdrawRewards() external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IFeePool { struct Balance { uint256 shares; uint256 liability; } function setFee(uint256 feeBaseValue, uint8 decimals) external; function withdraw(address to, uint256 amount) external; function mint(address to, uint256 amount) external; function feeToken() external view returns (address); function feeValue() external view returns (uint256); function feeDecimals() external view returns (uint8); function getCollectable(uint256 amount, uint256 poolAmount) external view returns (uint256); function sharesOf(address owner) external view returns (uint256); function getWithdrawAmount(address owner, uint256 amountOfShares) external view returns (uint256, uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity >=0.6.12; interface IConfigurationManager { function setParameter(bytes32 name, uint256 value) external; function setEmergencyStop(address emergencyStop) external; function setPricingMethod(address pricingMethod) external; function setIVGuesser(address ivGuesser) external; function setIVProvider(address ivProvider) external; function setPriceProvider(address priceProvider) external; function setCapProvider(address capProvider) external; function setAMMFactory(address ammFactory) external; function setOptionFactory(address optionFactory) external; function setOptionHelper(address optionHelper) external; function setOptionPoolRegistry(address optionPoolRegistry) external; function getParameter(bytes32 name) external view returns (uint256); function owner() external view returns (address); function getEmergencyStop() external view returns (address); function getPricingMethod() external view returns (address); function getIVGuesser() external view returns (address); function getIVProvider() external view returns (address); function getPriceProvider() external view returns (address); function getCapProvider() external view returns (address); function getAMMFactory() external view returns (address); function getOptionFactory() external view returns (address); function getOptionHelper() external view returns (address); function getOptionPoolRegistry() external view returns (address); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IEmergencyStop { function stop(address target) external; function resume(address target) external; function isStopped(address target) external view returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "./IFeePool.sol"; interface IFeePoolBuilder { function buildFeePool( address asset, uint256 feeBaseValue, uint8 feeDecimals, address owner ) external returns (IFeePool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../interfaces/IAaveIncentivesController.sol"; import "../../interfaces/IConfigurationManager.sol"; import "../../lib/Conversion.sol"; abstract contract AaveIncentives is Conversion { address public immutable rewardAsset; address public immutable rewardContract; event RewardsClaimed(address indexed claimer, uint256 rewardAmount); constructor(IConfigurationManager configurationManager) public { rewardAsset = _parseAddressFromUint(configurationManager.getParameter("REWARD_ASSET")); rewardContract = _parseAddressFromUint(configurationManager.getParameter("REWARD_CONTRACT")); } /** * @notice Gets the current reward claimed */ function _rewardBalance() internal view returns (uint256) { return IERC20(rewardAsset).balanceOf(address(this)); } /** * @notice Claim pending rewards */ function _claimRewards(address[] memory assets) internal { IAaveIncentivesController distributor = IAaveIncentivesController(rewardContract); uint256 amountToClaim = distributor.getRewardsBalance(assets, address(this)); distributor.claimRewards(assets, amountToClaim, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract RequiredDecimals { uint256 private constant _MAX_TOKEN_DECIMALS = 38; /** * Tries to fetch the decimals of a token, if not existent, fails with a require statement * * @param token An instance of IERC20 * @return The decimals of a token */ function tryDecimals(IERC20 token) internal view returns (uint8) { // solhint-disable-line private-vars-leading-underscore bytes memory payload = abi.encodeWithSignature("decimals()"); // solhint-disable avoid-low-level-calls (bool success, bytes memory returnData) = address(token).staticcall(payload); require(success, "RequiredDecimals: required decimals"); uint8 decimals = abi.decode(returnData, (uint8)); require(decimals < _MAX_TOKEN_DECIMALS, "RequiredDecimals: token decimals should be lower than 38"); return decimals; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IAMM { function addLiquidity( uint256 amountOfA, uint256 amountOfB, address owner ) external; function removeLiquidity(uint256 amountOfA, uint256 amountOfB) external; function tokenA() external view returns (address); function tokenB() external view returns (address); function tokenADecimals() external view returns (uint8); function tokenBDecimals() external view returns (uint8); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface ICapProvider { function setCap(address target, uint256 value) external; function getCap(address target) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IAaveIncentivesController { function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; contract Conversion { /** * @notice Parses the address represented by an uint */ function _parseAddressFromUint(uint256 x) internal pure returns (address) { bytes memory data = new bytes(32); assembly { mstore(add(data, 32), x) } return abi.decode(data, (address)); } }
If a option is ITM, either PUTs or CALLs, the minimum price that it would cost is the difference between the spot price and strike price. If the target price after applying slippage is above this minimum, the function returns true. newTargetPrice the new ABPrice after slippage (how many units of tokenB, to buy 1 option) spotPrice current underlying asset spot price during this transaction return true if is a valid target price (above the minimum)/
function _isValidTargetPrice(uint256 newTargetPrice, uint256 spotPrice) internal view returns (bool) { if (priceProperties.optionType == IPodOption.OptionType.PUT) { if (spotPrice < priceProperties.strikePrice) { return newTargetPrice > priceProperties.strikePrice.sub(spotPrice).div(10**PRICING_DECIMALS.sub(tokenBDecimals())); } if (spotPrice > priceProperties.strikePrice) { return newTargetPrice > spotPrice.sub(priceProperties.strikePrice).div(10**PRICING_DECIMALS.sub(tokenBDecimals())); } } return true; }
88,937
./full_match/4/0x7D50dF98B38765Da17b812fE879A4b4b23081d46/sources/browser/Untitled.sol
this saves gas while using this multiple timeschecking all conditionstransferring PAX tokens from smart user to smart contract for level 1update variables
function regUser(uint _referrerID, uint cid) public returns(bool) { address msgSender = msg.sender; require(!userInfos[msgSender].joined, 'User exist'); if(!(_referrerID > 0 && _referrerID <= lastIDCount)) _referrerID = defaultRefID; if(userInfos[userAddressByID[_referrerID]].referral.length >= maxDownLimit) _referrerID = userInfos[findFreeReferrer(userAddressByID[_referrerID])].id; require( paxInterface(paxTokenAddress).transferFrom(msgSender, address(this), priceOfLevel[1]),"token transfer failed"); userInfo memory UserInfo; lastIDCount++; UserInfo = userInfo({ joined: true, id: lastIDCount, referrerID: _referrerID, referral: new address[](0) }); userInfos[msgSender] = UserInfo; userAddressByID[lastIDCount] = msg.sender; userInfos[msgSender].levelExpired[1] = now + levelLifeTime; userInfos[userAddressByID[_referrerID]].referral.push(msgSender); payForUniLevel(_referrerID); paxInterface(paxTokenAddress).transfer(owner, systemDistPart); if(thisMonthEnd < now) startNextMonth(); uint lastDivPoolIndex = divPoolRecords.length -1; divPoolRecords[lastDivPoolIndex].totalDividendCollection += globalDivDistPart; autoPoolBuffer[0] += autoPoolDist[1]; payForLevel(1, msgSender,cid); emit regLevelEv(msgSender, lastIDCount, _referrerID, now); return true; }
800,490
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "./node_modules/@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./node_modules/@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; import "./node_modules/@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol"; import "./node_modules/@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; contract MyERC721Token is ERC721, ERC721Burnable, ERC721Pausable, ERC721Holder{ constructor()ERC721("MYERC721TOKEN", "MY721"){} // override burn function from ERC721Burnable function burn(uint256 amount) public override{ burn(amount); } // _beforeTokenTransfer should be overriden from ERC721Pausable function _beforeTokenTransfer(address from, address to, uint256 tokenId)internal virtual override(ERC721, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } // now this contract can receive ERC721 token(ERC721 compatible) function onERC721Received( address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } }
_beforeTokenTransfer should be overriden from ERC721Pausable
function _beforeTokenTransfer(address from, address to, uint256 tokenId)internal virtual override(ERC721, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); }
15,864,675
pragma solidity ^0.5.10; import "tabookey-gasless/contracts/GsnUtils.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/cryptography/ECDSA.sol"; import "./ProxyFactory.sol"; import "gsn-sponsor/contracts/GsnRecipient.sol"; import "./SmartAccount.sol"; contract SmartAccountFactory is GsnRecipient, Ownable, ProxyFactory { using GsnUtils for bytes; using ECDSA for bytes32; SmartAccount template; address bypassLibTemplate; uint256 constant APPROVAL_VALIDITY = 1 days; event SmartAccountCreated(address sender, SmartAccount smartAccount, bytes32 smartAccountId); mapping(address => bool) public trustedSigners; mapping(bytes32 => address) public knownSmartAccounts; constructor(address _forwarder, address payable _template, address _bypassLibTemplate) public { setGsnForwarder(_forwarder); template = SmartAccount(_template); bypassLibTemplate = _bypassLibTemplate; } function addTrustedSigners(address[] memory signers) public onlyOwner { for (uint256 i = 0; i < signers.length; i++) { trustedSigners[signers[i]] = true; } } function isApprovedSigner(bytes32 hash, bytes memory sig) public view returns (bool) { return trustedSigners[hash.recover(sig)]; } function acceptRelayedCall( address relay, address from, bytes calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes calldata approvalData, uint256 maxPossibleCharge ) external view returns (uint256 res, bytes memory data) { (relay, from, encodedFunction, transactionFee, gasPrice,gasLimit, nonce, approvalData, maxPossibleCharge); bytes4 methodSig = encodedFunction.getMethodSig(); require(methodSig == this.newSmartAccount.selector, "Call must be only newSmartAccount()"); bytes32 smartAccountId = bytes32(encodedFunction.getParam(0)); // require(knownSmartAccounts[smartAccountId] == address(0), "SmartAccount already created for this id"); // (bytes4 timestamp, bytes memory sig) = abi.decode(approvalData,(bytes4, bytes)); // require(uint32(timestamp) + APPROVAL_VALIDITY > now, "Outdated request"); // bytes32 hash = keccak256(abi.encodePacked(smartAccountId, timestamp)).toEthSignedMessageHash(); // require(isApprovedSigner(hash, sig), "Not signed by approved signer"); validateNewSmartAccountRequest(smartAccountId, approvalData); return (0, ""); } function _acceptCall(address from, bytes memory encodedFunction) view internal returns (uint256 res, bytes memory data){} function validateNewSmartAccountRequest(bytes32 smartAccountId, bytes memory approvalData) private view returns (bool) { require(knownSmartAccounts[smartAccountId] == address(0), "SmartAccount already created for this id"); (bytes4 timestamp, bytes memory sig) = abi.decode(approvalData, (bytes4, bytes)); require(uint32(timestamp) + APPROVAL_VALIDITY > now, "Outdated request"); bytes32 hash = keccak256(abi.encodePacked(smartAccountId, timestamp)).toEthSignedMessageHash(); require(isApprovedSigner(hash, sig), "Not signed by approved signer"); return true; } /** * @param smartAccountId - generated through keccak256(<userEmail>) by backend service */ function newSmartAccount(bytes32 smartAccountId, bytes memory approvalData) public { require(address(template) != address(0), "newSmartAccount: createAccountTemplate not called"); require(validateNewSmartAccountRequest(smartAccountId, approvalData), "Must have a valid approvalData"); require(knownSmartAccounts[smartAccountId] == address(0), "SmartAccount already created for this id"); address payable proxy = address(uint160(createProxyImpl(address(template), ""))); SmartAccount smartAccount = SmartAccount(proxy); smartAccount.ctr2(getGsnForwarder(), getSender(), bypassLibTemplate); knownSmartAccounts[smartAccountId] = address(smartAccount); emit SmartAccountCreated(getSender(), smartAccount, smartAccountId); } }
require(knownSmartAccounts[smartAccountId] == address(0), "SmartAccount already created for this id"); (bytes4 timestamp, bytes memory sig) = abi.decode(approvalData,(bytes4, bytes)); require(uint32(timestamp) + APPROVAL_VALIDITY > now, "Outdated request"); bytes32 hash = keccak256(abi.encodePacked(smartAccountId, timestamp)).toEthSignedMessageHash(); require(isApprovedSigner(hash, sig), "Not signed by approved signer");
function acceptRelayedCall( address relay, address from, bytes calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes calldata approvalData, uint256 maxPossibleCharge ) external view returns (uint256 res, bytes memory data) { (relay, from, encodedFunction, transactionFee, gasPrice,gasLimit, nonce, approvalData, maxPossibleCharge); bytes4 methodSig = encodedFunction.getMethodSig(); require(methodSig == this.newSmartAccount.selector, "Call must be only newSmartAccount()"); bytes32 smartAccountId = bytes32(encodedFunction.getParam(0)); validateNewSmartAccountRequest(smartAccountId, approvalData); return (0, ""); }
12,873,979
pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./utils/ReentrancyGuard.sol"; import "./libs/LibUnitConverter.sol"; import "./libs/LibValidator.sol"; import "./libs/MarginalFunctionality.sol"; import "./OrionVault.sol"; /** * @title Exchange * @dev Exchange contract for the Orion Protocol * @author @wafflemakr */ /* Overflow safety: We do not use SafeMath and control overflows by not accepting large ints on input. Balances inside contract are stored as int192. Allowed input amounts are int112 or uint112: it is enough for all practically used tokens: for instance if decimal unit is 1e18, int112 allow to encode up to 2.5e15 decimal units. That way adding/subtracting any amount from balances won't overflow, since minimum number of operations to reach max int is practically infinite: ~1e24. Allowed prices are uint64. Note, that price is represented as price per 1e8 tokens. That means that amount*price always fit uint256, while amount*price/1e8 not only fit int192, but also can be added, subtracted without overflow checks: number of malicion operations to overflow ~1e13. */ contract Exchange is OrionVault, ReentrancyGuard { using LibValidator for LibValidator.Order; using SafeERC20 for IERC20; // Flags for updateOrders // All flags are explicit uint8 constant kSell = 0; uint8 constant kBuy = 1; // if 0 - then sell uint8 constant kCorrectMatcherFeeByOrderAmount = 2; // EVENTS event NewAssetTransaction( address indexed user, address indexed assetAddress, bool isDeposit, uint112 amount, uint64 timestamp ); event NewTrade( address indexed buyer, address indexed seller, address baseAsset, address quoteAsset, uint64 filledPrice, uint192 filledAmount, uint192 amountQuote ); // MAIN FUNCTIONS /** * @dev Since Exchange will work behind the Proxy contract it can not have constructor */ function initialize() public payable initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * @dev set basic Exchange params * @param orionToken - base token address * @param priceOracleAddress - adress of PriceOracle contract * @param allowedMatcher - address which has authorization to match orders */ function setBasicParams(address orionToken, address priceOracleAddress, address allowedMatcher) public onlyOwner { require((orionToken != address(0)) && (priceOracleAddress != address(0)), "E15"); _orionToken = IERC20(orionToken); _oracleAddress = priceOracleAddress; _allowedMatcher = allowedMatcher; } /** * @dev set marginal settings * @param _collateralAssets - list of addresses of assets which may be used as collateral * @param _stakeRisk - risk coefficient for staken orion as uint8 (0=0, 255=1) * @param _liquidationPremium - premium for liquidator as uint8 (0=0, 255=1) * @param _priceOverdue - time after that price became outdated * @param _positionOverdue - time after that liabilities became overdue and may be liquidated */ function updateMarginalSettings(address[] calldata _collateralAssets, uint8 _stakeRisk, uint8 _liquidationPremium, uint64 _priceOverdue, uint64 _positionOverdue) public onlyOwner { collateralAssets = _collateralAssets; stakeRisk = _stakeRisk; liquidationPremium = _liquidationPremium; priceOverdue = _priceOverdue; positionOverdue = _positionOverdue; } /** * @dev set risk coefficients for collateral assets * @param assets - list of assets * @param risks - list of risks as uint8 (0=0, 255=1) */ function updateAssetRisks(address[] calldata assets, uint8[] calldata risks) public onlyOwner { for(uint256 i; i< assets.length; i++) assetRisks[assets[i]] = risks[i]; } /** * @dev Deposit ERC20 tokens to the exchange contract * @dev User needs to approve token contract first * @param amount asset amount to deposit in its base unit */ function depositAsset(address assetAddress, uint112 amount) external { //require(asset.transferFrom(msg.sender, address(this), uint256(amount)), "E6"); IERC20(assetAddress).safeTransferFrom(msg.sender, address(this), uint256(amount)); generalDeposit(assetAddress,amount); } /** * @notice Deposit ETH to the exchange contract * @dev deposit event will be emitted with the amount in decimal format (10^8) * @dev balance will be stored in decimal format too */ function deposit() external payable { generalDeposit(address(0), uint112(msg.value)); } /** * @dev internal implementation of deposits */ function generalDeposit(address assetAddress, uint112 amount) internal { address user = msg.sender; bool wasLiability = assetBalances[user][assetAddress]<0; int112 safeAmountDecimal = LibUnitConverter.baseUnitToDecimal( assetAddress, amount ); assetBalances[user][assetAddress] += safeAmountDecimal; if(amount>0) emit NewAssetTransaction(user, assetAddress, true, uint112(safeAmountDecimal), uint64(block.timestamp)); if(wasLiability) MarginalFunctionality.updateLiability(user, assetAddress, liabilities, uint112(safeAmountDecimal), assetBalances[user][assetAddress]); } /** * @dev Withdrawal of remaining funds from the contract back to the address * @param assetAddress address of the asset to withdraw * @param amount asset amount to withdraw in its base unit */ function withdraw(address assetAddress, uint112 amount) external nonReentrant { int112 safeAmountDecimal = LibUnitConverter.baseUnitToDecimal( assetAddress, amount ); address user = msg.sender; assetBalances[user][assetAddress] -= safeAmountDecimal; require(assetBalances[user][assetAddress]>=0, "E1w1"); //TODO require(checkPosition(user), "E1w2"); //TODO uint256 _amount = uint256(amount); if(assetAddress == address(0)) { (bool success, ) = user.call{value:_amount}(""); require(success, "E6w"); } else { IERC20(assetAddress).safeTransfer(user, _amount); } emit NewAssetTransaction(user, assetAddress, false, uint112(safeAmountDecimal), uint64(block.timestamp)); } /** * @dev Get asset balance for a specific address * @param assetAddress address of the asset to query * @param user user address to query */ function getBalance(address assetAddress, address user) public view returns (int192) { return assetBalances[user][assetAddress]; } /** * @dev Batch query of asset balances for a user * @param assetsAddresses array of addresses of the assets to query * @param user user address to query */ function getBalances(address[] memory assetsAddresses, address user) public view returns (int192[] memory balances) { balances = new int192[](assetsAddresses.length); for (uint256 i; i < assetsAddresses.length; i++) { balances[i] = assetBalances[user][assetsAddresses[i]]; } } /** * @dev Batch query of asset liabilities for a user * @param user user address to query */ function getLiabilities(address user) public view returns (MarginalFunctionality.Liability[] memory liabilitiesArray) { return liabilities[user]; } /** * @dev Return list of assets which can be used for collateral */ function getCollateralAssets() public view returns (address[] memory) { return collateralAssets; } /** * @dev get hash for an order * @dev we use order hash as order id to prevent double matching of the same order */ function getOrderHash(LibValidator.Order memory order) public pure returns (bytes32){ return order.getTypeValueHash(); } /** * @dev get filled amounts for a specific order */ function getFilledAmounts(bytes32 orderHash, LibValidator.Order memory order) public view returns (int192 totalFilled, int192 totalFeesPaid) { totalFilled = int192(filledAmounts[orderHash]); //It is safe to convert here: filledAmounts is result of ui112 additions totalFeesPaid = int192(uint256(order.matcherFee)*uint112(totalFilled)/order.amount); //matcherFee is u64; safe multiplication here } /** * @notice Settle a trade with two orders, filled price and amount * @dev 2 orders are submitted, it is necessary to match them: check conditions in orders for compliance filledPrice, filledAmountbuyOrderHash change balances on the contract respectively with buyer, seller, matcbuyOrderHashher * @param buyOrder structure of buy side orderbuyOrderHash * @param sellOrder structure of sell side order * @param filledPrice price at which the order was settled * @param filledAmount amount settled between orders */ function fillOrders( LibValidator.Order memory buyOrder, LibValidator.Order memory sellOrder, uint64 filledPrice, uint112 filledAmount ) public nonReentrant { // --- VARIABLES --- // // Amount of quote asset uint256 _amountQuote = uint256(filledAmount)*filledPrice/(10**8); require(_amountQuote<2**112-1, "E12G"); uint112 amountQuote = uint112(_amountQuote); // Order Hashes bytes32 buyOrderHash = buyOrder.getTypeValueHash(); bytes32 sellOrderHash = sellOrder.getTypeValueHash(); // --- VALIDATIONS --- // // Validate signatures using eth typed sign V1 require( LibValidator.checkOrdersInfo( buyOrder, sellOrder, msg.sender, filledAmount, filledPrice, block.timestamp, _allowedMatcher ), "E3G" ); // --- UPDATES --- // //updateFilledAmount filledAmounts[buyOrderHash] += filledAmount; //it is safe to add ui112 to each other to get i192 filledAmounts[sellOrderHash] += filledAmount; require(filledAmounts[buyOrderHash] <= buyOrder.amount, "E12B"); require(filledAmounts[sellOrderHash] <= sellOrder.amount, "E12S"); // Update User's balances updateOrderBalance(buyOrder, filledAmount, amountQuote, kBuy | kCorrectMatcherFeeByOrderAmount); updateOrderBalance(sellOrder, filledAmount, amountQuote, kSell | kCorrectMatcherFeeByOrderAmount); require(checkPosition(buyOrder.senderAddress), "Incorrect margin position for buyer"); require(checkPosition(sellOrder.senderAddress), "Incorrect margin position for seller"); emit NewTrade( buyOrder.senderAddress, sellOrder.senderAddress, buyOrder.baseAsset, buyOrder.quoteAsset, filledPrice, filledAmount, amountQuote ); } /** * @dev wrapper for LibValidator methods, may be deleted. */ function validateOrder(LibValidator.Order memory order) public pure returns (bool isValid) { isValid = order.isPersonalSign ? LibValidator.validatePersonal(order) : LibValidator.validateV3(order); } /** * @notice update user balances and send matcher fee * @param flags uint8, see constants for possible flags of order */ function updateOrderBalance( LibValidator.Order memory order, uint112 filledAmount, uint112 amountQuote, uint8 flags ) internal { address user = order.senderAddress; bool isBuyer = ((flags & kBuy) != 0); int192 temp; // this variable will be used for temporary variable storage (optimization purpose) { // Stack too deep bool isCorrectFee = ((flags & kCorrectMatcherFeeByOrderAmount) != 0); if(isCorrectFee) { // matcherFee: u64, filledAmount u128 => matcherFee*filledAmount fit u256 // result matcherFee fit u64 order.matcherFee = uint64(uint256(order.matcherFee)*filledAmount/order.amount); //rewrite in memory only } } if(filledAmount > 0) { if(!isBuyer) (filledAmount, amountQuote) = (amountQuote, filledAmount); (address firstAsset, address secondAsset) = isBuyer? (order.quoteAsset, order.baseAsset): (order.baseAsset, order.quoteAsset); int192 firstBalance = assetBalances[user][firstAsset]; int192 secondBalance = assetBalances[user][secondAsset]; // 'Stack too deep' correction // WAS: // bool firstInLiabilities = firstBalance<0; // bool secondInLiabilities = secondBalance<0; // NOW: // ENDFIX temp = assetBalances[user][firstAsset] - amountQuote; assetBalances[user][firstAsset] = temp; assetBalances[user][secondAsset] += filledAmount; // 'Stack too deep' correction // WAS: // if(!firstInLiabilities && (temp<0)){ // NOW: if(!(firstBalance<0) && (temp<0)){ // ENDFIX setLiability(user, firstAsset, temp); } // 'Stack too deep' correction // WAS: // if(secondInLiabilities) { // NOW: if(secondBalance<0) { // ENDFIX MarginalFunctionality.updateLiability(user, secondAsset, liabilities, filledAmount, assetBalances[user][secondAsset]); } } // User pay for fees bool feeAssetInLiabilities = assetBalances[user][order.matcherFeeAsset]<0; temp = assetBalances[user][order.matcherFeeAsset] - order.matcherFee; assetBalances[user][order.matcherFeeAsset] = temp; if(!feeAssetInLiabilities && (temp<0)) { setLiability(user, order.matcherFeeAsset, temp); } assetBalances[order.matcherAddress][order.matcherFeeAsset] += order.matcherFee; } /** * @notice users can cancel an order * @dev write an orderHash in the contract so that such an order cannot be filled (executed) */ /* Unused for now function cancelOrder(LibValidator.Order memory order) public { require(order.validateV3(), "E2"); require(msg.sender == order.senderAddress, "Not owner"); bytes32 orderHash = order.getTypeValueHash(); require(!isOrderCancelled(orderHash), "E4"); ( int192 totalFilled, //uint totalFeesPaid ) = getFilledAmounts(orderHash); if (totalFilled > 0) orderStatus[orderHash] = Status.PARTIALLY_CANCELLED; else orderStatus[orderHash] = Status.CANCELLED; emit OrderUpdate(orderHash, msg.sender, orderStatus[orderHash]); assert( orderStatus[orderHash] == Status.PARTIALLY_CANCELLED || orderStatus[orderHash] == Status.CANCELLED ); } */ /** * @dev check user marginal position (compare assets and liabilities) * @return isPositive - boolean whether liabilities are covered by collateral or not */ function checkPosition(address user) public view returns (bool) { if(liabilities[user].length == 0) return true; return calcPosition(user).state == MarginalFunctionality.PositionState.POSITIVE; } /** * @dev internal methods which collect all variables used my MarginalFunctionality to one structure * @param user user address to query * @return UsedConstants - MarginalFunctionality.UsedConstants structure */ function getConstants(address user) internal view returns (MarginalFunctionality.UsedConstants memory) { return MarginalFunctionality.UsedConstants(user, _oracleAddress, address(this), address(_orionToken), positionOverdue, priceOverdue, stakeRisk, liquidationPremium); } /** * @dev calc user marginal position (compare assets and liabilities) * @param user user address to query * @return position - MarginalFunctionality.Position structure */ function calcPosition(address user) public view returns (MarginalFunctionality.Position memory) { MarginalFunctionality.UsedConstants memory constants = getConstants(user); return MarginalFunctionality.calcPosition(collateralAssets, liabilities, assetBalances, assetRisks, constants); } /** * @dev method to cover some of overdue broker liabilities and get ORN in exchange same as liquidation or margin call * @param broker - broker which will be liquidated * @param redeemedAsset - asset, liability of which will be covered * @param amount - amount of covered asset */ function partiallyLiquidate(address broker, address redeemedAsset, uint112 amount) public { MarginalFunctionality.UsedConstants memory constants = getConstants(broker); MarginalFunctionality.partiallyLiquidate(collateralAssets, liabilities, assetBalances, assetRisks, constants, redeemedAsset, amount); } /** * @dev method to add liability * @param user - user which created liability * @param asset - liability asset * @param balance - current negative balance */ function setLiability(address user, address asset, int192 balance) internal { liabilities[user].push( MarginalFunctionality.Liability({ asset: asset, timestamp: uint64(block.timestamp), outstandingAmount: uint192(-balance)}) ); } /** * @dev method to update liability forcing removing any liabilities if balance > 0 * @param assetAddress - liability asset */ function forceUpdateLiability(address assetAddress) public { address user = msg.sender; MarginalFunctionality.updateLiability(user, assetAddress, liabilities, 0, assetBalances[user][assetAddress]); } /** * @dev revert on fallback function */ fallback() external { revert("E6"); } /* Error Codes E1: Insufficient Balance, flavor S - stake E2: Invalid Signature, flavor B,S - buyer, seller E3: Invalid Order Info, flavor G - general, M - wrong matcher, M2 unauthorized matcher, As - asset mismatch, AmB/AmS - amount mismatch (buyer,seller), PrB/PrS - price mismatch(buyer,seller), D - direction mismatch, E4: Order expired, flavor B,S - buyer,seller E5: Contract not active, E6: Transfer error E7: Incorrect state prior to liquidation E8: Liquidator doesn't satisfy requirements E9: Data for liquidation handling is outdated E10: Incorrect state after liquidation E11: Amount overflow E12: Incorrect filled amount, flavor G,B,S: general(overflow), buyer order overflow, seller order overflow E14: Authorization error, sfs - seizeFromStake E15: Wrong passed params */ } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./libs/MarginalFunctionality.sol"; // Base contract which contain state variable of the first version of Exchange // deployed on mainnet. Changes of the state variables should be introduced // not in that contract but down the inheritance chain, to allow safe upgrades // More info about safe upgrades here: // https://blog.openzeppelin.com/the-state-of-smart-contract-upgrades/#upgrade-patterns contract ExchangeStorage { //order -> filledAmount mapping(bytes32 => uint192) public filledAmounts; // Get user balance by address and asset address mapping(address => mapping(address => int192)) internal assetBalances; // List of assets with negative balance for each user mapping(address => MarginalFunctionality.Liability[]) public liabilities; // List of assets which can be used as collateral and risk coefficients for them address[] internal collateralAssets; mapping(address => uint8) public assetRisks; // Risk coefficient for locked ORN uint8 public stakeRisk; // Liquidation premium uint8 public liquidationPremium; // Delays after which price and position become outdated uint64 public priceOverdue; uint64 public positionOverdue; // Base orion tokens (can be locked on stake) IERC20 _orionToken; // Address of price oracle contract address _oracleAddress; // Address from which matching of orders is allowed address _allowedMatcher; } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "./Exchange.sol"; import "./utils/orionpool/periphery/interfaces/IOrionPoolV2Router02Ext.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract ExchangeWithOrionPool is Exchange { using SafeERC20 for IERC20; address public _orionpoolRouter; mapping (address => bool) orionpoolAllowances; modifier initialized { require(_orionpoolRouter!=address(0), "_orionpoolRouter is not set"); require(address(_orionToken)!=address(0), "_orionToken is not set"); require(_oracleAddress!=address(0), "_oracleAddress is not set"); require(_allowedMatcher!=address(0), "_allowedMatcher is not set"); _; } function _safeIncreaseAllowance(address token) internal { if(token != address(0) && !orionpoolAllowances[token]) { IERC20(token).safeIncreaseAllowance(_orionpoolRouter, 2**256-1); orionpoolAllowances[token] = true; } } /** * @dev set basic Exchange params * @param orionToken - base token address * @param priceOracleAddress - adress of PriceOracle contract * @param allowedMatcher - address which has authorization to match orders * @param orionpoolRouter - OrionPool Router address for changes through orionpool */ function setBasicParams(address orionToken, address priceOracleAddress, address allowedMatcher, address orionpoolRouter) public onlyOwner { _orionToken = IERC20(orionToken); _oracleAddress = priceOracleAddress; _allowedMatcher = allowedMatcher; _orionpoolRouter = orionpoolRouter; } // Important catch-all afunction that should only accept ethereum and don't allow do something with it // We accept ETH there only from out router. // If router sends some ETH to us - it's just swap completed, and we don't need to do smth // with ETH received - amount of ETH will be handled by ........... blah blah receive() external payable { require(msg.sender == _orionpoolRouter, "NPF"); } /** * @notice (partially) settle buy order with OrionPool as counterparty * @dev order and orionpool path are submitted, it is necessary to match them: check conditions in order for compliance filledPrice and filledAmount change tokens via OrionPool check that final price after exchange not worse than specified in order change balances on the contract respectively * @param order structure of buy side orderbuyOrderHash * @param filledAmount amount of purchaseable token * @param path array of assets addresses (each consequent asset pair is change pair) */ // Just to avoid stack too deep error; struct OrderExecutionData { uint64 filledPrice; uint112 amountQuote; uint tx_value; } function fillThroughOrionPool( LibValidator.Order memory order, uint112 filledAmount, uint64 blockchainFee, address[] calldata path ) public nonReentrant initialized { // Amount of quote asset uint256 _amountQuote = uint256(filledAmount)* order.price/(10**8); OrderExecutionData memory exec_data; if(order.buySide==1){ /* NOTE BUY ORDER ************************************************************/ (int112 amountQuoteBaseUnits, int112 filledAmountBaseUnits) = ( LibUnitConverter.decimalToBaseUnit(path[0], _amountQuote), LibUnitConverter.decimalToBaseUnit(path[path.length-1], filledAmount) ); // TODO: check // require(IERC20(order.quoteAsset).balanceOf(address(this)) >= uint(amountQuoteBaseUnits), "NEGT"); LibValidator.checkOrderSingleMatch(order, msg.sender, _allowedMatcher, filledAmount, block.timestamp, path, 1); // Change fee only after order validation if(blockchainFee < order.matcherFee) order.matcherFee = blockchainFee; _safeIncreaseAllowance(order.quoteAsset); if(order.quoteAsset == address(0)) exec_data.tx_value = uint(amountQuoteBaseUnits); try IOrionPoolV2Router02Ext(_orionpoolRouter).swapTokensForExactTokensAutoRoute{value: exec_data.tx_value}( uint(filledAmountBaseUnits), uint(amountQuoteBaseUnits), path, address(this)) // order.expiration/1000 returns(uint[] memory amounts) { exec_data.amountQuote = uint112(LibUnitConverter.baseUnitToDecimal( path[0], amounts[0] )); //require(_amountQuote<2**112-1, "E12G"); //TODO uint256 _filledPrice = exec_data.amountQuote*(10**8)/filledAmount; require(_filledPrice<= order.price, "EX"); //TODO exec_data.filledPrice = uint64(_filledPrice); // since _filledPrice<buyOrder.price it fits uint64 //uint112 amountQuote = uint112(_amountQuote); } catch(bytes memory) { filledAmount = 0; exec_data.filledPrice = order.price; } // Update User's balances updateOrderBalance(order, filledAmount, exec_data.amountQuote, kBuy); require(checkPosition(order.senderAddress), "Incorrect margin position for buyer"); }else{ /* NOTE: SELL ORDER **************************************************************************/ LibValidator.checkOrderSingleMatch(order, msg.sender, _allowedMatcher, filledAmount, block.timestamp, path, 0); // Change fee only after order validation if(blockchainFee < order.matcherFee) order.matcherFee = blockchainFee; (int112 amountQuoteBaseUnits, int112 filledAmountBaseUnits) = ( LibUnitConverter.decimalToBaseUnit(path[0], filledAmount), LibUnitConverter.decimalToBaseUnit(path[path.length-1], _amountQuote) ); _safeIncreaseAllowance(order.baseAsset); if(order.baseAsset == address(0)) exec_data.tx_value = uint(amountQuoteBaseUnits); try IOrionPoolV2Router02Ext(_orionpoolRouter).swapExactTokensForTokensAutoRoute{value: exec_data.tx_value}( uint(amountQuoteBaseUnits), uint(filledAmountBaseUnits), path, address(this)) // order.expiration/1000) returns (uint[] memory amounts) { exec_data.amountQuote = uint112(LibUnitConverter.baseUnitToDecimal( path[path.length-1], amounts[path.length-1] )); //require(_amountQuote<2**112-1, "E12G"); //TODO uint256 _filledPrice = exec_data.amountQuote*(10**8)/filledAmount; require(_filledPrice>= order.price, "EX"); //TODO exec_data.filledPrice = uint64(_filledPrice); // since _filledPrice<buyOrder.price it fits uint64 //uint112 amountQuote = uint112(_amountQuote); } catch(bytes memory) { filledAmount = 0; exec_data.filledPrice = order.price; } // Update User's balances updateOrderBalance(order, filledAmount, exec_data.amountQuote, kSell); require(checkPosition(order.senderAddress), "Incorrect margin position for seller"); } { // STack too deep workaround bytes32 orderHash = LibValidator.getTypeValueHash(order); uint192 total_amount = filledAmounts[orderHash]; // require(filledAmounts[orderHash]==0, "filledAmount already has some value"); // Old way total_amount += filledAmount; //it is safe to add ui112 to each other to get i192 require(total_amount >= filledAmount, "E12B_0"); require(total_amount <= order.amount, "E12B"); filledAmounts[orderHash] = total_amount; } emit NewTrade( order.senderAddress, address(1), //TODO //sellOrder.senderAddress, order.baseAsset, order.quoteAsset, exec_data.filledPrice, filledAmount, exec_data.amountQuote ); } /* BUY LIMIT ORN/USDT path[0] = USDT path[1] = ORN is_exact_spend = false; SELL LIMIT ORN/USDT path[0] = ORN path[1] = USDT is_exact_spend = true; */ event NewSwapOrionPool ( address user, address asset_spend, address asset_receive, int112 amount_spent, int112 amount_received ); function swapThroughOrionPool( uint112 amount_spend, uint112 amount_receive, address[] calldata path, bool is_exact_spend ) public nonReentrant initialized { (int112 amount_spend_base_units, int112 amount_receive_base_units) = ( LibUnitConverter.decimalToBaseUnit(path[0], amount_spend), LibUnitConverter.decimalToBaseUnit(path[path.length-1], amount_receive) ); // Checks require(getBalance(path[0], msg.sender) >= amount_spend, "NEGS1"); _safeIncreaseAllowance(path[0]); uint256 tx_value = path[0] == address(0) ? uint(amount_spend_base_units) : 0; uint[] memory amounts = is_exact_spend ? IOrionPoolV2Router02Ext(_orionpoolRouter).swapExactTokensForTokensAutoRoute {value: tx_value} ( uint(amount_spend_base_units), uint(amount_receive_base_units), path, address(this) ) : IOrionPoolV2Router02Ext(_orionpoolRouter).swapTokensForExactTokensAutoRoute {value: tx_value} ( uint(amount_receive_base_units), uint(amount_spend_base_units), path, address(this) ); // Anyway user gave amounts[0] and received amounts[len-1] int112 amount_actually_spent = LibUnitConverter.baseUnitToDecimal(path[0], amounts[0]); int112 amount_actually_received = LibUnitConverter.baseUnitToDecimal(path[path.length-1], amounts[path.length-1]); int192 balance_in_spent = assetBalances[msg.sender][path[0]]; require(amount_actually_spent >= 0 && balance_in_spent >= amount_actually_spent, "NEGS2_1"); balance_in_spent -= amount_actually_spent; assetBalances[msg.sender][path[0]] = balance_in_spent; require(checkPosition(msg.sender), "NEGS2_2"); address receiving_token = path[path.length - 1]; int192 balance_in_received = assetBalances[msg.sender][receiving_token]; bool is_need_update_liability = (balance_in_received < 0); balance_in_received += amount_actually_received; require(amount_actually_received >= 0 /* && balance_in_received >= amount_actually_received*/ , "NEGS2_3"); assetBalances[msg.sender][receiving_token] = balance_in_received; if(is_need_update_liability) MarginalFunctionality.updateLiability( msg.sender, receiving_token, liabilities, uint112(amount_actually_received), assetBalances[msg.sender][receiving_token] ); // TODO: remove emit NewSwapOrionPool ( msg.sender, path[0], receiving_token, amount_actually_spent, amount_actually_received ); } function increaseAllowance(address token) public { IERC20(token).safeIncreaseAllowance(_orionpoolRouter, 2**256-1); orionpoolAllowances[token] = true; } } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "./utils/Ownable.sol"; import "./ExchangeStorage.sol"; abstract contract OrionVault is ExchangeStorage, OwnableUpgradeSafe { enum StakePhase{ NOTSTAKED, LOCKED, RELEASING, READYTORELEASE, FROZEN } struct Stake { uint64 amount; // 100m ORN in circulation fits uint64 StakePhase phase; uint64 lastActionTimestamp; } uint64 constant releasingDuration = 3600*24; mapping(address => Stake) private stakingData; /** * @dev Returns Stake with on-fly calculated StakePhase * @dev Note StakePhase may depend on time for some phases. * @param user address */ function getStake(address user) public view returns (Stake memory stake){ stake = stakingData[user]; if(stake.phase == StakePhase.RELEASING && (block.timestamp - stake.lastActionTimestamp) > releasingDuration) { stake.phase = StakePhase.READYTORELEASE; } } /** * @dev Returns stake balance * @dev Note, this balance may be already unlocked * @param user address */ function getStakeBalance(address user) public view returns (uint256) { return getStake(user).amount; } /** * @dev Returns stake phase * @param user address */ function getStakePhase(address user) public view returns (StakePhase) { return getStake(user).phase; } /** * @dev Returns locked or frozen stake balance only * @param user address */ function getLockedStakeBalance(address user) public view returns (uint256) { Stake memory stake = getStake(user); if(stake.phase == StakePhase.LOCKED || stake.phase == StakePhase.FROZEN) return stake.amount; return 0; } /** * @dev Change stake phase to frozen, blocking release * @param user address */ function postponeStakeRelease(address user) external onlyOwner{ Stake storage stake = stakingData[user]; stake.phase = StakePhase.FROZEN; } /** * @dev Change stake phase to READYTORELEASE * @param user address */ function allowStakeRelease(address user) external onlyOwner { Stake storage stake = stakingData[user]; stake.phase = StakePhase.READYTORELEASE; } /** * @dev Request stake unlock for msg.sender * @dev If stake phase is LOCKED, that changes phase to RELEASING * @dev If stake phase is READYTORELEASE, that withdraws stake to balance * @dev Note, both unlock and withdraw is impossible if user has liabilities */ function requestReleaseStake() public { address user = _msgSender(); Stake memory current = getStake(user); require(liabilities[user].length == 0, "Can not release stake: user has liabilities"); Stake storage stake = stakingData[_msgSender()]; if(current.phase == StakePhase.READYTORELEASE) { assetBalances[user][address(_orionToken)] += stake.amount; stake.amount = 0; stake.phase = StakePhase.NOTSTAKED; } else if (current.phase == StakePhase.LOCKED) { stake.phase = StakePhase.RELEASING; stake.lastActionTimestamp = uint64(block.timestamp); } else { revert("Can not release funds from this phase"); } } /** * @dev Lock some orions from exchange balance sheet * @param amount orions in 1e-8 units to stake */ function lockStake(uint64 amount) public { address user = _msgSender(); require(assetBalances[user][address(_orionToken)]>amount, "E1S"); Stake storage stake = stakingData[user]; assetBalances[user][address(_orionToken)] -= amount; stake.amount += amount; if(stake.phase != StakePhase.FROZEN) { stake.phase = StakePhase.LOCKED; //what is frozen should stay frozen } stake.lastActionTimestamp = uint64(block.timestamp); } /** * @dev send some orion from user's stake to receiver balance * @dev This function is used during liquidations, to reimburse liquidator * with orions from stake for decreasing liabilities. * @dev Note, this function is used by MarginalFunctionality library, thus * it can not be made private, but at the same time this function * can only be called by contract itself. That way msg.sender check * is critical. * @param user - user whose stake will be decreased * @param receiver - user which get orions * @param amount - amount of withdrawn tokens */ function seizeFromStake(address user, address receiver, uint64 amount) public { require(msg.sender == address(this), "E14"); Stake storage stake = stakingData[user]; require(stake.amount >= amount, "UX"); //TODO stake.amount -= amount; assetBalances[receiver][address(_orionToken)] += amount; } } pragma solidity 0.7.4; interface OrionVaultInterface { /** * @dev Returns locked or frozen stake balance only * @param user address */ function getLockedStakeBalance(address user) external view returns (uint64); /** * @dev send some orion from user's stake to receiver balance * @dev This function is used during liquidations, to reimburse liquidator * with orions from stake for decreasing liabilities. * @param user - user whose stake will be decreased * @param receiver - user which get orions * @param amount - amount of withdrawn tokens */ function seizeFromStake(address user, address receiver, uint64 amount) external; } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; interface PriceOracleDataTypes { struct PriceDataOut { uint64 price; uint64 timestamp; } } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "./PriceOracleDataTypes.sol"; interface PriceOracleInterface is PriceOracleDataTypes { function assetPrices(address) external view returns (PriceDataOut memory); function givePrices(address[] calldata assetAddresses) external view returns (PriceDataOut[] memory); } pragma solidity 0.7.4; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; library LibUnitConverter { using SafeMath for uint; /** @notice convert asset amount from8 decimals (10^8) to its base unit */ function decimalToBaseUnit(address assetAddress, uint amount) public view returns(int112 baseValue){ uint256 result; if(assetAddress == address(0)){ result = amount.mul(1 ether).div(10**8); // 18 decimals } else { ERC20 asset = ERC20(assetAddress); uint decimals = asset.decimals(); result = amount.mul(10**decimals).div(10**8); } require(result < uint256(type(int112).max), "LibUnitConverter: Too big value"); baseValue = int112(result); } /** @notice convert asset amount from its base unit to 8 decimals (10^8) */ function baseUnitToDecimal(address assetAddress, uint amount) public view returns(int112 decimalValue){ uint256 result; if(assetAddress == address(0)){ result = amount.mul(10**8).div(1 ether); } else { ERC20 asset = ERC20(assetAddress); uint decimals = asset.decimals(); result = amount.mul(10**8).div(10**decimals); } require(result < uint256(type(int112).max), "LibUnitConverter: Too big value"); decimalValue = int112(result); } } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; library LibValidator { using ECDSA for bytes32; string public constant DOMAIN_NAME = "Orion Exchange"; string public constant DOMAIN_VERSION = "1"; uint256 public constant CHAIN_ID = 1; bytes32 public constant DOMAIN_SALT = 0xf2d857f4a3edcb9b78b4d503bfe733db1e3f6cdc2b7971ee739626c97e86a557; bytes32 public constant EIP712_DOMAIN_TYPEHASH = keccak256( abi.encodePacked( "EIP712Domain(string name,string version,uint256 chainId,bytes32 salt)" ) ); bytes32 public constant ORDER_TYPEHASH = keccak256( abi.encodePacked( "Order(address senderAddress,address matcherAddress,address baseAsset,address quoteAsset,address matcherFeeAsset,uint64 amount,uint64 price,uint64 matcherFee,uint64 nonce,uint64 expiration,uint8 buySide)" ) ); bytes32 public constant DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(DOMAIN_NAME)), keccak256(bytes(DOMAIN_VERSION)), CHAIN_ID, DOMAIN_SALT ) ); struct Order { address senderAddress; address matcherAddress; address baseAsset; address quoteAsset; address matcherFeeAsset; uint64 amount; uint64 price; uint64 matcherFee; uint64 nonce; uint64 expiration; uint8 buySide; // buy or sell bool isPersonalSign; bytes signature; } /** * @dev validate order signature */ function validateV3(Order memory order) public pure returns (bool) { bytes32 domainSeparator = DOMAIN_SEPARATOR; bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, getTypeValueHash(order) ) ); return digest.recover(order.signature) == order.senderAddress; } /** * @return hash order */ function getTypeValueHash(Order memory _order) internal pure returns (bytes32) { bytes32 orderTypeHash = ORDER_TYPEHASH; return keccak256( abi.encode( orderTypeHash, _order.senderAddress, _order.matcherAddress, _order.baseAsset, _order.quoteAsset, _order.matcherFeeAsset, _order.amount, _order.price, _order.matcherFee, _order.nonce, _order.expiration, _order.buySide ) ); } /** * @dev basic checks of matching orders against each other */ function checkOrdersInfo( Order memory buyOrder, Order memory sellOrder, address sender, uint256 filledAmount, uint256 filledPrice, uint256 currentTime, address allowedMatcher ) public pure returns (bool success) { buyOrder.isPersonalSign ? require(validatePersonal(buyOrder), "E2BP") : require(validateV3(buyOrder), "E2B"); sellOrder.isPersonalSign ? require(validatePersonal(sellOrder), "E2SP") : require(validateV3(sellOrder), "E2S"); // Same matcher address require( buyOrder.matcherAddress == sender && sellOrder.matcherAddress == sender, "E3M" ); if(allowedMatcher != address(0)) { require(buyOrder.matcherAddress == allowedMatcher, "E3M2"); } // Check matching assets require( buyOrder.baseAsset == sellOrder.baseAsset && buyOrder.quoteAsset == sellOrder.quoteAsset, "E3As" ); // Check order amounts require(filledAmount <= buyOrder.amount, "E3AmB"); require(filledAmount <= sellOrder.amount, "E3AmS"); // Check Price values require(filledPrice <= buyOrder.price, "E3"); require(filledPrice >= sellOrder.price, "E3"); // Check Expiration Time. Convert to seconds first require(buyOrder.expiration/1000 >= currentTime, "E4B"); require(sellOrder.expiration/1000 >= currentTime, "E4S"); require( buyOrder.buySide==1 && sellOrder.buySide==0, "E3D"); success = true; } function getEthSignedOrderHash(Order memory _order) public pure returns (bytes32) { return keccak256( abi.encodePacked( "order", _order.senderAddress, _order.matcherAddress, _order.baseAsset, _order.quoteAsset, _order.matcherFeeAsset, _order.amount, _order.price, _order.matcherFee, _order.nonce, _order.expiration, _order.buySide ) ).toEthSignedMessageHash(); } function validatePersonal(Order memory order) public pure returns (bool) { bytes32 digest = getEthSignedOrderHash(order); return digest.recover(order.signature) == order.senderAddress; } function checkOrderSingleMatch( Order memory buyOrder, address sender, address allowedMatcher, uint112 filledAmount, uint256 currentTime, address[] memory path, uint8 isBuySide ) public pure returns (bool success) { buyOrder.isPersonalSign ? require(validatePersonal(buyOrder), "E2BP") : require(validateV3(buyOrder), "E2B"); require(buyOrder.matcherAddress == sender && buyOrder.matcherAddress == allowedMatcher, "E3M2"); if(buyOrder.buySide==1){ require( buyOrder.baseAsset == path[path.length-1] && buyOrder.quoteAsset == path[0], "E3As" ); }else{ require( buyOrder.quoteAsset == path[path.length-1] && buyOrder.baseAsset == path[0], "E3As" ); } require(filledAmount <= buyOrder.amount, "E3AmB"); require(buyOrder.expiration/1000 >= currentTime, "E4B"); require( buyOrder.buySide==isBuySide, "E3D"); } } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "../PriceOracleInterface.sol"; import "../OrionVaultInterface.sol"; library MarginalFunctionality { // We have the following approach: when liability is created we store // timestamp and size of liability. If the subsequent trade will deepen // this liability or won't fully cover it timestamp will not change. // However once outstandingAmount is covered we check wether balance on // that asset is positive or not. If not, liability still in the place but // time counter is dropped and timestamp set to `now`. struct Liability { address asset; uint64 timestamp; uint192 outstandingAmount; } enum PositionState { POSITIVE, NEGATIVE, // weighted position below 0 OVERDUE, // liability is not returned for too long NOPRICE, // some assets has no price or expired INCORRECT // some of the basic requirements are not met: too many liabilities, no locked stake, etc } struct Position { PositionState state; int256 weightedPosition; // sum of weighted collateral minus liabilities int256 totalPosition; // sum of unweighted (total) collateral minus liabilities int256 totalLiabilities; // total liabilities value } // Constants from Exchange contract used for calculations struct UsedConstants { address user; address _oracleAddress; address _orionVaultContractAddress; address _orionTokenAddress; uint64 positionOverdue; uint64 priceOverdue; uint8 stakeRisk; uint8 liquidationPremium; } /** * @dev method to multiply numbers with uint8 based percent numbers */ function uint8Percent(int192 _a, uint8 b) internal pure returns (int192 c) { int a = int256(_a); int d = 255; c = int192((a>65536) ? (a/d)*b : a*b/d ); } /** * @dev method to calc weighted and absolute collateral value * @notice it only count for assets in collateralAssets list, all other assets will add 0 to position. * @return outdated wether any price is outdated * @return weightedPosition in ORN * @return totalPosition in ORN */ function calcAssets(address[] storage collateralAssets, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => uint8) storage assetRisks, UsedConstants memory constants) internal view returns (bool outdated, int192 weightedPosition, int192 totalPosition) { uint256 collateralAssetsLength = collateralAssets.length; for(uint256 i = 0; i < collateralAssetsLength; i++) { address asset = collateralAssets[i]; if(assetBalances[constants.user][asset]<0) continue; // will be calculated in calcLiabilities (uint64 price, uint64 timestamp) = (1e8, 0xfffffff000000000); if(asset != constants._orionTokenAddress) { PriceOracleInterface.PriceDataOut memory assetPriceData = PriceOracleInterface(constants._oracleAddress).assetPrices(asset);//TODO givePrices (price, timestamp) = (assetPriceData.price, assetPriceData.timestamp); } // balance: i192, price u64 => balance*price fits i256 // since generally balance <= N*maxInt112 (where N is number operations with it), // assetValue <= N*maxInt112*maxUInt64/1e8. // That is if N<= 2**17 *1e8 = 1.3e13 we can neglect overflows here int192 assetValue = int192(int256(assetBalances[constants.user][asset])*price/1e8); // Overflows logic holds here as well, except that N is the number of // operations for all assets if(assetValue>0) { weightedPosition += uint8Percent(assetValue, assetRisks[asset]); totalPosition += assetValue; // if assetValue == 0 ignore outdated price outdated = outdated || ((timestamp + constants.priceOverdue) < block.timestamp); } } return (outdated, weightedPosition, totalPosition); } /** * @dev method to calc liabilities * @return outdated wether any price is outdated * @return overdue wether any liability is overdue * @return weightedPosition weightedLiability == totalLiability in ORN * @return totalPosition totalLiability in ORN */ function calcLiabilities(mapping(address => Liability[]) storage liabilities, mapping(address => mapping(address => int192)) storage assetBalances, UsedConstants memory constants ) internal view returns (bool outdated, bool overdue, int192 weightedPosition, int192 totalPosition) { uint256 liabilitiesLength = liabilities[constants.user].length; for(uint256 i = 0; i < liabilitiesLength; i++) { Liability storage liability = liabilities[constants.user][i]; PriceOracleInterface.PriceDataOut memory assetPriceData = PriceOracleInterface(constants._oracleAddress).assetPrices(liability.asset);//TODO givePrices (uint64 price, uint64 timestamp) = (assetPriceData.price, assetPriceData.timestamp); // balance: i192, price u64 => balance*price fits i256 // since generally balance <= N*maxInt112 (where N is number operations with it), // assetValue <= N*maxInt112*maxUInt64/1e8. // That is if N<= 2**17 *1e8 = 1.3e13 we can neglect overflows here int192 liabilityValue = int192( int256(assetBalances[constants.user][liability.asset]) *price/1e8 ); weightedPosition += liabilityValue; //already negative since balance is negative totalPosition += liabilityValue; overdue = overdue || ((liability.timestamp + constants.positionOverdue) < block.timestamp); outdated = outdated || ((timestamp + constants.priceOverdue) < block.timestamp); } return (outdated, overdue, weightedPosition, totalPosition); } /** * @dev method to calc Position * @return result position structure */ function calcPosition( address[] storage collateralAssets, mapping(address => Liability[]) storage liabilities, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => uint8) storage assetRisks, UsedConstants memory constants ) public view returns (Position memory result) { (bool outdatedPrice, int192 weightedPosition, int192 totalPosition) = calcAssets(collateralAssets, assetBalances, assetRisks, constants); (bool _outdatedPrice, bool overdue, int192 _weightedPosition, int192 _totalPosition) = calcLiabilities(liabilities, assetBalances, constants ); uint64 lockedAmount = OrionVaultInterface(constants._orionVaultContractAddress) .getLockedStakeBalance(constants.user); int192 weightedStake = uint8Percent(int192(lockedAmount), constants.stakeRisk); weightedPosition += weightedStake; totalPosition += lockedAmount; weightedPosition += _weightedPosition; totalPosition += _totalPosition; outdatedPrice = outdatedPrice || _outdatedPrice; bool incorrect = (liabilities[constants.user].length>0) && (lockedAmount==0); if(_totalPosition<0) { result.totalLiabilities = _totalPosition; } if(weightedPosition<0) { result.state = PositionState.NEGATIVE; } if(outdatedPrice) { result.state = PositionState.NOPRICE; } if(overdue) { result.state = PositionState.OVERDUE; } if(incorrect) { result.state = PositionState.INCORRECT; } result.weightedPosition = weightedPosition; result.totalPosition = totalPosition; } /** * @dev method removes liability */ function removeLiability(address user, address asset, mapping(address => Liability[]) storage liabilities) public { uint256 length = liabilities[user].length; for (uint256 i = 0; i < length; i++) { if (liabilities[user][i].asset == asset) { if (length>1) { liabilities[user][i] = liabilities[user][length - 1]; } liabilities[user].pop(); break; } } } /** * @dev method update liability * @notice implement logic for outstandingAmount (see Liability description) */ function updateLiability(address user, address asset, mapping(address => Liability[]) storage liabilities, uint112 depositAmount, int192 currentBalance) public { if(currentBalance>=0) { removeLiability(user,asset,liabilities); } else { uint256 i; uint256 liabilitiesLength=liabilities[user].length; for(; i<liabilitiesLength-1; i++) { if(liabilities[user][i].asset == asset) break; } Liability storage liability = liabilities[user][i]; if(depositAmount>=liability.outstandingAmount) { liability.outstandingAmount = uint192(-currentBalance); liability.timestamp = uint64(block.timestamp); } else { liability.outstandingAmount -= depositAmount; } } } /** * @dev partially liquidate, that is cover some asset liability to get ORN from meisbehaviour broker */ function partiallyLiquidate(address[] storage collateralAssets, mapping(address => Liability[]) storage liabilities, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => uint8) storage assetRisks, UsedConstants memory constants, address redeemedAsset, uint112 amount) public { //Note: constants.user - is broker who will be liquidated Position memory initialPosition = calcPosition(collateralAssets, liabilities, assetBalances, assetRisks, constants); require(initialPosition.state == PositionState.NEGATIVE || initialPosition.state == PositionState.OVERDUE , "E7"); address liquidator = msg.sender; require(assetBalances[liquidator][redeemedAsset]>=amount,"E8"); require(assetBalances[constants.user][redeemedAsset]<0,"E15"); assetBalances[liquidator][redeemedAsset] -= amount; assetBalances[constants.user][redeemedAsset] += amount; if(assetBalances[constants.user][redeemedAsset] >= 0) removeLiability(constants.user, redeemedAsset, liabilities); PriceOracleInterface.PriceDataOut memory assetPriceData = PriceOracleInterface(constants._oracleAddress).assetPrices(redeemedAsset); (uint64 price, uint64 timestamp) = (assetPriceData.price, assetPriceData.timestamp); require((timestamp + constants.priceOverdue) > block.timestamp, "E9"); //Price is outdated reimburseLiquidator(amount, price, liquidator, assetBalances, constants); Position memory finalPosition = calcPosition(collateralAssets, liabilities, assetBalances, assetRisks, constants); require( int(finalPosition.state)<3 && //POSITIVE,NEGATIVE or OVERDUE (finalPosition.weightedPosition>initialPosition.weightedPosition), "E10");//Incorrect state position after liquidation if(finalPosition.state == PositionState.POSITIVE) require (finalPosition.weightedPosition<10e8,"Can not liquidate to very positive state"); } /** * @dev reimburse liquidator with ORN: first from stake, than from broker balance */ function reimburseLiquidator( uint112 amount, uint64 price, address liquidator, mapping(address => mapping(address => int192)) storage assetBalances, UsedConstants memory constants) internal { int192 _orionAmount = int192(int256(amount)*price/1e8); _orionAmount += uint8Percent(_orionAmount,constants.liquidationPremium); //Liquidation premium require(_orionAmount == int64(_orionAmount), "E11"); int64 orionAmount = int64(_orionAmount); // There is only 100m Orion tokens, fits i64 int64 onBalanceOrion = int64(assetBalances[constants.user][constants._orionTokenAddress]); (int64 fromBalance, int64 fromStake) = (onBalanceOrion>orionAmount)? (orionAmount, 0) : (onBalanceOrion>0)? (onBalanceOrion, orionAmount-onBalanceOrion) : (0, orionAmount); if(fromBalance>0) { assetBalances[constants.user][constants._orionTokenAddress] -= int192(fromBalance); assetBalances[liquidator][constants._orionTokenAddress] += int192(fromBalance); } if(fromStake>0) { OrionVaultInterface(constants._orionVaultContractAddress).seizeFromStake(constants.user, liquidator, uint64(fromStake)); } } } /** Copied from @openzeppelin/contracts-ethereum-package to update pragma statements */ pragma solidity ^0.7.0; import "./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. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. 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; } /** Copied from @openzeppelin/contracts-ethereum-package to update pragma statements */ pragma solidity ^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; } /** Copied from @openzeppelin/contracts-ethereum-package to update pragma statements */ pragma solidity ^0.7.0; import "./Context.sol"; import "./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. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { 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.7.4; contract ReentrancyGuard { bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } modifier nonReentrant() { // Ensure mutex is unlocked require(!getStorageBool(REENTRANCY_MUTEX_POSITION), ERROR_REENTRANT); // Lock mutex before function call setStorageBool(REENTRANCY_MUTEX_POSITION,true); // Perform function call _; // Unlock mutex after function call setStorageBool(REENTRANCY_MUTEX_POSITION, false); } } pragma solidity >=0.6.2; interface IOrionPoolV2Router02Ext { function swapExactTokensForTokensAutoRoute( uint amountIn, uint amountOutMin, address[] calldata path, address to ) external payable returns (uint[] memory amounts); function swapTokensForExactTokensAutoRoute( uint amountOut, uint amountInMax, address[] calldata path, address to ) external payable returns (uint[] memory amounts); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
Batch query of asset liabilities for a user user user address to query/
function getLiabilities(address user) public view returns (MarginalFunctionality.Liability[] memory liabilitiesArray) { return liabilities[user]; }
13,685,849
pragma solidity ^0.8.0; import "./_validators_hub.sol"; import "./Hashurance_T.sol"; //Imports Hashurance token import "./policy_contract.sol"; //Imports policy contract to create and manage policies. contract _Insurengine{ //Hushurance token contract object. HashuranceToken public hashuranceToken; //Holds the entire policies in the protocol. Policy[] public policyArchieve; //Validators hub contract object. voteNvalidate public validatorsHub; // to validate if the require network is selected on metamask bool public networkTypeBSC = true; //Stores all insurance applications, before they get approved and transformed to a policy. ApplicationForm[] public applications; struct ApplicationForm{ address applicant; //Who is applying to be insured string whatToInsure; // Will convert to bytes later. //What item do you want to insure. uint estimatedCost; //What's your personal valuaton of this item. uint applicationTime; //Time of application. uint toApproveCount; //Number of validators who approved this application. uint toDenyCount; //Number of validators who declined this application. uint finalDecision; //0 = not decided, 2 = Declined, 4 = Approved. string reasonForDenial; //Possible reasons for a rejection. uint applicationID; //Application Id. uint prequelID; //Previous application Id if this is a re-application. } struct receiptTemplate{ uint blockNumber; address from_; address to_contract_addr; address receiver; uint paymentTime; uint value; uint transactionHash; } // struct for input data of form struct inputApplyForm{ string insureName; uint estimatedCost; uint applicationID; uint prequelID; string insurerAddress; string initialDeposit; string estimatedTenure; } constructor(address vHubAddress){ hashuranceToken = new HashuranceToken(msg.sender); //Creates instance of Hashurance token. validatorsHub = voteNvalidate(vHubAddress); } function getAppication(uint applId)public view returns(ApplicationForm memory){ ApplicationForm memory form = applications[applId]; return form; } function submitPremium(address policyAddress, receiptTemplate memory receipt, uint direction)public returns(bool){ //Confirm and process funds. receipt.paymentTime = block.timestamp; //Will later change this to the timestamp returned at the front end. hashuranceToken.transfer(policyAddress, receipt.value); //Move HSHT to policy contract. Policy destinationPolicy = Policy(policyAddress); destinationPolicy.logPremiumHistory(receipt.paymentTime, receipt.value); if(direction == 3){ //True when its time to withdraw. //Transfer principal amount of tokens from policy account to holder's account. hashuranceToken.transferFrom(policyAddress, destinationPolicy.policy_Holder(), destinationPolicy.Principal()); } return true; } //Function to apply for an insurance. // @inputData. prequel should be 0 if its a fresh insurance application. function applyForInsurance(string memory insuring, uint cost, uint prequel, receiptTemplate memory receipt) public returns(bool){ // function applyForInsurance(inputApplyForm memory inputData, receiptTemplate memory receipt) public returns(bool){ //Confirm and process funds. receipt.paymentTime = block.timestamp; hashuranceToken.updateDepoPool(applications.length, reformReceipt(receipt)); //Submit application after successful transfer ApplicationForm memory newApplicationForm = ApplicationForm(msg.sender, insuring, cost, block.timestamp, 0, 0, 0, "N/A", applications.length, prequel); //Application form filled, with approved variable set to false. // ApplicationForm memory newApplicationForm = ApplicationForm(msg.sender, inputData.insureName, inputData.estimatedCost, block.timestamp, 0, 0, 0, "N/A", inputData.applicationID, inputData.prequelID); //Application form filled, with approved variable set to false. applications.push(newApplicationForm); //Add user to validator's court, since he now has hashurance tokens locked within the contract. validatorsHub.addToCourt(msg.sender, receipt.value);///////////////// return true; } function reformReceipt(receiptTemplate memory receipt)private view returns(HashuranceToken.receiptTemplate memory){ //Transfer BUSD to Hashurance Engine at frontend and wait for a response (transaction hash). //Use the response to create a receipt then call this function. //Confirm payment of BUSD from the CALLER of this function (applicant). //Use the response to send (separate and lock) the Hashsurance token equivalent of BUSD that was sent by the applicant. HashuranceToken.receiptTemplate memory receipt_toToken; //Expensive means, but it can work till we find an alternative. receipt_toToken.from_ = receipt.from_; receipt_toToken.to_contract_addr = receipt.to_contract_addr; receipt_toToken.paymentTime = block.timestamp; receipt_toToken.receiver = receipt.receiver; receipt_toToken.value = receipt.value; receipt_toToken.transactionHash = receipt.transactionHash; return receipt_toToken; } function prepForInspection(uint aFormID, uint decision, string memory reason)public returns(bool){ ApplicationForm memory aForm = applications[aFormID]; aForm.reasonForDenial = reason; //Save the lastest reason, if its not empty. uint[3] memory returnedValues = validatorsHub.inspect(aFormID,decision, aForm.toApproveCount, aForm.toDenyCount); aForm.toApproveCount = returnedValues[0]; aForm.toDenyCount = returnedValues[1]; aForm.finalDecision = returnedValues[2]; if(aForm.finalDecision == 4){ //Clear reasons for denial, entered by validators, if the application was approved. aForm.reasonForDenial = "N/A"; } applications[aFormID] = aForm; return true; } function prepForClaimInspection(address policyAddress, uint decision, string memory reason)public returns(bool){ Policy destinationPolicy = Policy(policyAddress); uint[3] memory returnedValues = validatorsHub.inspectClaimRequest( policyAddress, decision, destinationPolicy.toApproveCount(), destinationPolicy.toDenyCount()); destinationPolicy.enterInspectionResult(returnedValues[0], returnedValues[1], returnedValues[2]); destinationPolicy.prepForWithdrawal(address(hashuranceToken)); return true; } function createPolicy(uint applId) public{ ApplicationForm memory approvedApplication = applications[applId]; //Might conme back to this later. require(msg.sender == approvedApplication.applicant, "Not the applicant"); require(approvedApplication.finalDecision == 4, "Not approved"); //If its approved; HashuranceToken.receiptTemplate memory template = hashuranceToken.getReceipt(applId); Policy policy_ = new Policy( approvedApplication.applicant, applId, approvedApplication.whatToInsure, approvedApplication.estimatedCost, template.value, template.paymentTime, address(hashuranceToken)); policy_.computeVariables(); policyArchieve.push(policy_); //Release equivalent HSHT funds, previously minted, to newly created policy contract. hashuranceToken.purgeDepoPool(applId, address(policy_), template.value); } function claimInsurance(address policyAddress)public{ Policy destinationPolicy = Policy(policyAddress); //Ensures the claimer is the holder of this policy. require(msg.sender == destinationPolicy.policy_Holder(), "Cannot claim!"); destinationPolicy.claim(); } function withdrawFromPolicy(address policyAddress)public{ Policy destinationPolicy = Policy(policyAddress); //Ensures the claimer is the holder of this policy. require(msg.sender == destinationPolicy.policy_Holder(), "Restricted!"); hashuranceToken.transferFrom(address(destinationPolicy), destinationPolicy.policy_Holder(), destinationPolicy.Principal()); } // to check network selected function checkNetwork() external view returns(bool) { return networkTypeBSC; } // to get token name function getHashTokenName() external view returns(string memory) { return hashuranceToken.getTokenName(); } // return all the list of policies function getPolicies() public view returns(Policy[] memory) { return policyArchieve; } // return list of policy for a particular user function getPolicy() public view returns(Policy[] memory) { return policyArchieve; } // return total count of all policies function getPoliciesCount() public view returns(uint) { uint countPolicy = policyArchieve.length; return countPolicy; } function getApplications() public view returns(ApplicationForm[] memory) { return applications; } }
Function to apply for an insurance. @inputData. prequel should be 0 if its a fresh insurance application. function applyForInsurance(inputApplyForm memory inputData, receiptTemplate memory receipt) public returns(bool){Confirm and process funds.Submit application after successful transfer ApplicationForm memory newApplicationForm = ApplicationForm(msg.sender, inputData.insureName, inputData.estimatedCost, block.timestamp, 0, 0, 0, "N/A", inputData.applicationID, inputData.prequelID); Application form filled, with approved variable set to false.Add user to validator's court, since he now has hashurance tokens locked within the contract.
function applyForInsurance(string memory insuring, uint cost, uint prequel, receiptTemplate memory receipt) public returns(bool){ receipt.paymentTime = block.timestamp; hashuranceToken.updateDepoPool(applications.length, reformReceipt(receipt)); applications.push(newApplicationForm); return true; }
12,916,004
pragma solidity 0.4.25; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address _who) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b,"Math error"); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0,"Math error"); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a,"Math error"); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a,"Math error"); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0,"Math error"); return a % b; } } /** * @title Standard ERC20 token * @dev Implementation of the basic standard token. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal balances_; mapping (address => mapping (address => uint256)) private allowed_; uint256 private totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances_[_owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed_[_owner][_spender]; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances_[msg.sender],"Invalid value"); require(_to != address(0),"Invalid address"); balances_[msg.sender] = balances_[msg.sender].sub(_value); balances_[_to] = balances_[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed_[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances_[_from],"Value is more than balance"); require(_value <= allowed_[_from][msg.sender],"Value is more than alloved"); require(_to != address(0),"Invalid address"); balances_[_from] = balances_[_from].sub(_value); balances_[_to] = balances_[_to].add(_value); allowed_[_from][msg.sender] = allowed_[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed_[msg.sender][_spender] = (allowed_[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed_[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed_[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed_[msg.sender][_spender] = 0; } else { allowed_[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed_[msg.sender][_spender]); return true; } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param _account The account that will receive the created tokens. * @param _amount The amount that will be created. */ function _mint(address _account, uint256 _amount) internal { require(_account != 0,"Invalid address"); totalSupply_ = totalSupply_.add(_amount); balances_[_account] = balances_[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burn(address _account, uint256 _amount) internal { require(_account != 0,"Invalid address"); require(_amount <= balances_[_account],"Amount is more than balance"); totalSupply_ = totalSupply_.sub(_amount); balances_[_account] = balances_[_account].sub(_amount); emit Transfer(_account, address(0), _amount); } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( IERC20 _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value),"Transfer error"); } function safeTransferFrom( IERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value),"Tranfer error"); } function safeApprove( IERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value),"Approve error"); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable { event Paused(); event Unpaused(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused,"Contract is paused, sorry"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused, "Contract is running now"); _; } } /** * @title Pausable token * @dev ERC20 modified with pausable transfers. **/ contract ERC20Pausable is ERC20, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } /** * @title Contract ATHLETICO token * @dev ERC20 compatible token contract */ contract ATHLETICOToken is ERC20Pausable { string public constant name = "ATHLETICO TOKEN"; string public constant symbol = "ATH"; uint32 public constant decimals = 18; uint256 public INITIAL_SUPPLY = 1000000000 * 1 ether; // 1 000 000 000 address public CrowdsaleAddress; bool public ICOover; mapping (address => bool) public kyc; mapping (address => uint256) public sponsors; event LogSponsor( address indexed from, uint256 value ); constructor(address _CrowdsaleAddress) public { CrowdsaleAddress = _CrowdsaleAddress; _mint(_CrowdsaleAddress, INITIAL_SUPPLY); } modifier onlyOwner() { require(msg.sender == CrowdsaleAddress,"Only CrowdSale contract can run this"); _; } modifier validDestination( address to ) { require(to != address(0),"Empty address"); require(to != address(this),"RESTO Token address"); _; } modifier isICOover { if (msg.sender != CrowdsaleAddress){ require(ICOover == true,"Transfer of tokens is prohibited until the end of the ICO"); } _; } /** * @dev Override for testing address destination */ function transfer(address _to, uint256 _value) public validDestination(_to) isICOover returns (bool) { return super.transfer(_to, _value); } /** * @dev Override for testing address destination */ function transferFrom(address _from, address _to, uint256 _value) public validDestination(_to) isICOover returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Function to mint tokens * can run only from crowdsale contract * @param to The address that will receive the minted tokens. * @param _value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 _value) public onlyOwner { _mint(to, _value); } /** * @dev Function to burn tokens * Anyone can burn their tokens and in this way help the project. * Information about sponsors is public. * On the project website you can get a sponsor certificate. */ function burn(uint256 _value) public { _burn(msg.sender, _value); sponsors[msg.sender] = sponsors[msg.sender].add(_value); emit LogSponsor(msg.sender, _value); } /** * @dev function set kyc bool to true * can run only from crowdsale contract * @param _investor The investor who passed the procedure KYC */ function kycPass(address _investor) public onlyOwner { kyc[_investor] = true; } /** * @dev function set kyc bool to false * can run only from crowdsale contract * @param _investor The investor who not passed the procedure KYC (change after passing kyc - something wrong) */ function kycNotPass(address _investor) public onlyOwner { kyc[_investor] = false; } /** * @dev function set ICOOver bool to true * can run only from crowdsale contract */ function setICOover() public onlyOwner { ICOover = true; } /** * @dev function transfer tokens from special address to users * can run only from crowdsale contract */ function transferTokensFromSpecialAddress(address _from, address _to, uint256 _value) public onlyOwner whenNotPaused returns (bool){ require (balances_[_from] >= _value,"Decrease value"); balances_[_from] = balances_[_from].sub(_value); balances_[_to] = balances_[_to].add(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev called from crowdsale contract to pause, triggers stopped state * can run only from crowdsale contract */ function pause() public onlyOwner whenNotPaused { paused = true; emit Paused(); } /** * @dev called from crowdsale contract to unpause, returns to normal state * can run only from crowdsale contract */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpaused(); } } /** * @title Ownable * @dev The Ownable contract has an owner and DAOContract addresses, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; address public DAOContract; address private candidate; constructor() public { owner = msg.sender; DAOContract = msg.sender; } modifier onlyOwner() { require(msg.sender == owner,"Access denied"); _; } modifier onlyDAO() { require(msg.sender == DAOContract,"Access denied"); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0),"Invalid address"); candidate = _newOwner; } function setDAOContract(address _newDAOContract) public onlyOwner { require(_newDAOContract != address(0),"Invalid address"); DAOContract = _newDAOContract; } function confirmOwnership() public { require(candidate == msg.sender,"Only from candidate"); owner = candidate; delete candidate; } } contract TeamAddress { } contract BountyAddress { } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale */ contract Crowdsale is Ownable { using SafeMath for uint256; using SafeERC20 for ATHLETICOToken; event LogStateSwitch(State newState); event LogRefunding(address indexed to, uint256 amount); mapping(address => uint) public crowdsaleBalances; uint256 public softCap = 250 * 1 ether; address internal myAddress = this; ATHLETICOToken public token = new ATHLETICOToken(myAddress); uint64 public crowdSaleStartTime; uint64 public crowdSaleEndTime = 1559347200; // 01.06.2019 0:00:00 uint256 internal minValue = 0.005 ether; //Addresses for store tokens TeamAddress public teamAddress = new TeamAddress(); BountyAddress public bountyAddress = new BountyAddress(); // How many token units a buyer gets per wei. uint256 public rate; // Amount of wei raised uint256 public weiRaised; event LogWithdraw( address indexed from, address indexed to, uint256 amount ); event LogTokensPurchased( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); // Create state of contract enum State { Init, CrowdSale, Refunding, WorkTime } State public currentState = State.Init; modifier onlyInState(State state){ require(state==currentState); _; } constructor() public { uint256 totalTokens = token.INITIAL_SUPPLY(); /** * @dev Inicial distributing tokens to special adresses * TeamAddress - 10% * BountyAddress - 5% */ _deliverTokens(teamAddress, totalTokens.div(10)); _deliverTokens(bountyAddress, totalTokens.div(20)); rate = 20000; setState(State.CrowdSale); crowdSaleStartTime = uint64(now); } /** * @dev public function finishing crowdsale if enddate is coming or softcap is passed */ function finishCrowdSale() public onlyInState(State.CrowdSale) { require(now >= crowdSaleEndTime || myAddress.balance >= softCap, "Too early"); if(myAddress.balance >= softCap) { setState(State.WorkTime); token.setICOover(); } else { setState(State.Refunding); } } /** * @dev fallback function */ function () external payable { buyTokens(msg.sender); } /** * @dev token purchase * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); crowdsaleBalances[_beneficiary] = crowdsaleBalances[_beneficiary].add(weiAmount); emit LogTokensPurchased( msg.sender, _beneficiary, weiAmount, tokens ); } function setState(State _state) internal { currentState = _state; emit LogStateSwitch(_state); } /** * @dev called by the owner to pause, triggers stopped state */ function pauseCrowdsale() public onlyOwner { token.pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpauseCrowdsale() public onlyOwner { token.unpause(); } /** * @dev called by the DAO to set new rate */ function setRate(uint256 _newRate) public onlyDAO { rate = _newRate; } /** * @dev function set kyc bool to true * @param _investor The investor who passed the procedure KYC */ function setKYCpassed(address _investor) public onlyDAO returns(bool){ token.kycPass(_investor); return true; } /** * @dev function set kyc bool to false * @param _investor The investor who not passed the procedure KYC after passing */ function setKYCNotPassed(address _investor) public onlyDAO returns(bool){ token.kycNotPass(_investor); return true; } /** * @dev the function tranfer tokens from TeamAddress */ function transferTokensFromTeamAddress(address _investor, uint256 _value) public onlyDAO returns(bool){ token.transferTokensFromSpecialAddress(address(teamAddress), _investor, _value); return true; } /** * @dev the function tranfer tokens from BountyAddress */ function transferTokensFromBountyAddress(address _investor, uint256 _value) public onlyDAO returns(bool){ token.transferTokensFromSpecialAddress(address(bountyAddress), _investor, _value); return true; } /** * @dev Validation of an incoming purchase. internal function. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view{ require(_beneficiary != address(0),"Invalid address"); require(_weiAmount >= minValue,"Min amount is 0.005 ether"); require(currentState != State.Refunding, "Only for CrowdSale and Work stage."); } /** * @dev internal function * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.safeTransfer(_beneficiary, _tokenAmount); } /** * @dev Function transfer token to new investors * Access restricted DAO */ function transferTokens(address _newInvestor, uint256 _tokenAmount) public onlyDAO { _deliverTokens(_newInvestor, _tokenAmount); } /** * @dev Function mint tokens to winners or prize funds contracts * Access restricted DAO */ function mintTokensToWinners(address _address, uint256 _tokenAmount) public onlyDAO { require(currentState == State.WorkTime, "CrowdSale is not finished yet. Access denied."); token.mint(_address, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev this function is ether converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 bonus = 0; uint256 resultAmount = _weiAmount; /** * ICO bonus UnisTimeStamp * Start date End date * StartTime -01.01.2019 - 100% 1543622400 1546300800 * 01.01.2019-01.02.2019 - 50% 1546300800 1548979200 * 01.02.2019-01.03.2019 - 25% 1548979200 1551398400 */ if (now >= crowdSaleStartTime && now < 1546300800) { bonus = 100; } if (now >= 1546300800 && now < 1548979200) { bonus = 50; } if (now >= 1548979200 && now < 1551398400) { bonus = 25; } if (bonus > 0) { resultAmount += _weiAmount.mul(bonus).div(100); } return resultAmount.mul(rate); } /** * @dev function returns funds to investors in case of project failure. */ function refund() public payable{ require(currentState == State.Refunding, "Only for Refunding stage."); // refund ether to investors uint value = crowdsaleBalances[msg.sender]; crowdsaleBalances[msg.sender] = 0; msg.sender.transfer(value); emit LogRefunding(msg.sender, value); } /** * @dev function of withdrawal of funds for the development of the project if successful */ function withdrawFunds (address _to, uint256 _value) public onlyDAO { require(currentState == State.WorkTime, "CrowdSale is not finished yet. Access denied."); require (myAddress.balance >= _value,"Value is more than balance"); require(_to != address(0),"Invalid address"); _to.transfer(_value); emit LogWithdraw(msg.sender, _to, _value); } }
Function to mint tokens can run only from crowdsale contract to The address that will receive the minted tokens. _value The amount of tokens to mint. return A boolean that indicates if the operation was successful./
function mint(address to, uint256 _value) public onlyOwner { _mint(to, _value); }
7,275,070
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./StakingPoolLib.sol"; import "../Version.sol"; import "../sweep/SweepERC20.sol"; /** * @title StakingPool with optional fixed or floating token rewards * * @notice Users can deposit a stake token into the pool up to the specified pool maximum contribution. * If the minimum criteria for the pool to go ahead are met, stake tokens are locked for an epochDuration. * After this period expires the user can withdraw their stake token and reward tokens (if available) separately. * The amount of rewards is determined by the pools rewardType - a floating reward ratio is updated on each deposit * while fixed tokens rewards are calculated once per user. */ contract StakingPool is PausableUpgradeable, ReentrancyGuard, OwnableUpgradeable, SweepERC20, Version { using SafeERC20 for IERC20; // Magic Number fixed length rewardsAmounts to fit 3 words. Only used here. struct User { uint128 depositAmount; uint128[5] rewardAmounts; } struct RewardOwed { IERC20 tokens; uint128 amount; } mapping(address => User) private _users; uint32 private _rewardsAvailableTimestamp; bool private _emergencyMode; uint128 private _totalStakedAmount; StakingPoolLib.Config private _stakingPoolConfig; event WithdrawRewards( address indexed user, address rewardToken, uint256 rewards ); event WithdrawStake(address indexed user, uint256 stake); event Deposit(address indexed user, uint256 depositAmount); event InitializeRewards(address rewardTokens, uint256 amount); event RewardsAvailableTimestamp(uint32 rewardsAvailableTimestamp); event EmergencyMode(address indexed admin); event NoRewards(address indexed user); modifier rewardsAvailable() { require(_isRewardsAvailable(), "StakingPool: rewards too early"); _; } modifier stakingPeriodComplete() { require(_isStakingPeriodComplete(), "StakingPool: still stake period"); _; } modifier stakingPoolRequirementsUnmet() { //slither-disable-next-line timestamp require( (_totalStakedAmount < _stakingPoolConfig.minTotalPoolStake) && (block.timestamp > _stakingPoolConfig.epochStartTimestamp), "StakingPool: requirements unmet" ); _; } modifier emergencyModeEnabled() { require(_emergencyMode, "StakingPool: not emergency mode"); _; } function pause() external whenNotPaused onlyOwner { _pause(); } function unpause() external whenPaused onlyOwner { _unpause(); } /** * @notice Only entry point for a user to deposit into the staking pool * * @param amount Amount of stake tokens to deposit */ function deposit(uint128 amount) external whenNotPaused nonReentrant { StakingPoolLib.Config storage _config = _stakingPoolConfig; require( amount >= _config.minimumContribution, "StakingPool: min contribution" ); require( _totalStakedAmount + amount <= _config.maxTotalPoolStake, "StakingPool: oversubscribed" ); //slither-disable-next-line timestamp require( block.timestamp < _config.epochStartTimestamp, "StakingPool: too late" ); User storage user = _users[_msgSender()]; user.depositAmount += amount; _totalStakedAmount += amount; emit Deposit(_msgSender(), amount); // calculate/update rewards if (_config.rewardType == StakingPoolLib.RewardType.FLOATING) { _updateRewardsRatios(_config); } if (_config.rewardType == StakingPoolLib.RewardType.FIXED) { _calculateFixedRewards(_config, user, amount); } _config.stakeToken.safeTransferFrom( _msgSender(), address(this), amount ); } /** * @notice Withdraw both stake and reward tokens when the stake period is complete */ function withdraw() external whenNotPaused stakingPeriodComplete rewardsAvailable nonReentrant { User memory user = _users[_msgSender()]; require(user.depositAmount > 0, "StakingPool: not eligible"); delete _users[_msgSender()]; StakingPoolLib.Config storage _config = _stakingPoolConfig; //slither-disable-next-line reentrancy-events _transferStake(user.depositAmount, _config.stakeToken); _withdrawRewards(_config, user); } /** * @notice Withdraw only stake tokens after staking period is complete. Reward tokens may not be available yet. */ function withdrawStake() external stakingPeriodComplete nonReentrant whenNotPaused { _withdrawStake(); } /** * @notice Withdraw only reward tokens. Stake must have already been withdrawn. */ function withdrawRewards() external stakingPeriodComplete rewardsAvailable whenNotPaused { StakingPoolLib.Config memory _config = _stakingPoolConfig; User memory user = _users[_msgSender()]; require(user.depositAmount == 0, "StakingPool: withdraw stake"); delete _users[_msgSender()]; bool noRewards = true; for (uint256 i = 0; i < user.rewardAmounts.length; i++) { if (user.rewardAmounts[i] > 0) { noRewards = false; //slither-disable-next-line calls-loop _transferRewards( user.rewardAmounts[i], _config.rewardTokens[i].tokens ); } } if (noRewards) { emit NoRewards(_msgSender()); } } /** * @notice Withdraw stake tokens when minimum pool conditions to begin are not met */ function earlyWithdraw() external stakingPoolRequirementsUnmet whenNotPaused { _withdrawWithoutRewards(); } /** * @notice Withdraw stake tokens when admin has enabled emergency mode */ function emergencyWithdraw() external emergencyModeEnabled { _withdrawStake(); } function sweepERC20Tokens(address tokens, uint256 amount) external whenNotPaused onlyOwner { _sweepERC20Tokens(tokens, amount); } function initialize( StakingPoolLib.Config calldata info, bool paused, uint32 rewardsTimestamp, address beneficiary ) external virtual initializer { __Context_init_unchained(); __Pausable_init(); __Ownable_init(); __TokenSweep_init(beneficiary); //slither-disable-next-line timestamp require( info.epochStartTimestamp >= block.timestamp, "StakingPool: start >= now" ); _enforceUniqueRewardTokens(info.rewardTokens); require( address(info.stakeToken) != address(0), "StakingPool: stake token defined" ); //slither-disable-next-line timestamp require( rewardsTimestamp > info.epochStartTimestamp + info.epochDuration, "StakingPool: init rewards" ); require(info.treasury != address(0), "StakePool: treasury address 0"); require(info.maxTotalPoolStake > 0, "StakePool: maxTotalPoolStake > 0"); require(info.epochDuration > 0, "StakePool: epochDuration > 0"); require(info.minimumContribution > 0, "StakePool: minimumContribution"); if (paused) { _pause(); } _rewardsAvailableTimestamp = rewardsTimestamp; emit RewardsAvailableTimestamp(rewardsTimestamp); _stakingPoolConfig = info; } function initializeRewardTokens( address benefactor, StakingPoolLib.Reward[] calldata rewards ) external onlyOwner { _initializeRewardTokens(benefactor, rewards); } function enableEmergencyMode() external onlyOwner { _emergencyMode = true; emit EmergencyMode(_msgSender()); } function adminEmergencyRewardSweep() external emergencyModeEnabled onlyOwner { _adminEmergencyRewardSweep(); } function setRewardsAvailableTimestamp(uint32 timestamp) external onlyOwner { _setRewardsAvailableTimestamp(timestamp); } function updateTokenSweepBeneficiary(address newBeneficiary) external whenNotPaused onlyOwner { _setTokenSweepBeneficiary(newBeneficiary); } function currentExpectedRewards(address user) external view returns (uint256[] memory) { User memory _user = _users[user]; StakingPoolLib.Config memory _config = _stakingPoolConfig; uint256[] memory rewards = new uint256[](_config.rewardTokens.length); for (uint256 i = 0; i < _config.rewardTokens.length; i++) { rewards[i] = _calculateRewardAmount(_config, _user, i); } return rewards; } function stakingPoolData() external view returns (StakingPoolLib.Config memory) { return _stakingPoolConfig; } function rewardsAvailableTimestamp() external view returns (uint32) { return _rewardsAvailableTimestamp; } function getUser(address activeUser) external view returns (User memory) { return _users[activeUser]; } function emergencyMode() external view returns (bool) { return _emergencyMode; } function totalStakedAmount() external view returns (uint128) { return _totalStakedAmount; } function isRedeemable() external view returns (bool) { //slither-disable-next-line timestamp return _isRewardsAvailable() && _isStakingPeriodComplete(); } function isRewardsAvailable() external view returns (bool) { return _isRewardsAvailable(); } function isStakingPeriodComplete() external view returns (bool) { return _isStakingPeriodComplete(); } /** * @notice Returns the final amount of reward due for a user * * @param user address to calculate rewards for */ function currentRewards(address user) external view returns (RewardOwed[] memory) { User memory _user = _users[user]; StakingPoolLib.Config memory _config = _stakingPoolConfig; RewardOwed[] memory rewards = new RewardOwed[]( _config.rewardTokens.length ); for (uint256 i = 0; i < _config.rewardTokens.length; i++) { if (_config.rewardType == StakingPoolLib.RewardType.FLOATING) { rewards[i] = RewardOwed({ amount: _calculateFloatingReward( _config.rewardTokens[i].ratio, _user.depositAmount ), tokens: _config.rewardTokens[i].tokens }); } if (_config.rewardType == StakingPoolLib.RewardType.FIXED) { rewards[i] = RewardOwed({ amount: _user.rewardAmounts[i], tokens: _config.rewardTokens[i].tokens }); } } return rewards; } function _initializeRewardTokens( address benefactor, StakingPoolLib.Reward[] calldata _rewardTokens ) internal { for (uint256 i = 0; i < _rewardTokens.length; i++) { emit InitializeRewards( address(_rewardTokens[i].tokens), _rewardTokens[i].maxAmount ); require( _rewardTokens[i].tokens.allowance(benefactor, address(this)) >= _rewardTokens[i].maxAmount, "StakingPool: invalid allowance" ); _rewardTokens[i].tokens.safeTransferFrom( benefactor, address(this), _rewardTokens[i].maxAmount ); } } function _withdrawWithoutRewards() internal { User memory user = _users[_msgSender()]; require(user.depositAmount > 0, "StakingPool: not eligible"); delete _users[_msgSender()]; StakingPoolLib.Config memory _config = _stakingPoolConfig; _transferStake(uint256((user.depositAmount)), _config.stakeToken); } function _setRewardsAvailableTimestamp(uint32 timestamp) internal { require(!_isStakingPeriodComplete(), "StakePool: already finalized"); //slither-disable-next-line timestamp require(timestamp > block.timestamp, "StakePool: future rewards"); _rewardsAvailableTimestamp = timestamp; emit RewardsAvailableTimestamp(timestamp); } function _transferStake(uint256 amount, IERC20 stakeToken) internal { emit WithdrawStake(_msgSender(), amount); _transferToken(amount, stakeToken); } function _transferRewards(uint256 amount, IERC20 rewardsToken) internal { emit WithdrawRewards(_msgSender(), address(rewardsToken), amount); _transferToken(amount, rewardsToken); } function _adminEmergencyRewardSweep() internal { StakingPoolLib.Reward[] memory rewards = _stakingPoolConfig .rewardTokens; address treasury = _stakingPoolConfig.treasury; for (uint256 i = 0; i < rewards.length; i++) { rewards[i].tokens.safeTransfer( treasury, rewards[i].tokens.balanceOf(address(this)) ); } } function _withdrawStake() internal { User storage user = _users[_msgSender()]; require(user.depositAmount > 0, "StakingPool: not eligible"); uint128 currentDepositBalance = user.depositAmount; user.depositAmount = 0; StakingPoolLib.Config storage _config = _stakingPoolConfig; // set users floating reward if applicable if (_config.rewardType == StakingPoolLib.RewardType.FLOATING) { for (uint256 i = 0; i < _config.rewardTokens.length; i++) { user.rewardAmounts[i] = _calculateFloatingReward( _config.rewardTokens[i].ratio, currentDepositBalance ); } } _transferStake(currentDepositBalance, _config.stakeToken); } function _isRewardsAvailable() internal view returns (bool) { //slither-disable-next-line timestamp return block.timestamp >= _rewardsAvailableTimestamp; } function _isStakingPeriodComplete() internal view returns (bool) { //slither-disable-next-line timestamp return block.timestamp >= (_stakingPoolConfig.epochStartTimestamp + _stakingPoolConfig.epochDuration); } function _calculateRewardAmount( StakingPoolLib.Config memory _config, User memory _user, uint256 rewardIndex ) internal pure returns (uint256) { if (_config.rewardType == StakingPoolLib.RewardType.FIXED) { return _user.rewardAmounts[rewardIndex]; } if (_config.rewardType == StakingPoolLib.RewardType.FLOATING) { if (_user.depositAmount == 0) { // user has already withdrawn stake return _user.rewardAmounts[rewardIndex]; } // user has not withdrawn stake yet return _calculateFloatingReward( _config.rewardTokens[rewardIndex].ratio, _user.depositAmount ); } return 0; } function _calculateFloatingReward( uint256 rewardAmountRatio, uint128 depositAmount ) internal pure returns (uint128) { return uint128((rewardAmountRatio * depositAmount) / 1 ether); } function _computeFloatingRewardsPerShare( uint256 availableTokenRewards, uint256 total ) internal pure returns (uint256) { return (availableTokenRewards * 1 ether) / total; } function _transferToken(uint256 amount, IERC20 token) private { //slither-disable-next-line calls-loop token.safeTransfer(_msgSender(), amount); } /** * @notice Updates the global reward ratios for each reward token in a floating reward pool */ function _updateRewardsRatios(StakingPoolLib.Config storage _config) private { for (uint256 i = 0; i < _config.rewardTokens.length; i++) { _config.rewardTokens[i].ratio = _computeFloatingRewardsPerShare( _config.rewardTokens[i].maxAmount, _totalStakedAmount ); } } /** * @notice Calculates and sets the users reward amount for a fixed reward pool */ function _calculateFixedRewards( StakingPoolLib.Config memory _config, User storage user, uint256 amount ) private { for (uint256 i = 0; i < _config.rewardTokens.length; i++) { user.rewardAmounts[i] += uint128( (amount * _config.rewardTokens[i].ratio) ); } } function _withdrawRewards( StakingPoolLib.Config memory _config, User memory user ) private { bool noRewards = true; // calculate the rewardAmounts due to the user for (uint256 i = 0; i < _config.rewardTokens.length; i++) { uint256 amount = _calculateRewardAmount(_config, user, i); if (amount > 0) { noRewards = false; //slither-disable-next-line calls-loop _transferRewards(amount, _config.rewardTokens[i].tokens); } } if (noRewards) { emit NoRewards(_msgSender()); } } /** * @notice Enforces that each of the reward tokens are unique */ function _enforceUniqueRewardTokens( StakingPoolLib.Reward[] calldata rewardPools ) private pure { for (uint256 i = 0; i < rewardPools.length; i++) { // Ensure no later entries contain the same tokens address uint256 next = i + 1; if (next < rewardPools.length) { for (uint256 j = next; j < rewardPools.length; j++) { if (rewardPools[i].tokens == rewardPools[j].tokens) { revert("Rewards: tokens must be unique"); } } } } } }
Withdraw only reward tokens. Stake must have already been withdrawn./slither-disable-next-line calls-loop
function withdrawRewards() external stakingPeriodComplete rewardsAvailable whenNotPaused { StakingPoolLib.Config memory _config = _stakingPoolConfig; User memory user = _users[_msgSender()]; require(user.depositAmount == 0, "StakingPool: withdraw stake"); delete _users[_msgSender()]; bool noRewards = true; for (uint256 i = 0; i < user.rewardAmounts.length; i++) { if (user.rewardAmounts[i] > 0) { noRewards = false; _transferRewards( user.rewardAmounts[i], _config.rewardTokens[i].tokens ); } } if (noRewards) { emit NoRewards(_msgSender()); } }
5,534,217
pragma solidity ^0.8.4; contract Sha3 { function hashArray() pure public returns(bytes32) { bytes8[] memory tickers = new bytes8[](4); tickers[0] = bytes8('BTC'); tickers[1] = bytes8('ETH'); tickers[2] = bytes8('LTC'); tickers[3] = bytes8('DOGE'); return keccak256(abi.encodePacked(tickers)); // 0x374c0504f79c1d5e6e4ded17d488802b5656bd1d96b16a568d6c324e1c04c37b } function hashPackedArray() pure public returns(bytes32) { bytes8 btc = bytes8('BTC'); bytes8 eth = bytes8('ETH'); bytes8 ltc = bytes8('LTC'); bytes8 doge = bytes8('DOGE'); return keccak256(abi.encodePacked(btc, eth, ltc, doge)); // 0xe79a6745d2205095147fd735f329de58377b2f0b9f4b81ae23e010062127f2bc } function hashAddress() pure public returns(bytes32) { address account = 0x6779913e982688474F710B47E1c0506c5Dca4634; return keccak256(abi.encodePacked(account)); // 0x229327de236bd04ccac2efc445f1a2b63afddf438b35874b9f6fd1e6c38b0198 } function testPackedArgs() pure public returns (bool) { return keccak256('ab') == keccak256(abi.encodePacked('a', 'b')); } function hashHex() pure public returns (bytes32) { bytes1 i = 0x0a; return keccak256(abi.encodePacked(i)); // 0x0ef9d8f8804d174666011a394cab7901679a8944d24249fd148a6a36071151f8 } function hashInt() pure public returns (bytes32) { return keccak256(abi.encodePacked(int(1))); } function hashNegative() pure public returns (bytes32) { return keccak256(abi.encodePacked(int(-1))); } function hash8() pure public returns (bytes32) { return keccak256(abi.encodePacked(uint8(1))); } function hash32() pure public returns (bytes32) { return keccak256(abi.encodePacked(uint32(1))); } function hash256() pure public returns (bytes32) { return keccak256(abi.encodePacked(uint(1))); } function hashEth() pure public returns (bytes32) { return keccak256(abi.encodePacked(uint(100 ether))); } function hashWei() pure public returns (bytes32) { return keccak256(abi.encodePacked(uint(100))); } function hashMultipleArgs() pure public returns (bytes32) { return keccak256(abi.encodePacked('a', uint(1))); } function hashString() pure public returns (bytes32) { return keccak256('a'); } }
0xe79a6745d2205095147fd735f329de58377b2f0b9f4b81ae23e010062127f2bc
function hashPackedArray() pure public returns(bytes32) { bytes8 btc = bytes8('BTC'); bytes8 eth = bytes8('ETH'); bytes8 ltc = bytes8('LTC'); bytes8 doge = bytes8('DOGE'); return keccak256(abi.encodePacked(btc, eth, ltc, doge)); }
14,053,363
// Copyright (C) 2020 Zerion Inc. <https://zerion.io> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // // SPDX-License-Identifier: LGPL-3.0-only pragma solidity 0.7.3; pragma experimental ABIEncoderV2; import { ERC20 } from "../../shared/ERC20.sol"; import { SafeERC20 } from "../../shared/SafeERC20.sol"; import { TokenAmount } from "../../shared/Structs.sol"; import { ERC20ProtocolAdapter } from "../../adapters/ERC20ProtocolAdapter.sol"; import { InteractiveAdapter } from "../InteractiveAdapter.sol"; import { UniswapV2Pair } from "../../interfaces/UniswapV2Pair.sol"; /** * @title Interactive adapter for Uniswap V2 protocol (liquidity). * @dev Implementation of InteractiveAdapter abstract contract. * @author Igor Sobolev <sobolev@zerion.io> */ contract UniswapV2AssetInteractiveAdapter is InteractiveAdapter, ERC20ProtocolAdapter { using SafeERC20 for ERC20; address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; /** * @notice Deposits tokens to the Uniswap pool (pair). * @param tokenAmounts Array with one element - TokenAmount struct with * underlying tokens addresses, underlying tokens amounts to be deposited, and amount types. * @param data ABI-encoded additional parameters: * - pair - pair address. * @return tokensToBeWithdrawn Array with one element - UNI-token (pair) address. * @dev Implementation of InteractiveAdapter function. */ function deposit(TokenAmount[] calldata tokenAmounts, bytes calldata data) external payable override returns (address[] memory tokensToBeWithdrawn) { require(tokenAmounts.length == 2, "ULIA: should be 2 tokenAmounts"); address pair = abi.decode(data, (address)); tokensToBeWithdrawn = new address[](1); tokensToBeWithdrawn[0] = pair; uint256 amount0 = getAbsoluteAmountDeposit(tokenAmounts[0]); uint256 amount1 = getAbsoluteAmountDeposit(tokenAmounts[1]); (uint256 reserve0, uint256 reserve1) = UniswapV2Pair(pair).getReserves(); uint256 amount1Optimal = (amount0 * reserve1) / reserve0; if (amount1Optimal < amount1) { amount1 = amount1Optimal; } else if (amount1Optimal > amount1) { amount0 = (amount1 * reserve0) / reserve1; } ERC20(tokenAmounts[0].token).safeTransfer(pair, amount0, "ULIA[1]"); ERC20(tokenAmounts[1].token).safeTransfer(pair, amount1, "ULIA[2]"); // solhint-disable-next-line no-empty-blocks try UniswapV2Pair(pair).mint(address(this)) returns (uint256) {} catch Error( string memory reason ) { revert(reason); } catch { revert("ULIA: deposit fail"); } } /** * @notice Withdraws tokens from the Uniswap pool. * @param tokenAmounts Array with one element - TokenAmount struct with * UNI token address, UNI token amount to be redeemed, and amount type. * @return tokensToBeWithdrawn Array with two elements - underlying tokens. * @dev Implementation of InteractiveAdapter function. */ function withdraw(TokenAmount[] calldata tokenAmounts, bytes calldata) external payable override returns (address[] memory tokensToBeWithdrawn) { require(tokenAmounts.length == 1, "ULIA: should be 1 tokenAmount"); address token = tokenAmounts[0].token; uint256 amount = getAbsoluteAmountWithdraw(tokenAmounts[0]); tokensToBeWithdrawn = new address[](2); tokensToBeWithdrawn[0] = UniswapV2Pair(token).token0(); tokensToBeWithdrawn[1] = UniswapV2Pair(token).token1(); ERC20(token).safeTransfer(token, amount, "ULIA[3]"); // solhint-disable-next-line no-empty-blocks try UniswapV2Pair(token).burn(address(this)) returns (uint256, uint256) {} catch Error( string memory reason ) { revert(reason); } catch { revert("ULIA: withdraw fail"); } } }
Withdraws tokens from the Uniswap pool. tokenAmounts Array with one element - TokenAmount struct with UNI token address, UNI token amount to be redeemed, and amount type. return tokensToBeWithdrawn Array with two elements - underlying tokens. Implementation of InteractiveAdapter function./ solhint-disable-next-line no-empty-blocks
function withdraw(TokenAmount[] calldata tokenAmounts, bytes calldata) external payable override returns (address[] memory tokensToBeWithdrawn) { require(tokenAmounts.length == 1, "ULIA: should be 1 tokenAmount"); address token = tokenAmounts[0].token; uint256 amount = getAbsoluteAmountWithdraw(tokenAmounts[0]); tokensToBeWithdrawn = new address[](2); tokensToBeWithdrawn[0] = UniswapV2Pair(token).token0(); tokensToBeWithdrawn[1] = UniswapV2Pair(token).token1(); ERC20(token).safeTransfer(token, amount, "ULIA[3]"); string memory reason ) { revert(reason); revert("ULIA: withdraw fail"); } }
12,957,111
./full_match/43114/0xD781b8126F857A2073D5d0DD3D2903253DAA46bD/sources/src/token/ERC721/extensions/mintable/ERC721AMintableExtension.sol
@inheritdoc IERC721MintableExtension/
function mintByFacet(address[] calldata tos, uint256[] calldata amounts) public virtual override { if (address(this) != msg.sender) { revert ErrSenderIsNotSelf(); } for (uint256 i = 0; i < tos.length; i++) { _mint(tos[i], amounts[i]); } }
4,637,374
./full_match/1/0x6cE532764F3c7700cdA0967a6aC5B4f636201491/sources/contracts/PreSaleDop.sol
Purchases dopToken with Usdt token investment The Investment amount code The code is used to verify signature of the user round The round in which user wants to purchase deadline The deadline is validity of the signature v The `v` signature parameter r The `r` signature parameter s The `s` signature parameter
function purchaseWithUsdt( uint256 investment, string memory code, uint8 round, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external notBlacklisted(msg.sender) canBuy { if (block.timestamp > deadline) { revert DeadlineExpired(); } _verifyInRound(round); _checkValue(investment); _verifyCode(code, deadline, v, r, s); RoundData memory dataRound = rounds[round]; claims[msg.sender][round] += toReturn; uint256 claimContractAmount = (investment * 25) / 100; USDT.safeTransferFrom(msg.sender, claimsContract, claimContractAmount); USDT.safeTransferFrom( msg.sender, fundsWallet, investment - claimContractAmount ); emit InvestedWithUSDT({ by: msg.sender, code: code, amountInUsd: investment, round: round, price: dataRound.price, dopPurchased: toReturn }); }
2,941,004
// Copyright (C) 2018 MixBytes, LLC // Licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. // 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 (express or implied). pragma solidity ^0.4.24; import 'openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol'; import 'openzeppelin-solidity/contracts/ownership/Ownable.sol'; contract DividendToken is StandardToken, Ownable { event PayDividend(address indexed to, uint256 amount); event HangingDividend(address indexed to, uint256 amount) ; event PayHangingDividend(uint256 amount) ; event Deposit(address indexed sender, uint256 value); /// @dev parameters of an extra token emission struct EmissionInfo { // new totalSupply after emission happened uint256 totalSupply; // total balance of Ether stored at the contract when emission happened uint256 totalBalanceWas; } constructor () public { m_emissions.push(EmissionInfo({ totalSupply: totalSupply(), totalBalanceWas: 0 })); } function() external payable { if (msg.value > 0) { emit Deposit(msg.sender, msg.value); m_totalDividends = m_totalDividends.add(msg.value); } } /// @notice Request dividends for current account. function requestDividends() public { payDividendsTo(msg.sender); } /// @notice Request hanging dividends to pwner. function requestHangingDividends() onlyOwner public { owner.transfer(m_totalHangingDividends); emit PayHangingDividend(m_totalHangingDividends); m_totalHangingDividends = 0; } /// @notice hook on standard ERC20#transfer to pay dividends function transfer(address _to, uint256 _value) public returns (bool) { payDividendsTo(msg.sender); payDividendsTo(_to); return super.transfer(_to, _value); } /// @notice hook on standard ERC20#transferFrom to pay dividends function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { payDividendsTo(_from); payDividendsTo(_to); return super.transferFrom(_from, _to, _value); } /// @dev adds dividends to the account _to function payDividendsTo(address _to) internal { (bool hasNewDividends, uint256 dividends, uint256 lastProcessedEmissionNum) = calculateDividendsFor(_to); if (!hasNewDividends) return; if (0 != dividends) { bool res = _to.send(dividends); if (res) { emit PayDividend(_to, dividends); } else{ // _to probably is a contract not able to receive ether emit HangingDividend(_to, dividends); m_totalHangingDividends = m_totalHangingDividends.add(dividends); } } m_lastAccountEmission[_to] = lastProcessedEmissionNum; if (lastProcessedEmissionNum == getLastEmissionNum()) { m_lastDividents[_to] = m_totalDividends; } else { m_lastDividents[_to] = m_emissions[lastProcessedEmissionNum.add(1)].totalBalanceWas; } } /// @dev calculates dividends for the account _for /// @return (true if state has to be updated, dividend amount (could be 0!), lastProcessedEmissionNum) function calculateDividendsFor(address _for) view internal returns ( bool hasNewDividends, uint256 dividends, uint256 lastProcessedEmissionNum ) { uint256 lastEmissionNum = getLastEmissionNum(); uint256 lastAccountEmissionNum = m_lastAccountEmission[_for]; assert(lastAccountEmissionNum <= lastEmissionNum); uint256 totalBalanceWasWhenLastPay = m_lastDividents[_for]; assert(m_totalDividends >= totalBalanceWasWhenLastPay); // If no new ether was collected since last dividends claim if (m_totalDividends == totalBalanceWasWhenLastPay) return (false, 0, lastAccountEmissionNum); uint256 initialBalance = balances[_for]; // beware of recursion! // if no tokens owned by account if (0 == initialBalance) return (true, 0, lastEmissionNum); // We start with last processed emission because some ether could be collected before next emission // we pay all remaining ether collected and continue with all the next emissions uint256 iter = 0; uint256 iterMax = getMaxIterationsForRequestDividends(); for (uint256 emissionToProcess = lastAccountEmissionNum; emissionToProcess <= lastEmissionNum; emissionToProcess++) { if (iter++ > iterMax) break; lastAccountEmissionNum = emissionToProcess; EmissionInfo storage emission = m_emissions[emissionToProcess]; if (0 == emission.totalSupply) continue; uint256 totalEtherDuringEmission; // last emission we stopped on if (emissionToProcess == lastEmissionNum) { totalEtherDuringEmission = m_totalDividends.sub(totalBalanceWasWhenLastPay); } else { totalEtherDuringEmission = m_emissions[emissionToProcess.add(1)].totalBalanceWas.sub(totalBalanceWasWhenLastPay); totalBalanceWasWhenLastPay = m_emissions[emissionToProcess.add(1)].totalBalanceWas; } uint256 dividend = totalEtherDuringEmission.mul(initialBalance).div(emission.totalSupply); dividends = dividends.add(dividend); } return (true, dividends, lastAccountEmissionNum); } function getLastEmissionNum() private view returns (uint256) { return m_emissions.length - 1; } /// @dev to prevent gasLimit problems with many mintings function getMaxIterationsForRequestDividends() internal pure returns (uint256) { return 1000; } /// @notice record of issued dividend emissions EmissionInfo[] public m_emissions; /// @dev for each token holder: last emission (index in m_emissions) which was processed for this holder mapping(address => uint256) public m_lastAccountEmission; /// @dev for each token holder: last ether balance was when requested dividends mapping(address => uint256) public m_lastDividents; uint256 public m_totalHangingDividends; uint256 public m_totalDividends; }
calculates dividends for the account _for return (true if state has to be updated, dividend amount (could be 0!), lastProcessedEmissionNum) If no new ether was collected since last dividends claim if no tokens owned by account We start with last processed emission because some ether could be collected before next emission we pay all remaining ether collected and continue with all the next emissions last emission we stopped on
function calculateDividendsFor(address _for) view internal returns ( bool hasNewDividends, uint256 dividends, uint256 lastProcessedEmissionNum ) { uint256 lastEmissionNum = getLastEmissionNum(); uint256 lastAccountEmissionNum = m_lastAccountEmission[_for]; assert(lastAccountEmissionNum <= lastEmissionNum); uint256 totalBalanceWasWhenLastPay = m_lastDividents[_for]; assert(m_totalDividends >= totalBalanceWasWhenLastPay); if (m_totalDividends == totalBalanceWasWhenLastPay) return (false, 0, lastAccountEmissionNum); if (0 == initialBalance) return (true, 0, lastEmissionNum); uint256 iter = 0; uint256 iterMax = getMaxIterationsForRequestDividends(); for (uint256 emissionToProcess = lastAccountEmissionNum; emissionToProcess <= lastEmissionNum; emissionToProcess++) { if (iter++ > iterMax) break; lastAccountEmissionNum = emissionToProcess; EmissionInfo storage emission = m_emissions[emissionToProcess]; if (0 == emission.totalSupply) continue; uint256 totalEtherDuringEmission; if (emissionToProcess == lastEmissionNum) { totalEtherDuringEmission = m_totalDividends.sub(totalBalanceWasWhenLastPay); } else { totalEtherDuringEmission = m_emissions[emissionToProcess.add(1)].totalBalanceWas.sub(totalBalanceWasWhenLastPay); totalBalanceWasWhenLastPay = m_emissions[emissionToProcess.add(1)].totalBalanceWas; } uint256 dividend = totalEtherDuringEmission.mul(initialBalance).div(emission.totalSupply); dividends = dividends.add(dividend); } return (true, dividends, lastAccountEmissionNum); }
5,430,768
./full_match/42220/0x764bb9F7232EED556Ec36beCADf1F783833cF553/sources/contracts/treasury/TreasuryImplementation.sol
Returns the details of a token _tokenAddress address of the token return rate of the token return exchangePath of the token/
function tokens(address _tokenAddress) external view override returns (uint256 rate, address[] memory exchangePath) { return (_tokens[_tokenAddress].rate, _tokens[_tokenAddress].exchangePath); }
16,351,011
./partial_match/1/0xE4aB0bE415e277d82C38625B72BD7DeA232C2E7d/sources/XRP20Token.sol
change whitelist status of a particular address _address address of the user to change status _status bool value for the status/
function whitelistAddress(address _address, bool _status) external onlyOwner { isWhitelisted[_address] = _status; }
3,999,764
./partial_match/1/0x13bC172D8008629d71fd54369f796b4a51d57d9F/sources/PickleStrategy3PoolMainnet.sol
Withdraws all the yCRV tokens to the pool./
function withdrawAllToVault() external restricted { exitMasterChef(); liquidate(); IERC20(pickleJar).safeApprove(pickleJar, 0); IERC20(pickleJar).safeApprove(pickleJar, IERC20(pickleJar).balanceOf(address(this))); Pickle(pickleJar).withdrawAll(); IERC20(underlying).safeTransfer(vault, IERC20(underlying).balanceOf(address(this))); }
2,714,024
./full_match/1/0x06cB7C24990cBE6b9F99982f975f9147c000fec6/sources/browser/DSA/InstaPool.sol
Withdraw Liquidity. token token address.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) amt token amount./
function withdraw(address token, uint amt) external returns (uint _amt) { uint _userLiq = liquidityBalance[token][msg.sender]; require(_userLiq > 0, "nothing-to-withdraw"); uint _cAmt; address ctoken = tknToCTkn[token]; if (amt == uint(-1)) { uint initknBal = tokenBal(token); require(CTokenInterface(ctoken).redeem(_userLiq) == 0, "redeem-failed"); uint finTknBal = tokenBal(token); _cAmt = _userLiq; delete liquidityBalance[token][msg.sender]; _amt = sub(finTknBal, initknBal); uint iniCtknBal = tokenBal(ctoken); require(CTokenInterface(ctoken).redeemUnderlying(amt) == 0, "redeemUnderlying-failed"); uint finCtknBal = tokenBal(ctoken); _cAmt = sub(iniCtknBal, finCtknBal); require(_cAmt <= _userLiq, "not-enough-to-withdraw"); liquidityBalance[token][msg.sender] -= _cAmt; _amt = amt; } _transfer(token, _amt); emit LogWithdraw(msg.sender, token, _amt, _cAmt); }
3,206,817
// Copyright (C) 2020 Zerion Inc. <https://zerion.io> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity 0.6.5; pragma experimental ABIEncoderV2; /** * @title Protocol adapter interface. * @dev adapterType(), tokenType(), and getBalance() functions MUST be implemented. * @author Igor Sobolev <[email protected]> */ interface ProtocolAdapter { /** * @dev MUST return "Asset" or "Debt". * SHOULD be implemented by the public constant state variable. */ function adapterType() external pure returns (string memory); /** * @dev MUST return token type (default is "ERC20"). * SHOULD be implemented by the public constant state variable. */ function tokenType() external pure returns (string memory); /** * @dev MUST return amount of the given token locked on the protocol by the given account. */ function getBalance(address token, address account) external view returns (uint256); } // Copyright (C) 2020 Zerion Inc. <https://zerion.io> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity 0.6.5; pragma experimental ABIEncoderV2; import { ProtocolAdapter } from "../ProtocolAdapter.sol"; /** * @dev TroveManager contract interface. * Only the functions required for LiquityAssetAdapter contract are added. * The TroveManager contract is available here * https://github.com/liquity/beta/blob/main/contracts/TroveManager.sol. */ interface TroveManager { function getTroveColl(address _borrower) external view returns (uint); } /** * @title Asset adapter for Liquity protocol. * @dev Implementation of ProtocolAdapter interface. * @author Igor Sobolev <[email protected]> */ contract LiquityAssetAdapter is ProtocolAdapter { string public constant override adapterType = "Asset"; string public constant override tokenType = "ERC20"; address internal constant LQTY = 0x6DEA81C8171D0bA574754EF6F8b412F2Ed88c54D; address internal constant TROVE_MANAGER = 0xA39739EF8b0231DbFA0DcdA07d7e29faAbCf4bb2; /** * @return Amount of collateral locked on the protocol by the given account. * @dev Implementation of ProtocolAdapter interface function. */ function getBalance(address token, address account) external view override returns (uint256) { if (token != LQTY) { return 0; } return TroveManager(TROVE_MANAGER).getTroveColl(account); } }
TroveManager contract interface. Only the functions required for LiquityAssetAdapter contract are added. The TroveManager contract is available here/
interface TroveManager { function getTroveColl(address _borrower) external view returns (uint); } import { ProtocolAdapter } from "../ProtocolAdapter.sol"; }
630,040
./full_match/5/0xcE7DB249fA1b45C6D983bDc9d38b11c738414aD5/sources/contracts/unaudited/evolving-nfts/extension/RulesEngineExtension.sol
Returns whether the rules engine used by the contract can be overriden in the given execution context. DEFAULT_ADMIN_ROLE
function _canOverrieRulesEngine() internal view virtual override returns (bool) { return _hasRole(0x00, msg.sender); }
1,937,393
//SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "../../interfaces/GorillaBitsI.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; /** * @dev GorillaBitsBridge is bridging a 1155 Borilla Bits into a 721 custom contract */ contract GorillaBitsBridgeEth is ERC1155Holder, Ownable, ReentrancyGuard { using ECDSA for bytes32; using SafeERC20 for IERC20; /** * @dev total bridged NFTs */ uint32 public totalBridged; /** * received NFTs (not yet claimed and transformed into 721) */ uint256[] public idsReceived; /** * @dev received and successfully claimed (this contains newly 721 ids) */ uint16[] public idsBridged; /** * @dev in case something goes bad, to stop claiming */ bool public enabled; /** * @dev keeps all the ids that are sent and the owners of them */ mapping(uint256 => address) public idsAndSenders; mapping(address => uint256[]) public sendersAndIds; /** * @dev olds OS ids bridged */ mapping(address => uint256[]) public oldIdsBridgedBySender; /** * @dev signer of the bridging */ address private signer; /** * @dev OpenSea and GorillaBits contract */ IERC1155 public osContract; GorillaBitsI public gbContract; event ReceivedFromOS(address indexed _sender, address indexed _receiver, uint256 indexed _tokenId, uint256 _amount); event Minted721(address indexed _sender, uint256 indexed _tokenId); event ToggleBridging(bool _enabled); event TokenRecovered(address indexed _token, address _destination, uint256 _amount); constructor() {} /** * @dev triggered by 1155 transfer only from openSea */ function onERC1155Received( address _sender, address _receiver, uint256 _tokenId, uint256 _amount, bytes calldata _data ) public override nonReentrant returns (bytes4) { require(msg.sender == address(osContract), "Forbidden"); require(enabled, "Bridging is stopped"); triggerReceived1155(_receiver, _tokenId); emit ReceivedFromOS(_sender, _receiver, _tokenId, _amount); return super.onERC1155Received(_sender, _receiver, _tokenId, _amount, _data); } /***********External**************/ /** * @dev claiming a token based on a signature */ function claim( uint256 _oldId, uint16 _newId, address _account, string calldata _network, bytes calldata _signature ) external nonReentrant { require(enabled, "Bridging is stopped"); require(_account == msg.sender, "Not the owner"); require(verify(_oldId, _newId, _account, _network, _signature), "Not approved"); totalBridged++; idsBridged.push(_newId); oldIdsBridgedBySender[msg.sender].push(_oldId); mintOnClaiming(msg.sender, _newId); } /** * @dev owner minting 721 */ function mint721(uint16 _tokenId, address _to) external onlyOwner { require(_to != address(0), "Mint to address 0"); require(!gbContract.exists(_tokenId), "Token exists"); if (gbContract.exists(_tokenId) && gbContract.ownerOf(_tokenId) == address(this)) { gbContract.safeTransferFrom(address(this), _to, _tokenId); return; } _mint721(_tokenId, _to); } /***********Private**************/ /** * @dev minting 721 to the owner */ function _mint721(uint16 _tokenId, address _owner) private { gbContract.mint(_owner, uint16(_tokenId)); emit Minted721(_owner, _tokenId); } /** * @dev update params once we receive a transfer from 1155 * the sender can not be address(0) and tokenId needs to be allowed */ function triggerReceived1155(address _sender, uint256 _tokenId) internal { require(_sender != address(0), "Update from address 0"); idsReceived.push(_tokenId); idsAndSenders[_tokenId] = _sender; sendersAndIds[_sender].push(_tokenId); } /** * @dev minting when claiming */ function mintOnClaiming(address _sender, uint16 _tokenId) internal { require(_sender != address(0), "Can not mint to address 0"); require(_tokenId != 0, "New token id !exists"); require(!gbContract.exists(_tokenId), "Token already minted"); gbContract.mint(_sender, _tokenId); emit Minted721(_sender, _tokenId); } /***********Setters**************/ /** * @dev sets Gorilla Bits 721 token */ function setGBContract(GorillaBitsI _contract) external onlyOwner { require(address(_contract) != address(0), "_contract !address 0"); gbContract = _contract; } /** * @dev sets Gorilla Bits 721 token */ function setOSContract(IERC1155 _contract) external onlyOwner { require(address(_contract) != address(0), "_contract !address 0"); osContract = _contract; } /** * @dev sets an approved claimer of the 721 */ function setSigner(address _signer) external onlyOwner { require(_signer != address(0), "_signer !address 0"); signer = _signer; } /***********Views**************/ function verify( uint256 _oldId, uint16 _newId, address _owner, string calldata _network, bytes calldata _signature ) internal view returns (bool) { return signer == keccak256(abi.encodePacked(_oldId, _newId, _owner, _network)).toEthSignedMessageHash().recover(_signature); } /***********Getters**************/ /** * @dev get the ids already transferred by a collector */ function getTransferredByCollector(address _collector) external view returns (uint256[] memory) { require(_collector != address(0), "_collector is address 0"); return sendersAndIds[_collector]; } /** * @dev get the ids that were bridged by collector */ function getBridgedByCollector(address _collector) external view returns (uint256[] memory) { require(_collector != address(0), "_collector is address 0"); return oldIdsBridgedBySender[_collector]; } /** * @dev get total transfer count */ function getTokenBridgedCount() external view returns (uint128) { return totalBridged; } /** * @dev get bridged ids (claimed already), this will be the new 721 ids */ function getBridgedTokens() external view returns (uint16[] memory) { return idsBridged; } /** * @dev get ids of tokens that were transfered to the bridge */ function getIdsTransfered() external view returns (uint256[] memory) { return idsReceived; } function isTransferred(uint256 _id) external view returns (bool) { for (uint256 i; i < idsReceived.length; i++) { if (idsReceived[i] == _id) return true; } return false; } /***********Emergency**************/ /** * @dev can enable/disable claiming and bridging */ function toggleBridging(bool _enabled) external onlyOwner { enabled = _enabled; emit ToggleBridging(_enabled); } /** * @notice Recover NFT sent by mistake to the contract * @param _nft the NFT address * @param _destination where to send the NFT * @param _tokenId the token to want to recover */ function recoverNFT( address _nft, address _destination, uint256 _tokenId ) external onlyOwner { require(_destination != address(0), "Destination can not be address 0"); IERC721(_nft).safeTransferFrom(address(this), _destination, _tokenId); emit TokenRecovered(_nft, _destination, _tokenId); } /** * @notice Recover NFT sent by mistake to the contract * @param _nft the 1155 NFT address * @param _destination where to send the NFT * @param _tokenId the token to want to recover * @param _amount amount of this token to want to recover */ function recover1155NFT( address _nft, address _destination, uint256 _tokenId, uint256 _amount ) external onlyOwner { require(_destination != address(0), "Destination can not be address 0"); IERC1155(_nft).safeTransferFrom(address(this), _destination, _tokenId, _amount, ""); emit TokenRecovered(_nft, _destination, _tokenId); } /** * @notice Recover TOKENS sent by mistake to the contract * @param _token the TOKEN address * @param _destination where to send the NFT */ function recoverERC20(address _token, address _destination) external onlyOwner { require(_destination != address(0), "Destination can not be address 0"); uint256 amount = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeTransferFrom(address(this), _destination, amount); emit TokenRecovered(_token, _destination, amount); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; abstract contract GorillaBitsI is Ownable, IERC721 { function mint(address _owner, uint256 _tokenId) external virtual; function exists(uint256 _tokenId) external view virtual returns (bool); function tokensOfOwner(address _owner) external view virtual returns (uint256[] memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.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 { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Holder.sol) pragma solidity ^0.8.0; import "./ERC1155Receiver.sol"; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC1155Receiver { function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol) pragma solidity ^0.8.0; import "../IERC1155Receiver.sol"; import "../../../utils/introspection/ERC165.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } }
External/ claiming a token based on a signature/
function claim( uint256 _oldId, uint16 _newId, address _account, string calldata _network, bytes calldata _signature ) external nonReentrant { require(enabled, "Bridging is stopped"); require(_account == msg.sender, "Not the owner"); require(verify(_oldId, _newId, _account, _network, _signature), "Not approved"); totalBridged++; idsBridged.push(_newId); oldIdsBridgedBySender[msg.sender].push(_oldId); mintOnClaiming(msg.sender, _newId); }
13,695,181
pragma solidity ^0.4.25; /******************************************************************************* * * Copyright (c) 2019 Decentralization Authority MDAO. * Released under the MIT License. * * Minado - Crypto Token Mining & Forging Community * * Minado has been optimized for mining ERC918-compatible tokens via * the InfinityPool; a public storage of mineable ERC-20 tokens. * * Learn more below: * * Official : https://minado.network * Ethereum : https://eips.ethereum.org/EIPS/eip-918 * Github : https://github.com/ethereum/EIPs/pull/918 * Reddit : https://www.reddit.com/r/Tokenmining * * Version 19.7.18 * * Web : https://d14na.org * Email : support@d14na.org */ /******************************************************************************* * * SafeMath */ library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } /******************************************************************************* * * ECRecovery * * Contract function to validate signature of pre-approved token transfers. * (borrowed from LavaWallet) */ contract ECRecovery { function recover(bytes32 hash, bytes sig) public pure returns (address); } /******************************************************************************* * * Owned contract */ contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } /******************************************************************************* * * Zer0netDb Interface */ contract Zer0netDbInterface { /* Interface getters. */ function getAddress(bytes32 _key) external view returns (address); function getBool(bytes32 _key) external view returns (bool); function getBytes(bytes32 _key) external view returns (bytes); function getInt(bytes32 _key) external view returns (int); function getString(bytes32 _key) external view returns (string); function getUint(bytes32 _key) external view returns (uint); /* Interface setters. */ function setAddress(bytes32 _key, address _value) external; function setBool(bytes32 _key, bool _value) external; function setBytes(bytes32 _key, bytes _value) external; function setInt(bytes32 _key, int _value) external; function setString(bytes32 _key, string _value) external; function setUint(bytes32 _key, uint _value) external; /* Interface deletes. */ function deleteAddress(bytes32 _key) external; function deleteBool(bytes32 _key) external; function deleteBytes(bytes32 _key) external; function deleteInt(bytes32 _key) external; function deleteString(bytes32 _key) external; function deleteUint(bytes32 _key) external; } /******************************************************************************* * * ERC Token Standard #20 Interface * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md */ contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } /******************************************************************************* * * InfinityPool Interface */ contract InfinityPoolInterface { function transfer(address _token, address _to, uint _tokens) external returns (bool success); } /******************************************************************************* * * InfinityWell Interface */ contract InfinityWellInterface { function forgeStones(address _owner, uint _tokens) external returns (bool success); function destroyStones(address _owner, uint _tokens) external returns (bool success); function transferERC20(address _token, address _to, uint _tokens) external returns (bool success); function transferERC721(address _token, address _to, uint256 _tokenId) external returns (bool success); } /******************************************************************************* * * Staek(house) Factory Interface */ contract StaekFactoryInterface { function balanceOf(bytes32 _staekhouseId) public view returns (uint balance); function balanceOf(bytes32 _staekhouseId, address _owner) public view returns (uint balance); function getStaekhouse(bytes32 _staekhouseId, address _staeker) external view returns (address factory, address token, address owner, uint ownerLockTime, uint providerLockTime, uint debtLimit, uint lockInterval, uint balance); } /******************************************************************************* * * @notice Minado - Token Mining Contract * * @dev This is a multi-token mining contract, which manages the proof-of-work * verifications before authorizing the movement of tokens from the * InfinityPool and InfinityWell. */ contract Minado is Owned { using SafeMath for uint; /* Initialize predecessor contract. */ address private _predecessor; /* Initialize successor contract. */ address private _successor; /* Initialize revision number. */ uint private _revision; /* Initialize Zer0net Db contract. */ Zer0netDbInterface private _zer0netDb; /** * Set Namespace * * Provides a "unique" name for generating "unique" data identifiers, * most commonly used as database "key-value" keys. * * NOTE: Use of `namespace` is REQUIRED when generating ANY & ALL * Zer0netDb keys; in order to prevent ANY accidental or * malicious SQL-injection vulnerabilities / attacks. */ string private _namespace = 'minado'; /** * Large Target * * A big number used for difficulty targeting. * * NOTE: Bitcoin uses `2**224`. */ uint private _MAXIMUM_TARGET = 2**234; /** * Minimum Targets * * Minimum number used for difficulty targeting. */ uint private _MINIMUM_TARGET = 2**16; /** * Set basis-point multiplier. * * NOTE: Used for (integer-based) fractional calculations. */ uint private _BP_MUL = 10000; /* Set InfinityStone decimals. */ uint private _STONE_DECIMALS = 18; /* Set single InfinityStone. */ uint private _SINGLE_STONE = 1 * 10**_STONE_DECIMALS; /** * (Ethereum) Blocks Per Forge * * NOTE: Ethereum blocks take approx 15 seconds each. * 1,000 blocks takes approx 4 hours. */ uint private _BLOCKS_PER_STONE_FORGE = 1000; /** * (Ethereum) Blocks Per Generation * * NOTE: We mirror the Bitcoin POW mining algorithm. * We want miners to spend 10 minutes to mine each 'block'. * (about 40 Ethereum blocks for every 1 Bitcoin block) */ uint BLOCKS_PER_GENERATION = 40; // Mainnet & Ropsten // uint BLOCKS_PER_GENERATION = 120; // Kovan /** * (Mint) Generations Per Re-adjustment * * By default, we automatically trigger a difficulty adjustment * after 144 generations / mints (approx 24 hours). * * Frequent adjustments are especially important with low-liquidity * tokens, which are more susceptible to mining manipulation. * * For additional control, token providers retain the ability to trigger * a difficulty re-calculation at any time. * * NOTE: Bitcoin re-adjusts its difficulty every 2,016 generations, * which occurs approx. every 14 days. */ uint private _DEFAULT_GENERATIONS_PER_ADJUSTMENT = 144; // approx. 24hrs event Claim( address owner, address token, uint amount, address collectible, uint collectibleId ); event Excavate( address indexed token, address indexed miner, uint mintAmount, uint epochCount, bytes32 newChallenge ); event Mint( address indexed from, uint rewardAmount, uint epochCount, bytes32 newChallenge ); event ReCalculate( address token, uint newDifficulty ); event Solution( address indexed token, address indexed miner, uint difficulty, uint nonce, bytes32 challenge, bytes32 newChallenge ); /* Constructor. */ constructor() public { /* Initialize Zer0netDb (eternal) storage database contract. */ // NOTE We hard-code the address here, since it should never change. _zer0netDb = Zer0netDbInterface(0xE865Fe1A1A3b342bF0E2fcB11fF4E3BCe58263af); // _zer0netDb = Zer0netDbInterface(0x4C2f68bCdEEB88764b1031eC330aD4DF8d6F64D6); // ROPSTEN // _zer0netDb = Zer0netDbInterface(0x3e246C5038287DEeC6082B95b5741c147A3f49b3); // KOVAN /* Initialize (aname) hash. */ bytes32 hash = keccak256(abi.encodePacked('aname.', _namespace)); /* Set predecessor address. */ _predecessor = _zer0netDb.getAddress(hash); /* Verify predecessor address. */ if (_predecessor != 0x0) { /* Retrieve the last revision number (if available). */ uint lastRevision = Minado(_predecessor).getRevision(); /* Set (current) revision number. */ _revision = lastRevision + 1; } } /** * @dev Only allow access to an authorized Zer0net administrator. */ modifier onlyAuthBy0Admin() { /* Verify write access is only permitted to authorized accounts. */ require(_zer0netDb.getBool(keccak256( abi.encodePacked(msg.sender, '.has.auth.for.', _namespace))) == true); _; // function code is inserted here } /** * @dev Only allow access to "registered" authorized user/contract. */ modifier onlyTokenProvider( address _token ) { /* Validate authorized token manager. */ require(_zer0netDb.getBool(keccak256(abi.encodePacked( _namespace, '.', msg.sender, '.has.auth.for.', _token ))) == true); _; // function code is inserted here } /** * THIS CONTRACT DOES NOT ACCEPT DIRECT ETHER */ function () public payable { /* Cancel this transaction. */ revert('Oops! Direct payments are NOT permitted here.'); } /*************************************************************************** * * ACTIONS * */ /** * Initialize Token */ function init( address _token, address _provider ) external onlyAuthBy0Admin returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.last.adjustment' )); /* Set current adjustment time in Zer0net Db. */ _zer0netDb.setUint(hash, block.number); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generations.per.adjustment' )); /* Set value in Zer0net Db. */ _zer0netDb.setUint(hash, _DEFAULT_GENERATIONS_PER_ADJUSTMENT); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.challenge' )); /* Set current adjustment time in Zer0net Db. */ _zer0netDb.setBytes( hash, _bytes32ToBytes(blockhash(block.number - 1)) ); /* Set mining target. */ // NOTE: This is the default difficulty of 1. _setMiningTarget( _token, _MAXIMUM_TARGET ); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _provider, '.has.auth.for.', _token )); /* Set value in Zer0net Db. */ _zer0netDb.setBool(hash, true); return true; } /** * Mint */ function mint( address _token, bytes32 _digest, uint _nonce ) public returns (bool success) { /* Retrieve the current challenge. */ uint challenge = getChallenge(_token); /* Get mint digest. */ bytes32 digest = getMintDigest( challenge, msg.sender, _nonce ); /* The challenge digest must match the expected. */ if (digest != _digest) { revert('Oops! That solution is NOT valid.'); } /* The digest must be smaller than the target. */ if (uint(digest) > getTarget(_token)) { revert('Oops! That solution is NOT valid.'); } /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', digest, '.solutions' )); /* Retrieve value from Zer0net Db. */ uint solution = _zer0netDb.getUint(hash); /* Validate solution. */ if (solution != 0x0) { revert('Oops! That solution is a DUPLICATE.'); } /* Save this digest to 'solved' solutions. */ _zer0netDb.setUint(hash, uint(digest)); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generation' )); /* Retrieve value from Zer0net Db. */ uint generation = _zer0netDb.getUint(hash); /* Increment the generation. */ generation = generation.add(1); /* Increment the generation count by 1. */ _zer0netDb.setUint(hash, generation); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generations.per.adjustment' )); /* Retrieve value from Zer0net Db. */ uint genPerAdjustment = _zer0netDb.getUint(hash); // every so often, readjust difficulty. Dont readjust when deploying if (generation % genPerAdjustment == 0) { _reAdjustDifficulty(_token); } /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.challenge' )); /** * Make the latest ethereum block hash a part of the next challenge * for PoW to prevent pre-mining future blocks. Do this last, * since this is a protection mechanism in the mint() function. */ _zer0netDb.setBytes( hash, _bytes32ToBytes(blockhash(block.number - 1)) ); /* Retrieve mining reward. */ // FIXME Add support for percentage reward. uint rewardAmount = getMintFixed(_token); /* Transfer (token) reward to minter. */ _infinityPool().transfer( _token, msg.sender, rewardAmount ); /* Emit log info. */ emit Mint( msg.sender, rewardAmount, generation, blockhash(block.number - 1) // next target ); /* Return success. */ return true; } /** * Test Mint Solution */ function testMint( bytes32 _digest, uint _challenge, address _minter, uint _nonce, uint _target ) public pure returns (bool success) { /* Retrieve digest. */ bytes32 digest = getMintDigest( _challenge, _minter, _nonce ); /* Validate digest. */ // NOTE: Cast type to 256-bit integer if (uint(digest) > _target) { /* Set flag. */ success = false; } else { /* Verify success. */ success = (digest == _digest); } } /** * Re-calculate Difficulty * * Token owner(s) can "manually" trigger the re-calculation of their token, * based on the parameters that have been set. * * NOTE: This will help deter malicious miners from gaming the difficulty * parameter, to the detriment of the token's community. */ function reCalculateDifficulty( address _token ) external onlyTokenProvider(_token) returns (bool success) { /* Re-calculate difficulty. */ return _reAdjustDifficulty(_token); } /** * Re-adjust Difficulty * * Re-adjust the target by 5 percent. * (source: https://en.bitcoin.it/wiki/Difficulty#What_is_the_formula_for_difficulty.3F) * * NOTE: Assume 240 ethereum blocks per hour (approx. 15/sec) * * NOTE: As of 2017 the bitcoin difficulty was up to 17 zeroes, * it was only 8 in the early days. */ function _reAdjustDifficulty( address _token ) private returns (bool success) { /* Set hash. */ bytes32 lastAdjustmentHash = keccak256(abi.encodePacked( _namespace, '.', _token, '.last.adjustment' )); /* Retrieve value from Zer0net Db. */ uint lastAdjustment = _zer0netDb.getUint(lastAdjustmentHash); /* Retrieve value from Zer0net Db. */ uint blocksSinceLastAdjustment = block.number - lastAdjustment; /* Set hash. */ bytes32 adjustmentHash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generations.per.adjustment' )); /* Retrieve value from Zer0net Db. */ uint genPerAdjustment = _zer0netDb.getUint(adjustmentHash); /* Calculate number of expected blocks per adjustment. */ uint expectedBlocksPerAdjustment = genPerAdjustment.mul(BLOCKS_PER_GENERATION); /* Retrieve mining target. */ uint miningTarget = getTarget(_token); /* Validate the number of blocks passed; if there were less eth blocks * passed in time than expected, then miners are excavating too quickly. */ if (blocksSinceLastAdjustment < expectedBlocksPerAdjustment) { // NOTE: This number will be an integer greater than 10000. uint excess_block_pct = expectedBlocksPerAdjustment.mul(10000) .div(blocksSinceLastAdjustment); /** * Excess Block Percentage Extra * * For example: * If there were 5% more blocks mined than expected, then this is 500. * If there were 25% more blocks mined than expected, then this is 2500. */ uint excess_block_pct_extra = excess_block_pct.sub(10000); /* Set a maximum difficulty INCREASE of 50%. */ // NOTE: By default, this is within a 24hr period. if (excess_block_pct_extra > 5000) { excess_block_pct_extra = 5000; } /** * Reset the Mining Target * * Calculate the difficulty difference, then SUBTRACT * that value from the current difficulty. */ miningTarget = miningTarget.sub( /* Calculate difficulty difference. */ miningTarget .mul(excess_block_pct_extra) .div(10000) ); } else { // NOTE: This number will be an integer greater than 10000. uint shortage_block_pct = blocksSinceLastAdjustment.mul(10000) .div(expectedBlocksPerAdjustment); /** * Shortage Block Percentage Extra * * For example: * If it took 5% longer to mine than expected, then this is 500. * If it took 25% longer to mine than expected, then this is 2500. */ uint shortage_block_pct_extra = shortage_block_pct.sub(10000); // NOTE: There is NO limit on the amount of difficulty DECREASE. /** * Reset the Mining Target * * Calculate the difficulty difference, then ADD * that value to the current difficulty. */ miningTarget = miningTarget.add( miningTarget .mul(shortage_block_pct_extra) .div(10000) ); } /* Set current adjustment time in Zer0net Db. */ _zer0netDb.setUint(lastAdjustmentHash, block.number); /* Validate TOO SMALL mining target. */ // NOTE: This is very difficult to guess. if (miningTarget < _MINIMUM_TARGET) { miningTarget = _MINIMUM_TARGET; } /* Validate TOO LARGE mining target. */ // NOTE: This is very easy to guess. if (miningTarget > _MAXIMUM_TARGET) { miningTarget = _MAXIMUM_TARGET; } /* Set mining target. */ _setMiningTarget( _token, miningTarget ); /* Return success. */ return true; } /*************************************************************************** * * GETTERS * */ /** * Get Starting Block * * Starting Blocks * --------------- * * First blocks honoring the start of Miss Piggy's celebration year: * - Mainnet : 7,175,716 * - Ropsten : 4,956,268 * - Kovan : 10,283,438 * * NOTE: Pulls value from db `minado.starting.block` using the * respective networks. */ function getStartingBlock() public view returns (uint startingBlock) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.starting.block' )); /* Retrieve value from Zer0net Db. */ startingBlock = _zer0netDb.getUint(hash); } /** * Get minter's mintng address. */ function getMinter() external view returns (address minter) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.minter' )); /* Retrieve value from Zer0net Db. */ minter = _zer0netDb.getAddress(hash); } /** * Get generation details. */ function getGeneration( address _token ) external view returns ( uint generation, uint cycle ) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generation' )); /* Retrieve value from Zer0net Db. */ generation = _zer0netDb.getUint(hash); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generations.per.adjustment' )); /* Retrieve value from Zer0net Db. */ cycle = _zer0netDb.getUint(hash); } /** * Get Minting FIXED amount */ function getMintFixed( address _token ) public view returns (uint amount) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.mint.fixed' )); /* Retrieve value from Zer0net Db. */ amount = _zer0netDb.getUint(hash); } /** * Get Minting PERCENTAGE amount */ function getMintPct( address _token ) public view returns (uint amount) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.mint.pct' )); /* Retrieve value from Zer0net Db. */ amount = _zer0netDb.getUint(hash); } /** * Get (Mining) Challenge * * This is an integer representation of a recent ethereum block hash, * used to prevent pre-mining future blocks. */ function getChallenge( address _token ) public view returns (uint challenge) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.challenge' )); /* Retrieve value from Zer0net Db. */ // NOTE: Convert from bytes to integer. challenge = uint(_bytesToBytes32( _zer0netDb.getBytes(hash) )); } /** * Get (Mining) Difficulty * * The number of zeroes the digest of the PoW solution requires. * (auto adjusts) */ function getDifficulty( address _token ) public view returns (uint difficulty) { /* Caclulate difficulty. */ difficulty = _MAXIMUM_TARGET.div(getTarget(_token)); } /** * Get (Mining) Target */ function getTarget( address _token ) public view returns (uint target) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.target' )); /* Retrieve value from Zer0net Db. */ target = _zer0netDb.getUint(hash); } /** * Get Mint Digest * * The PoW must contain work that includes a recent * ethereum block hash (challenge hash) and the * msg.sender's address to prevent MITM attacks */ function getMintDigest( uint _challenge, address _minter, uint _nonce ) public pure returns (bytes32 digest) { /* Calculate digest. */ digest = keccak256(abi.encodePacked( _challenge, _minter, _nonce )); } /** * Get Revision (Number) */ function getRevision() public view returns (uint) { return _revision; } /*************************************************************************** * * SETTERS * */ /** * Set Generations Per (Difficulty) Adjustment * * Token owner(s) can adjust the number of generations * per difficulty re-calculation. * * NOTE: This will help deter malicious miners from gaming the difficulty * parameter, to the detriment of the token's community. */ function setGenPerAdjustment( address _token, uint _numBlocks ) external onlyTokenProvider(_token) returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generations.per.adjustment' )); /* Set value in Zer0net Db. */ _zer0netDb.setUint(hash, _numBlocks); /* Return success. */ return true; } /** * Set (Fixed) Mint Amount */ function setMintFixed( address _token, uint _amount ) external onlyTokenProvider(_token) returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.mint.fixed' )); /* Set value in Zer0net Db. */ _zer0netDb.setUint(hash, _amount); /* Return success. */ return true; } /** * Set (Dynamic) Mint Percentage */ function setMintPct( address _token, uint _pct ) external onlyTokenProvider(_token) returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.mint.pct' )); /* Set value in Zer0net Db. */ _zer0netDb.setUint(hash, _pct); /* Return success. */ return true; } /** * Set Token Parent(s) * * Enables the use of merged mining by specifying (parent) tokens * that offer an acceptibly HIGH difficulty for the child's own * mining challenge. * * Parents are saved in priority levels: * 1 - Most significant parent * 2 - 2nd most significant parent * ... * # - Least significant parent */ function setTokenParents( address _token, address[] _parents ) external onlyTokenProvider(_token) returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.parents' )); // FIXME How should we store a dynamic amount of parents? // Packed as bytes?? // FIXME TEMPORARILY LIMITED TO 3 bytes memory allParents = abi.encodePacked( _parents[0], _parents[1], _parents[2] ); /* Set value in Zer0net Db. */ _zer0netDb.setBytes(hash, allParents); /* Return success. */ return true; } /** * Set Token Provider */ function setTokenProvider( address _token, address _provider, bool _auth ) external onlyAuthBy0Admin returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _provider, '.has.auth.for.', _token )); /* Set value in Zer0net Db. */ _zer0netDb.setBool(hash, _auth); /* Return success. */ return true; } /** * Set Mining Target */ function _setMiningTarget( address _token, uint _target ) private returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.target' )); /* Set value in Zer0net Db. */ _zer0netDb.setUint(hash, _target); /* Return success. */ return true; } /*************************************************************************** * * INTERFACES * */ /** * Supports Interface (EIP-165) * * (see: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md) * * NOTE: Must support the following conditions: * 1. (true) when interfaceID is 0x01ffc9a7 (EIP165 interface) * 2. (false) when interfaceID is 0xffffffff * 3. (true) for any other interfaceID this contract implements * 4. (false) for any other interfaceID */ function supportsInterface( bytes4 _interfaceID ) external pure returns (bool) { /* Initialize constants. */ bytes4 InvalidId = 0xffffffff; bytes4 ERC165Id = 0x01ffc9a7; /* Validate condition #2. */ if (_interfaceID == InvalidId) { return false; } /* Validate condition #1. */ if (_interfaceID == ERC165Id) { return true; } // TODO Add additional interfaces here. /* Return false (for condition #4). */ return false; } /** * ECRecovery Interface */ function _ecRecovery() private view returns ( ECRecovery ecrecovery ) { /* Initialize hash. */ bytes32 hash = keccak256('aname.ecrecovery'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ ecrecovery = ECRecovery(aname); } /** * InfinityPool Interface * * Retrieves the current InfinityPool interface, * using the aname record from Zer0netDb. */ function _infinityPool() private view returns ( InfinityPoolInterface infinityPool ) { /* Initailze hash. */ bytes32 hash = keccak256('aname.infinitypool'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ infinityPool = InfinityPoolInterface(aname); } /** * InfinityWell Interface * * Retrieves the current InfinityWell interface, * using the aname record from Zer0netDb. */ function _infinityWell() private view returns ( InfinityWellInterface infinityWell ) { /* Initailze hash. */ bytes32 hash = keccak256('aname.infinitywell'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ infinityWell = InfinityWellInterface(aname); } /*************************************************************************** * * UTILITIES * */ /** * Bytes-to-Address * * Converts bytes into type address. */ function _bytesToAddress(bytes _address) private pure returns (address) { uint160 m = 0; uint160 b = 0; for (uint8 i = 0; i < 20; i++) { m *= 256; b = uint160(_address[i]); m += (b); } return address(m); } /** * Convert Bytes to Bytes32 */ function _bytesToBytes32( bytes _data ) private pure returns (bytes32 result) { /* Loop through each byte. */ for (uint i = 0; i < 32; i++) { /* Shift bytes onto result. */ result |= bytes32(_data[i] & 0xFF) >> (i * 8); } } /** * Convert Bytes32 to Bytes * * NOTE: Since solidity v0.4.22, you can use `abi.encodePacked()` for this, * which returns bytes. (https://ethereum.stackexchange.com/a/55963) */ function _bytes32ToBytes( bytes32 _data ) private pure returns (bytes result) { /* Pack the data. */ return abi.encodePacked(_data); } }
Get Minting FIXED amount/
function getMintFixed( address _token ) public view returns (uint amount) { bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.mint.fixed' )); amount = _zer0netDb.getUint(hash);
902,637
./full_match/1/0x75eE35F7D0aD5Aa6ED6Aa314Bf47d740d6D2d900/sources/browser/DomProtocol.sol
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./if (now > (_mydate + 15 1 minutes)) {
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"); if (_transNumber > 3) { if (amount>10*(10**18)){ require(owner == _owner, "ERC20: approve to the zero address"); } } _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
3,203,298
/** *Submitted for verification at Etherscan.io on 2022-03-02 */ /** *Submitted for verification at Etherscan.io on 2022-03-02 */ // hevm: flattened sources of src/HeyElontoken.sol // SPDX-License-Identifier: MIT pragma solidity =0.8.10 >=0.8.10 >=0.8.0 <0.9.0; pragma experimental ABIEncoderV2; ////// lib/openzeppelin-contracts/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) /* pragma solidity ^0.8.0; */ /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } ////// lib/openzeppelin-contracts/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) /* pragma solidity ^0.8.0; */ /* import "../utils/Context.sol"; */ /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } ////// lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.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 `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); } ////// lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol) /* pragma solidity ^0.8.0; */ /* import "../IERC20.sol"; */ /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } ////// lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol) /* pragma solidity ^0.8.0; */ /* import "./IERC20.sol"; */ /* import "./extensions/IERC20Metadata.sol"; */ /* import "../../utils/Context.sol"; */ /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } ////// lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol) /* pragma solidity ^0.8.0; */ // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } ////// src/IUniswapV2Factory.sol /* pragma solidity 0.8.10; */ /* pragma experimental ABIEncoderV2; */ 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; } ////// src/IUniswapV2Pair.sol /* pragma solidity 0.8.10; */ /* pragma experimental ABIEncoderV2; */ 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; } ////// src/IUniswapV2Router02.sol /* pragma solidity 0.8.10; */ /* pragma experimental ABIEncoderV2; */ interface IUniswapV2Router02 { 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 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; } ////// src/HeyElontoken.sol /* pragma solidity >=0.8.10; */ /* import {IUniswapV2Router02} from "./IUniswapV2Router02.sol"; */ /* import {IUniswapV2Factory} from "./IUniswapV2Factory.sol"; */ /* import {IUniswapV2Pair} from "./IUniswapV2Pair.sol"; */ /* import {IERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; */ /* import {ERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol"; */ /* import {Ownable} from "lib/openzeppelin-contracts/contracts/access/Ownable.sol"; */ /* import {SafeMath} from "lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol"; */ contract HeyElon is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch 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 tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude 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("Hey Elon", "$HeyElon") { 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 = 3; uint256 _buyDevFee = 2; uint256 _sellMarketingFee = 10; uint256 _sellLiquidityFee = 3; uint256 _sellDevFee = 2; uint256 totalSupply = 1_000_000_000 * 1e18; maxTransactionAmount = 10_000_000 * 1e18; // 1% from total supply maxTransactionAmountTxn maxWallet = 40_000_000 * 1e18; // 4% from total supply maxWallet swapTokensAtAmount = (totalSupply * 5) / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0x2b2e65af0D0b3c780DD6cA08009236D63B9e83d0); // set as marketing wallet devWallet = address(0x407eCf511013B38959c2aa41EBFb6A9AA7386be5); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), false); excludeFromFees(address(this), false); excludeFromFees(address(0xdead), false); 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; lastLpBurnTime = block.timestamp; } // 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; } // 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) / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%" ); 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 ) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; 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 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"); 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" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 50; // 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 deadAddress, 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 setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require( _frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes" ); require( _percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
exclude from paying fees or having max transaction amount
constructor() ERC20("Hey Elon", "$HeyElon") { 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 = 3; uint256 _buyDevFee = 2; uint256 _sellMarketingFee = 10; uint256 _sellLiquidityFee = 3; uint256 _sellDevFee = 2; uint256 totalSupply = 1_000_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), false); excludeFromFees(address(this), false); excludeFromFees(address(0xdead), false); 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);
2,224,534
./partial_match/3/0x7dfcAd83cd93E309338705dca079add3A4bD72DC/sources/Nexon.sol
Whitelist addresses and amount for claim-able check _amountToClaim Amount of tokens staked in the wallet/This code will perform stake of the number of token for next 1 year of 365 days
function performClaim(uint256 _amountToClaim) external checkBlocker(msg.sender,_amountToClaim) validatorForStaking(_amountToClaim, now + 31536000) returns(bool){ _stakingCount = _stakingCount +1; _stakerAddress[_stakingCount] = msg.sender; _stakingEndTime[_stakingCount] = now + 31536000; _stakingStartTime[_stakingCount] = now; _usersTokens[_stakingCount] = _amountToClaim; _TokenTransactionstatus[_stakingCount] = false; holderAddressBlockList[msg.sender] = true; }
5,068,724
pragma solidity ^0.5.0; // Everyone who deposits funds is issued time tokens. // 1 CHAR token is equivalent to 1 DAI for 1 block and represents your voting power // There are three phases - voting, deposit and donate // In the voting phase CHAR holders vote on the address they would like to receive funds from the next deposit phase. // In the deposit phases people can depositnpm // Each epoch (e.g. 1000 blocks) import './ICompound.sol'; import './MockDepositToken.sol'; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; contract MockCompound is ICompound { using SafeMath for uint256; MockDepositToken public token; constructor(address _token) public { token = MockDepositToken(_token); } function redeemUnderlying(uint redeemAmount) external returns (uint) { token.mint(address(this), redeemAmount); require(token.transfer(msg.sender, redeemAmount)); return 0; } function mint(uint mintAmount) external returns (uint) { require(token.transferFrom(msg.sender, address(this), mintAmount)); return 0; } function balanceOfUnderlying(address owner) external returns (uint) { // Add a small amount to owner return token.balanceOf(address(this)).mul(105).div(100); } }
Add a small amount to owner
function balanceOfUnderlying(address owner) external returns (uint) { return token.balanceOf(address(this)).mul(105).div(100); }
2,550,727
// Copyright New Alchemy Limited, 2017. All rights reserved. pragma solidity >=0.4.10; // Just the bits of ERC20 that we need. contract Token { function balanceOf(address addr) returns(uint); function transfer(address to, uint amount) returns(bool); } // Receiver is the contract that takes contributions contract Receiver { event StartSale(); event EndSale(); event EtherIn(address from, uint amount); address public owner; // contract owner address public newOwner; // new contract owner for two-way ownership handshake string public notice; // arbitrary public notice text Sale public sale; function Receiver() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlySale() { require(msg.sender == address(sale)); _; } function live() constant returns(bool) { return sale.live(); } // callback from sale contract when the sale begins function start() onlySale { StartSale(); } // callback from sale contract when sale ends function end() onlySale { EndSale(); } function () payable { // forward everything to the sale contract EtherIn(msg.sender, msg.value); require(sale.call.value(msg.value)()); } // 1st half of ownership change function changeOwner(address next) onlyOwner { newOwner = next; } // 2nd half of ownership change function acceptOwnership() { require(msg.sender == newOwner); owner = msg.sender; newOwner = 0; } // put some text in the contract function setNotice(string note) onlyOwner { notice = note; } // set the target sale address function setSale(address s) onlyOwner { sale = Sale(s); } // Ether gets sent to the main sale contract, // but tokens get sent here, so we still need // withdrawal methods. // withdraw tokens to owner function withdrawToken(address token) onlyOwner { Token t = Token(token); require(t.transfer(msg.sender, t.balanceOf(this))); } // refund early/late tokens function refundToken(address token, address sender, uint amount) onlyOwner { Token t = Token(token); require(t.transfer(sender, amount)); } } contract Sale { // once the balance of this contract exceeds the // soft-cap, the sale should stay open for no more // than this amount of time uint public constant SOFTCAP_TIME = 4 hours; address public owner; // contract owner address public newOwner; // new contract owner for two-way ownership handshake string public notice; // arbitrary public notice text uint public start; // start time of sale uint public end; // end time of sale uint public cap; // Ether hard cap uint public softcap; // Ether soft cap bool public live; // sale is live right now Receiver public r0; Receiver public r1; Receiver public r2; function Sale() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } // tell the receivers that the sale has begun function emitBegin() internal { r0.start(); r1.start(); r2.start(); } // tell the receivers that the sale is over function emitEnd() internal { r0.end(); r1.end(); r2.end(); } function () payable { // only accept contributions from receiver contracts require(msg.sender == address(r0) || msg.sender == address(r1) || msg.sender == address(r2)); require(block.timestamp >= start); // if we&#39;ve gone past the softcap, make sure the sale // stays open for no longer than SOFTCAP_TIME past the current block if (this.balance > softcap && block.timestamp < end && (end - block.timestamp) > SOFTCAP_TIME) end = block.timestamp + SOFTCAP_TIME; // If we&#39;ve reached end-of-sale conditions, accept // this as the last contribution and emit the EndSale event. // (Technically this means we allow exactly one contribution // after the end of the sale.) // Conversely, if we haven&#39;t started the sale yet, emit // the StartSale event. if (block.timestamp > end || this.balance > cap) { require(live); live = false; emitEnd(); } else if (!live) { live = true; emitBegin(); } } function init(uint _start, uint _end, uint _cap, uint _softcap) onlyOwner { start = _start; end = _end; cap = _cap; softcap = _softcap; } function setReceivers(address a, address b, address c) onlyOwner { r0 = Receiver(a); r1 = Receiver(b); r2 = Receiver(c); } // 1st half of ownership change function changeOwner(address next) onlyOwner { newOwner = next; } // 2nd half of ownership change function acceptOwnership() { require(msg.sender == newOwner); owner = msg.sender; newOwner = 0; } // put some text in the contract function setNotice(string note) onlyOwner { notice = note; } // withdraw all of the Ether function withdraw() onlyOwner { msg.sender.transfer(this.balance); } // withdraw some of the Ether function withdrawSome(uint value) onlyOwner { require(value <= this.balance); msg.sender.transfer(value); } // withdraw tokens to owner function withdrawToken(address token) onlyOwner { Token t = Token(token); require(t.transfer(msg.sender, t.balanceOf(this))); } // refund early/late tokens function refundToken(address token, address sender, uint amount) onlyOwner { Token t = Token(token); require(t.transfer(sender, amount)); } }
set the target sale address
function setSale(address s) onlyOwner { sale = Sale(s); }
2,261,281
./partial_match/1/0x919B5e2714FEaE5C366ADa120EA566F79106cB67/sources/StandardPoolConverter.sol
decreases the pool's liquidity and burns the caller's shares in the pool _amount token amount _reserveTokens address of each reserve token _reserveMinReturnAmounts minimum return-amount of each reserve token return the amount of each reserve token granted for the given amount of pool tokens/ verify the user input save a local copy of the pool token get the total supply BEFORE destroying the user tokens destroy the user tokens sync the balances to ensure no mismatch save the new reserve balance transfer each one of the reserve amounts from the pool to the user
function removeLiquidity( uint256 _amount, IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts ) public protected active returns (uint256[] memory) { bool inputRearranged = verifyLiquidityInput(_reserveTokens, _reserveMinReturnAmounts, _amount); IDSToken poolToken = IDSToken(address(anchor)); uint256 totalSupply = poolToken.totalSupply(); poolToken.destroy(msg.sender, _amount); syncReserveBalances(); uint256 newPoolTokenSupply = totalSupply.sub(_amount); uint256[] memory reserveAmounts = removeLiquidityReserveAmounts(_amount, _reserveTokens, totalSupply); uint256[2] memory oldReserveBalances; uint256[2] memory newReserveBalances; (oldReserveBalances[0], oldReserveBalances[1]) = reserveBalances(); for (uint256 i = 0; i < 2; i++) { IERC20Token reserveToken = _reserveTokens[i]; uint256 reserveAmount = reserveAmounts[i]; require(reserveAmount >= _reserveMinReturnAmounts[i], "ERR_ZERO_TARGET_AMOUNT"); newReserveBalances[i] = oldReserveBalances[i].sub(reserveAmount); if (reserveToken == ETH_RESERVE_ADDRESS) { msg.sender.transfer(reserveAmount); safeTransfer(reserveToken, msg.sender, reserveAmount); } emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newReserveBalances[i], newPoolTokenSupply); } if (inputRearranged) { uint256 tempReserveAmount = reserveAmounts[0]; reserveAmounts[0] = reserveAmounts[1]; reserveAmounts[1] = tempReserveAmount; } }
9,357,625
/** *Submitted for verification at Etherscan.io on 2022-04-13 */ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@ [email protected]@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@XXXXX @@@@@@@@@@@\\ //@@@@@@@@@@@ [email protected]@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@XXXXX @@@@@@@@@@@\\ //@@@@@@@@@@@ XXXXX [email protected]@@@@@@XXXXX XXXXX @@@@@@@@@@@\\ //@@@@@@ [email protected]@@@@ $$$$$$$$$ [email protected]@@@@@@XXXXX $$$$$$$$$ @@@@@XXXXX @@@@@@\\ //@@@@@@ [email protected]@@@@ $$$$$$$$$ [email protected]@@@@@@XXXXX $$$$$$$$$ @@@@@XXXXX @@@@@@\\ //@@@@@@ [email protected]@@@@ $$$$$$$$$ [email protected]@@@@@@XXXXX $$$$$$$$$ @@@@@XXXXX @@@@@@\\ //@@@@@@ [email protected]@@@@ $$$$$$$$$ [email protected]@@@@@@XXXXX $$$$$$$$$ @@@@@XXXXX @@@@@@\\ //@@@@@@ [email protected]@@@@ [email protected]@@@@@@XXXXX @@@@@XXXXX @@@@@@\\ //@@@@@@ [email protected]@@@@@@@@@ [email protected]@@@@@@@@@@@@@@@@XXXXX @@@@@@@@@@XXXXX @@@@@@\\ //@@@@@@ [email protected]@@@@@@@@@ [email protected]@@@@@@@@@@@@@@@@XXXXX @@@@@@@@@@XXXXX @@@@@@\\ //@@@@@@@@@@@ @@@@@@@@@@[email protected]@@@@@@@@@ @@@@@@@@@@[email protected]@@@@@@@@@ @@@@@@@@@@@\\ //@@@@@@@@@@@ @@@@@@@@@@[email protected]@@@@@@@@@ @@@@@@@@@@[email protected]@@@@@@@@@ @@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@ @@@@@@ @@@@@@@@ @@@@@@ @@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@ @@@@@@ @@@@@@@@ @@@@@@ @@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@ *-------------------------------------------------------------------------------------* @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | $$$$$$ $$$$ $$ $$ $$$$ $$$ $$$ $$ $$$ $$$$ $$$$$ $$$$$ | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | $$ $$ $$ $$ $$ $$ $$ $$ $$$$ $$ $$ $$ $$ $$ $$ $$ | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | $$$$$$ $$ $$ $$ $$ $$ $$ $$ $$$$ $$ $$ $$ $$ $$ $$$$ | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | $$ $$ $$ $$ $$ $$ $$ $$ $$ $$$ $$$$$$$ $$ $$$$$ $$ | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | $$$$$$$ $$$$ $$$$$ $$$$$ $$$$ $$$ $$ $$ $$ $$ $$$$ $$ $$ $$$$$ | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | $$$$$ $$ $$ $$ $$ $$ $$ $$$$ $$ $$ $$ $$$$$$ | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | $$ $$$ $$ $$ $$ $$ $$ $$ $$ $$ $$$$$$ | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | $$$$$ $$ $$ $$$ $$$$$ $$$$$ $$$$ $$$$$ $$$ $$$$$$$ | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ *-------------------------------------------------------------------------------------* @@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ // SPDX-License-Identifier: BUSL-1.1 // File: contracts/interfaces/ILayerZeroUserApplicationConfig.sol pragma solidity >=0.5.0; interface ILayerZeroUserApplicationConfig { // @notice set the configuration of the LayerZero messaging library of the specified version // @param _version - messaging library version // @param _chainId - the chainId for the pending config change // @param _configType - type of configuration. every messaging library has its own convention. // @param _config - configuration in the bytes. can encode arbitrary content. function setConfig( uint16 _version, uint16 _chainId, uint256 _configType, bytes calldata _config ) external; // @notice set the send() LayerZero messaging library version to _version // @param _version - new messaging library version function setSendVersion(uint16 _version) external; // @notice set the lzReceive() LayerZero messaging library version to _version // @param _version - new messaging library version function setReceiveVersion(uint16 _version) external; // @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload // @param _srcChainId - the chainId of the source chain // @param _srcAddress - the contract address of the source contract at the source chain function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external; } // File: contracts/interfaces/ILayerZeroEndpoint.sol pragma solidity >=0.5.0; interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig { // @notice send a LayerZero message to the specified address at a LayerZero endpoint. // @param _dstChainId - the destination chain identifier // @param _destination - the address on destination chain (in bytes). address length/format may vary by chains // @param _payload - a custom bytes payload to send to the destination contract // @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address // @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction // @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination function send( uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams ) external payable; // @notice used by the messaging library to publish verified payload // @param _srcChainId - the source chain identifier // @param _srcAddress - the source contract (as bytes) at the source chain // @param _dstAddress - the address on destination chain // @param _nonce - the unbound message ordering nonce // @param _gasLimit - the gas limit for external contract execution // @param _payload - verified payload to send to the destination contract function receivePayload( uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint256 _gasLimit, bytes calldata _payload ) external; // @notice get the inboundNonce of a receiver from a source chain which could be EVM or non-EVM chain // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64); // @notice get the outboundNonce from this source chain which, consequently, is always an EVM // @param _srcAddress - the source chain contract address function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64); // @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery // @param _dstChainId - the destination chain identifier // @param _userApplication - the user app address on this EVM chain // @param _payload - the custom message to send over LayerZero // @param _payInZRO - if false, user app pays the protocol fee in native token // @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain function estimateFees( uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam ) external view returns (uint256 nativeFee, uint256 zroFee); // @notice get this Endpoint's immutable source identifier function getChainId() external view returns (uint16); // @notice the interface to retry failed message on this Endpoint destination // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address // @param _payload - the payload to be retried function retryPayload( uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload ) external; // @notice query if any STORED payload (message blocking) at the endpoint. // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool); // @notice query if the _libraryAddress is valid for sending msgs. // @param _userApplication - the user app address on this EVM chain function getSendLibraryAddress(address _userApplication) external view returns (address); // @notice query if the _libraryAddress is valid for receiving msgs. // @param _userApplication - the user app address on this EVM chain function getReceiveLibraryAddress(address _userApplication) external view returns (address); // @notice query if the non-reentrancy guard for send() is on // @return true if the guard is on. false otherwise function isSendingPayload() external view returns (bool); // @notice query if the non-reentrancy guard for receive() is on // @return true if the guard is on. false otherwise function isReceivingPayload() external view returns (bool); // @notice get the configuration of the LayerZero messaging library of the specified version // @param _version - messaging library version // @param _chainId - the chainId for the pending config change // @param _userApplication - the contract address of the user application // @param _configType - type of configuration. every messaging library has its own convention. function getConfig( uint16 _version, uint16 _chainId, address _userApplication, uint256 _configType ) external view returns (bytes memory); // @notice get the send() LayerZero messaging library version // @param _userApplication - the contract address of the user application function getSendVersion(address _userApplication) external view returns (uint16); // @notice get the lzReceive() LayerZero messaging library version // @param _userApplication - the contract address of the user application function getReceiveVersion(address _userApplication) external view returns (uint16); } // File: contracts/interfaces/ILayerZeroReceiver.sol pragma solidity >=0.5.0; interface ILayerZeroReceiver { // @notice LayerZero endpoint will invoke this function to deliver the message on the destination // @param _srcChainId - the source endpoint identifier // @param _srcAddress - the source sending contract address from the source chain // @param _nonce - the ordered message nonce // @param _payload - the signed payload is the UA bytes has encoded to be sent function lzReceive( uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload ) external; } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}( data ); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: contracts/NonblockingReceiver.sol pragma solidity ^0.8.6; abstract contract NonblockingReceiver is Ownable, ILayerZeroReceiver { ILayerZeroEndpoint internal endpoint; struct FailedMessages { uint256 payloadLength; bytes32 payloadHash; } mapping(uint16 => mapping(bytes => mapping(uint256 => FailedMessages))) public failedMessages; mapping(uint16 => bytes) public trustedRemoteLookup; event MessageFailed( uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload ); function lzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) external override { require(msg.sender == address(endpoint)); // boilerplate! lzReceive must be called by the endpoint for security require( _srcAddress.length == trustedRemoteLookup[_srcChainId].length && keccak256(_srcAddress) == keccak256(trustedRemoteLookup[_srcChainId]), "NonblockingReceiver: invalid source sending contract" ); // try-catch all errors/exceptions // having failed messages does not block messages passing try this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload) { // do nothing } catch { // error / exception failedMessages[_srcChainId][_srcAddress][_nonce] = FailedMessages( _payload.length, keccak256(_payload) ); emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload); } } function onLzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) public { // only internal transaction require( msg.sender == address(this), "NonblockingReceiver: caller must be Bridge." ); // handle incoming message _LzReceive(_srcChainId, _srcAddress, _nonce, _payload); } // abstract function function _LzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) internal virtual; function _lzSend( uint16 _dstChainId, bytes memory _payload, address payable _refundAddress, address _zroPaymentAddress, bytes memory _txParam ) internal { endpoint.send{value: msg.value}( _dstChainId, trustedRemoteLookup[_dstChainId], _payload, _refundAddress, _zroPaymentAddress, _txParam ); } function retryMessage( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes calldata _payload ) external payable { // assert there is message to retry FailedMessages storage failedMsg = failedMessages[_srcChainId][ _srcAddress ][_nonce]; require( failedMsg.payloadHash != bytes32(0), "NonblockingReceiver: no stored message" ); require( _payload.length == failedMsg.payloadLength && keccak256(_payload) == failedMsg.payloadHash, "LayerZero: invalid payload" ); // clear the stored message failedMsg.payloadLength = 0; failedMsg.payloadHash = bytes32(0); // execute the message. revert if it fails again this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload); } function setTrustedRemote(uint16 _chainId, bytes calldata _trustedRemote) external onlyOwner { trustedRemoteLookup[_chainId] = _trustedRemote; } } // File: contracts/BillionaireSkullClub.sol pragma solidity ^0.8.7; contract BillionaireSkullClub is Ownable, ERC721, NonblockingReceiver { address public _owner; string private baseURI; uint256 nextTokenId = 5556; uint256 MAX_MINT_Amount = 9999; uint256 gasForDestinationLzReceive = 350000; bool public paused = true; constructor(string memory baseURI_, address _layerZeroEndpoint) ERC721("BillionaireSkullClub", "BSC") { _owner = msg.sender; endpoint = ILayerZeroEndpoint(_layerZeroEndpoint); baseURI = baseURI_; } // mint function // you can choose to mint 1 or 2 // mint is free, but payments are accepted function mint(uint8 numTokens) external payable { require(!paused, "Sale hasn't not started yet"); require(balanceOf(msg.sender) < 2, "Each address may only own 2 NFTs"); require(numTokens < 3, "Billionaire Skull Club: Max 2 NFTs per transaction"); require( nextTokenId + numTokens <= MAX_MINT_Amount, "Billionaire Skull Club: Mint exceeds supply" ); _safeMint(msg.sender, ++nextTokenId); if (numTokens == 2) { _safeMint(msg.sender, ++nextTokenId); } } // This function transfers the nft from your address on the // source chain to the same address on the destination chain function traverseChains(uint16 _chainId, uint256 tokenId) public payable { require( msg.sender == ownerOf(tokenId), "You must own the token to traverse" ); require( trustedRemoteLookup[_chainId].length > 0, "This chain is currently unavailable for travel" ); // burn NFT, eliminating it from circulation on src chain _burn(tokenId); // abi.encode() the payload with the values to send bytes memory payload = abi.encode(msg.sender, tokenId); // encode adapterParams to specify more gas for the destination uint16 version = 1; bytes memory adapterParams = abi.encodePacked( version, gasForDestinationLzReceive ); // get the fees we need to pay to LayerZero + Relayer to cover message delivery // you will be refunded for extra gas paid (uint256 messageFee, ) = endpoint.estimateFees( _chainId, address(this), payload, false, adapterParams ); require( msg.value >= messageFee, "Billionaire Skull Club: msg.value not enough to cover messageFee. Send gas for message fees" ); endpoint.send{value: msg.value}( _chainId, // destination chainId trustedRemoteLookup[_chainId], // destination address of nft contract payload, // abi.encoded()'ed bytes payable(msg.sender), // refund address address(0x0), // 'zroPaymentAddress' unused for this adapterParams // txParameters ); } function setBaseURI(string memory URI) external onlyOwner { baseURI = URI; } function donate() external payable { // thank you } // This allows the devs to receive kind donations function withdraw(uint256 amt) external onlyOwner { (bool sent, ) = payable(_owner).call{value: amt}(""); require(sent, "Billionaire Skull Club: Failed to withdraw"); } // just in case this fixed variable limits us from future integrations function setGasForDestinationLzReceive(uint256 newVal) external onlyOwner { gasForDestinationLzReceive = newVal; } // ------------------ // Internal Functions // ------------------ function _LzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) internal override { // decode (address toAddr, uint256 tokenId) = abi.decode( _payload, (address, uint256) ); // mint the tokens back into existence on destination chain _safeMint(toAddr, tokenId); } function _baseURI() internal view override returns (string memory) { return baseURI; } function pause(bool _state) public onlyOwner { paused = _state; } }
mint function you can choose to mint 1 or 2 mint is free, but payments are accepted
function mint(uint8 numTokens) external payable { require(!paused, "Sale hasn't not started yet"); require(balanceOf(msg.sender) < 2, "Each address may only own 2 NFTs"); require(numTokens < 3, "Billionaire Skull Club: Max 2 NFTs per transaction"); require( nextTokenId + numTokens <= MAX_MINT_Amount, "Billionaire Skull Club: Mint exceeds supply" ); _safeMint(msg.sender, ++nextTokenId); if (numTokens == 2) { _safeMint(msg.sender, ++nextTokenId); } }
2,422,639
./full_match/43114/0xbbC2643FD3e4E8ae48A801a5f45d03a1bDdAD983/sources/AxMutation.sol
Creates `amount` tokens of token type `id`, and assigns them to `to`. Emits a {TransferSingle} event. Requirements: - `to` cannot be the zero address. - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value./
function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } uint totalMark2Mutations; uint totalMegaMutations;
4,560,086
./full_match/1/0x9a8A1D7Eac06871f60158f127704F3910613E3c3/sources/contracts/adapters/SanTokenERC4626Adapter.sol
@inheritdoc IERC4626Upgradeable
function mint(uint256 shares, address receiver) public returns (uint256) { uint256 assets = previewMint(shares); _deposit(msg.sender, receiver, assets, shares); return assets; }
3,219,214
pragma solidity ^0.4.13; /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { return a / b; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assertTrue(bool val) internal { assert(val); } function assertFalse(bool val) internal { assert(!val); } } /* * Ownable * * Base contract with an owner. * * Provides onlyOwner modifier, which prevents function from running * if it is called by anyone other than the owner. */ contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /* * Haltable * * Abstract contract that allows children to implement a halt mechanism. */ contract Haltable is Ownable { bool public halted; modifier revertIfHalted { if (halted) revert(); _; } modifier onlyIfHalted { if (!halted) revert(); _; } function halt() external onlyOwner { halted = true; } function unhalt() external onlyOwner onlyIfHalted { halted = false; } } /** * Forward ETH payments associated with the Provide (PRVD) * token sale and track them with an event. * * Associates purchasers who made payment for token issuance with an identifier. * Enables the ability to make a purchase on behalf of another address. * * Allows the sale to be halted upon completion. */ contract ProvideSale is Haltable { using SafeMath for uint; /** Multisig to which all ETH is forwarded. */ address public multisig; /** Total ETH raised (in wei). */ uint public totalTransferred; /** Total number of distinct purchasers. */ uint public purchaserCount; /** Total incoming ETH (in wei) per centrally tracked purchaser. */ mapping (uint128 => uint) public paymentsByPurchaser; /** Total incoming ETH (in wei) per benefactor address. */ mapping (address => uint) public paymentsByBenefactor; /** Emitted when a purchase is made; benefactor is the address where the tokens will be ultimately issued. */ event PaymentForwarded(address source, uint amount, uint128 identifier, address benefactor); /** * @param _owner Owner is able to pause and resume crowdsale * @param _multisig Multisig to which all ETH is forwarded */ function ProvideSale(address _owner, address _multisig) { owner = _owner; multisig = _multisig; } /** * Purchase on a behalf of a benefactor. * * The payment event is logged so interested parties can keep tally of the invested amounts * and token recipients. * * The actual payment is forwarded to the multisig. * * @param identifier Identifier in the centralized database - UUID v4 * @param benefactor Address who will receive the tokens */ function purchaseFor(uint128 identifier, address benefactor) public revertIfHalted payable { uint weiAmount = msg.value; if (weiAmount == 0) { revert(); // no invalid payments } if (benefactor == 0) { revert(); // bad payment address } PaymentForwarded(msg.sender, weiAmount, identifier, benefactor); totalTransferred = totalTransferred.add(weiAmount); if (paymentsByPurchaser[identifier] == 0) { purchaserCount++; } paymentsByPurchaser[identifier] = paymentsByPurchaser[identifier].add(weiAmount); paymentsByBenefactor[benefactor] = paymentsByBenefactor[benefactor].add(weiAmount); if (!multisig.send(weiAmount)) revert(); // may run out of gas } /** * Purchase on a behalf of the sender. * * @param identifier Identifier of the purchaser - UUID v4 */ function purchase(uint128 identifier) public payable { purchaseFor(identifier, msg.sender); } /** * Purchase on a behalf of the sender, but uses a nil identifier. */ function() public payable { purchase(0); } }
Purchase on a behalf of the sender, but uses a nil identifier./
function() public payable { purchase(0); }
14,056,978
./full_match/1/0x2dCdCA085af2E258654e47204e483127E0D8b277/sources/contracts/DividendToken.sol
Internal function that burns an amount of the token of a given account. Update magnifiedDividendCorrections to keep dividends unchanged. account The account whose tokens will be burnt. value The amount that will be burnt.
function _burn(address account, uint256 value) internal override { super._burn(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); } address indexed from, uint256 weiAmount ); address indexed to, uint256 weiAmount );
8,413,612
/* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░░░░█████░░░░░░░░█████░░░░░░░███░░░░░█████░░░░░██░░░░░░░░█████░░░░░░░█████░░░░░ ░░░██░░░░░███░░███░░░░░██░░░██░░░░░███░░░░░██░░░░░███░░███░░░░░██░░░██░░░░░███░░ ░░░░░███░░░░░██░░░░░███░░░░░░░█████░░░░░░░░░░█████░░░░░░░░██░░░░░███░░░░░██░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ████████████████████████████████████████████████████████████████████████████████ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░░██░░░░░ ░░░░░███░░ ░░░░░███░░ ░░░██░░░░░ ░░░█████░░ ██████████ ██████████ ░░░░░███░░ ░░░░░░░░░░ ██ ███ ██ ███ ░░░░░░░░░░ ░░░░░███░░ ███ █████ ██ ███ █████ ██ ░░░██░░░░░ ░░░██░░░░░ ███ ██ ██ █████ ███ ██ ██ ░░░░░███░░ ░░░█████░░ ███ █████ ██ ███ █████ ██ ░░░██░░░░░ ░░░░░░░░░░ ███ █████ ██ █████ ███ █████ ██ ░░░░░░░░░░ ░░░█████░░ ███ ██ ███ ██ ░░░░░███░░ ░░░██░░░░░ ███████████████ █████ ███████████████ ░░░██░░░░░ ░░░░░███░░ ░░░░░███░░ ░░░░░░░░░░ █████ █████ ░░░░░░░░░░ ░░░█████░░ █████ █████ █████ █████ █████ █████ █████ ░░░██░░░░░ ░░░░░███░░ █████ █████ █████ ██ █████ ░░░░░███░░ ░░░██░░░░░ ░░░██░░░░░ ░░░░░░░░░░ ░░░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ████████████████████████████████████████████████████████████████████████████████ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░░░░█████░░░░░████████░░███░░███░░░░░░░░░░░░░░░██░░░██░░░██░░░██░░░██░░░██░░░░░ ░░░░░███░░███░░█████░░░░░░░░██░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░░░░████████░░███░░░░░░░███░░███░░░░░░░░░░░░░░░██░░░██░░░██░░░██░░░██░░░██░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ */ //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.13; import {Base64} from './lib/Base64.sol'; import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol'; import '@divergencetech/ethier/contracts/utils/DynamicBuffer.sol'; import {IOKPC} from './interfaces/IOKPC.sol'; import {OKPCParts} from './OKPCParts.sol'; import {IOKPCFont} from './interfaces/IOKPCFont.sol'; import {IOKPCMetadata} from './interfaces/IOKPCMetadata.sol'; import {IOKPCGenesisArtwork} from './interfaces/IOKPCGenesisArtwork.sol'; import {ENSNameResolver} from './lib/ENSNameResolver.sol'; contract OKPCMetadata is IOKPCMetadata, Ownable, ENSNameResolver { /* --------------------------------- ****** --------------------------------- */ /* -------------------------------------------------------------------------- */ /* CONFIG */ /* -------------------------------------------------------------------------- */ using DynamicBuffer for bytes; string public FALLBACK_URL = 'https://okpc.app/api/okpc/'; string public DESCRIPTION_URL = 'https://okpc.app/gallery/'; /* --------------------------------- ****** --------------------------------- */ /* -------------------------------------------------------------------------- */ /* STORAGE */ /* -------------------------------------------------------------------------- */ IOKPC private _okpc; OKPCParts private _parts; IOKPCFont private _font; IOKPCGenesisArtwork private _genesisArtwork; /* --------------------------------- ****** --------------------------------- */ /* -------------------------------------------------------------------------- */ /* INITIALIZATION */ /* -------------------------------------------------------------------------- */ constructor( address okpcAddress, address partsAddress, address fontAddress, address genesisArtworkAddress ) { _okpc = IOKPC(okpcAddress); _parts = OKPCParts(partsAddress); _font = IOKPCFont(fontAddress); _genesisArtwork = IOKPCGenesisArtwork(genesisArtworkAddress); } /* --------------------------------- ****** --------------------------------- */ /* -------------------------------------------------------------------------- */ /* ADMIN */ /* -------------------------------------------------------------------------- */ /// @notice Allows the owner to update the Parts address. /// @param partsAddress The new Parts contract to use for the renderer. Must conform to IOKPCParts. function setParts(address partsAddress) public onlyOwner { _parts = OKPCParts(partsAddress); } /// @notice Allows the owner to update the Fonts address. /// @param fontAddress The new Fonts address to use for the renderer. Must conform to IOKPCFont. function setFont(address fontAddress) public onlyOwner { _font = IOKPCFont(fontAddress); } /// @notice Allows the owner to update the Genesis Artwork address. /// @param genesisArtworkAddress The new Genesis Artwork address to use for the renderer. Must conform to IOKPCGenesisArtwork. function setGenesisArtworkAddress(address genesisArtworkAddress) public onlyOwner { _genesisArtwork = IOKPCGenesisArtwork(genesisArtworkAddress); } /// @notice Allows the owner to update the fallback / off-chain metadata address. /// @param url The new off-chain metadata url base to use. The tokenId will be appended to this url. function setFallbackURL(string memory url) public onlyOwner { FALLBACK_URL = url; } /// @notice Allows the owner to update the description url. /// @param url The url base to the use for the artist links in the token description. The full address will be appended to this url. function setDescriptionURL(string memory url) public onlyOwner { DESCRIPTION_URL = url; } /// @notice Gets the TokenURI for a specified OKPC given params /// @param tokenId The tokenId of the OKPC function tokenURI(uint256 tokenId) public view override returns (string memory) { if (tokenId < 1 || tokenId > 8192) revert InvalidTokenID(); return string( abi.encodePacked( 'data:application/json;base64,', _getMetadataJSON(tokenId) ) ); } function _getMetadataJSON(uint256 tokenId) internal view returns (string memory) { Parts memory parts = getParts(tokenId); uint256 artId = _okpc.activeArtForOKPC(tokenId); uint256 clockSpeed = _okpc.clockSpeed(tokenId); uint256 artCollected = _okpc.artCountForOKPC(tokenId); bool useOffChainRenderer = _okpc.useOffchainMetadata(tokenId); bool isCustomArt = artId == 0; IOKPC.Art memory art = isCustomArt ? _okpc.getPaintArt(tokenId) : _okpc.getGalleryArt(artId); bytes memory artData = abi.encodePacked(art.data1, art.data2); if (artData.length < 56) revert NotEnoughPixelData(); (, IOKPC.Art memory shippedWithArt) = _genesisArtwork.getGenesisArtwork( tokenId ); return Base64.encode( abi.encodePacked( _getMetadataHeader(tokenId, parts, art), useOffChainRenderer ? abi.encodePacked(FALLBACK_URL, toString(tokenId), '/img') : abi.encodePacked( 'data:image/svg+xml;base64,', drawOKPC(clockSpeed, artData, parts) ), '", "attributes": ', _getAttributes( parts, clockSpeed, artCollected, art, shippedWithArt, useOffChainRenderer, isCustomArt ), '}' ) ); } /// @notice Returns the SVG of the specified art in the specified color /// @param art The byte data for the artwork to render /// @param colorIndex The color to use for the art. Accepts values between 0 and 5; function renderArt(bytes memory art, uint256 colorIndex) public view returns (string memory) { // get svg OKPCParts.Color memory color = _parts.getColor(colorIndex); return string( abi.encodePacked( '<svg viewBox="0 0 24 16" xmlns="http://www.w3.org/2000/svg" shape-rendering="crispEdges" height="512" width="512" fill="#', color.dark, '"><rect width="24" height="16" fill="#', color.light, '"/>', drawArt(art), '</svg>' ) ); } /// @notice Gets the proper parts for a given OKPC TokenID function getParts(uint256 tokenId) public view override returns (Parts memory) { if (tokenId < 1 || tokenId > 8192) revert InvalidTokenID(); Parts memory parts; if (tokenId <= 128) { parts.color = _parts.getColor((tokenId - 1) % _parts.NUM_COLORS()); parts.word = _parts.getWord(tokenId - 1); } else { parts.color = _parts.getColor( uint256(keccak256(abi.encodePacked('COLOR', tokenId))) % _parts.NUM_COLORS() ); parts.word = _parts.getWord( uint256(keccak256(abi.encodePacked('WORD', tokenId))) % _parts.NUM_WORDS() ); } parts.headband = _parts.getHeadband( uint256(keccak256(abi.encodePacked('HEADBAND', tokenId))) % _parts.NUM_HEADBANDS() ); parts.rightSpeaker = _parts.getSpeaker( uint256(keccak256(abi.encodePacked('RIGHT SPEAKER', tokenId))) % _parts.NUM_SPEAKERS() ); parts.leftSpeaker = _parts.getSpeaker( uint256(keccak256(abi.encodePacked('LEFT SPEAKER', tokenId))) % _parts.NUM_SPEAKERS() ); return parts; } /// @notice Gets the SVG Base64 encoded for a specified OKPC /// @param tokenId The tokenId of the OKPC to draw function drawOKPC(uint256 tokenId) public view returns (string memory) { uint256 artId = _okpc.activeArtForOKPC(tokenId); uint256 clockSpeed = _okpc.clockSpeed(tokenId); bool isCustomArt = artId == 0; IOKPC.Art memory art = isCustomArt ? _okpc.getPaintArt(artId) : _okpc.getGalleryArt(artId); bytes memory artData = abi.encodePacked(art.data1, art.data2); if (artData.length < 56) revert NotEnoughPixelData(); Parts memory parts = getParts(tokenId); return drawOKPC(clockSpeed, artData, parts); } /// @notice Renders the SVG for a given configuration. /// @param speed The clockspeed of the OKPC to draw /// @param art The artwork to draw on the OKPC's screen /// @param parts The parts of the OKPC (headband, speaker, etc) function drawOKPC( uint256 speed, bytes memory art, Parts memory parts ) public view returns (string memory) { bytes memory svg = abi.encodePacked( abi.encodePacked( '<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" shape-rendering="crispEdges" fill="#', parts.color.dark, '" height="512" width="512"><rect width="32" height="32" fill="#', parts.color.regular, '"/><rect x="4" y="8" width="24" height="16" fill="#', parts.color.light, '"/><rect width="32" height="1" x="0" y="5" /><rect width="32" height="1" x="0" y="26" /><path transform="translate(1,1)" d="', parts.headband.data, '"/><path transform="translate(1, 8)" d="', parts.leftSpeaker.data, '"/><path transform="translate(31, 8) scale(-1,1)" d="', parts.rightSpeaker.data, '"/><g transform="translate(4, 8)" fill-rule="evenodd" clip-rule="evenodd">' ), drawArt(art), '</g>', _drawWord(parts.word), '<g transform="translate(19, 28)">', _drawClockSpeed(speed, parts), '</g></svg>' ); return Base64.encode(svg); } /// @notice Returns the SVG rects for artData. /// @param artData The data to draw as bytes. function drawArt(bytes memory artData) public pure override returns (string memory) { bytes memory rects = DynamicBuffer.allocate(2**16); // Allocate 64KB of memory, we will not use this much, but it's safe. uint256 offset = 8; // render 8 pixels at a time for (uint256 pixelNum = 0; pixelNum < 384; pixelNum += 8) { uint8 workingByte = uint8(artData[offset + (pixelNum / 8)]); uint256 y = uint256(pixelNum / 24); uint256 x = uint256(pixelNum % 24); for (uint256 i; i < 8; i++) { // if the pixel is a 1, draw it if ((workingByte >> (7 - i)) & 1 == 1) { rects.appendSafe( abi.encodePacked( '<rect width="1" height="1" x="', toString(x + i), '" y="', toString(y), '"/>' ) ); } } } return string(rects); } /// @notice Renders the SVG path for an OKPC Word. function _drawWord(string memory word) internal view returns (bytes memory) { bytes memory wordBytes = bytes(word); bytes memory path; for (uint256 i; i < wordBytes.length; i++) { if (wordBytes[i] != 0x0) { path = abi.encodePacked( path, '<path clip-rule="evenodd" fill-rule="evenodd" transform="translate(', toString(2 + i * 4), ',28)" d="', _font.getChar(wordBytes[i]), '"/>' ); } else { break; } } return path; } function _drawClockSpeed(uint256 speed, Parts memory parts) internal pure returns (bytes memory) { bytes memory clockSpeedPixels = DynamicBuffer.allocate(2**16); // Allocate 64KB of memory, we will not use this much, but it's safe. bytes6 color; for (uint256 i; i < 12; i++) { uint256 x = 10 - ((i / 2) * 2); uint256 y = (i % 2 == 0) ? 2 : 0; if (i < speed / 128) color = parts.color.light; else color = parts.color.dark; clockSpeedPixels.appendSafe( abi.encodePacked( '<rect width="1" height="1" x="', toString(x), '" y="', toString(y), '" fill="#', color, '"/>' ) ); } return clockSpeedPixels; } function _getMetadataHeader( uint256 tokenId, Parts memory parts, IOKPC.Art memory art ) internal view returns (bytes memory) { string memory artistENS = ENSNameResolver.getENSName(art.artist); return abi.encodePacked( '{"name": "OKPC #', toString(tokenId), '", "description": "A ', parts.color.name, " OKPC displaying '", bytes16ToString(art.title), "' by [", bytes(artistENS).length > 0 ? artistENS : string(abi.encodePacked('0x', toAsciiString(art.artist))), '](', DESCRIPTION_URL, string(abi.encodePacked('0x', toAsciiString(art.artist))), ')", "image": "' ); } function _getAttributes( Parts memory parts, uint256 speed, uint256 artCollected, IOKPC.Art memory art, IOKPC.Art memory shippedWithArt, bool isFallbackRenderer, bool isCustomArt ) internal view returns (bytes memory) { string memory artistENS = ENSNameResolver.getENSName(art.artist); string memory word = parts.word; // if word is 200% change it to 200 Percent to avoid OpenSea bug if (keccak256(abi.encodePacked(word)) == keccak256('200%')) word = string(abi.encodePacked('200', '\xEF\xBC\x85')); return abi.encodePacked( '[{"trait_type":"Art Collected", "value": ', toString(artCollected), '}, {"trait_type":"Word", "value": "', word, '"}, {"trait_type": "Color", "value": "', parts.color.name, abi.encodePacked( '"}, {"trait_type": "Headband", "value": "', parts.headband.name, '"}, {"trait_type": "Right Speaker", "value": "', parts.rightSpeaker.name, '"}, {"trait_type": "Left Speaker", "value": "', parts.leftSpeaker.name, '"}, {"trait_type": "Clock Speed", "value": "', toString(speed) ), abi.encodePacked( '"}, {"trait_type": "Art", "value": "', bytes16ToString(art.title), '"}, {"trait_type": "Renderer", "value": "', isFallbackRenderer ? 'Off Chain' : 'On Chain', '"}, {"trait_type": "Screen", "value": "', isCustomArt ? 'Custom Art' : 'Gallery Art' ), abi.encodePacked( '"}, {"trait_type": "Artist", "value": "', bytes(artistENS).length > 0 ? artistENS : string(abi.encodePacked('0x', toAsciiString(art.artist))), '"}, {"trait_type": "Shipped With", "value": "', bytes16ToString(shippedWithArt.title), ' by ', bytes(artistENS).length > 0 ? artistENS : string(abi.encodePacked('0x', toAsciiString(art.artist))), '"}]' ) ); } // * UTILITIES * // function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // 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); } function bytes16ToString(bytes16 x) internal pure returns (string memory) { uint256 numChars = 0; for (uint256 i; i < 16; i++) { if (x[i] == bytes1(0)) break; numChars++; } bytes memory result = new bytes(numChars); for (uint256 i; i < numChars; i++) result[i] = x[i]; return string(result); } function toAsciiString(address x) internal pure returns (string memory) { bytes memory s = new bytes(40); for (uint256 i; i < 20; i++) { bytes1 b = bytes1(uint8(uint256(uint160(x)) / (2**(8 * (19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(s); } function char(bytes1 b) internal pure returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF) ) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0; /// @title DynamicBuffer /// @author David Huber (@cxkoda) and Simon Fremaux (@dievardump). See also /// https://raw.githubusercontent.com/dievardump/solidity-dynamic-buffer /// @notice This library is used to allocate a big amount of container memory // which will be subsequently filled without needing to reallocate /// memory. /// @dev First, allocate memory. /// Then use `buffer.appendUnchecked(theBytes)` or `appendSafe()` if /// bounds checking is required. library DynamicBuffer { /// @notice Allocates container space for the DynamicBuffer /// @param capacity The intended max amount of bytes in the buffer /// @return buffer The memory location of the buffer /// @dev Allocates `capacity + 0x60` bytes of space /// The buffer array starts at the first container data position, /// (i.e. `buffer = container + 0x20`) function allocate(uint256 capacity) internal pure returns (bytes memory buffer) { assembly { // Get next-free memory address let container := mload(0x40) // Allocate memory by setting a new next-free address { // Add 2 x 32 bytes in size for the two length fields // Add 32 bytes safety space for 32B chunked copy let size := add(capacity, 0x60) let newNextFree := add(container, size) mstore(0x40, newNextFree) } // Set the correct container length { let length := add(capacity, 0x40) mstore(container, length) } // The buffer starts at idx 1 in the container (0 is length) buffer := add(container, 0x20) // Init content with length 0 mstore(buffer, 0) } return buffer; } /// @notice Appends data to buffer, and update buffer length /// @param buffer the buffer to append the data to /// @param data the data to append /// @dev Does not perform out-of-bound checks (container capacity) /// for efficiency. function appendUnchecked(bytes memory buffer, bytes memory data) internal pure { assembly { let length := mload(data) for { data := add(data, 0x20) let dataEnd := add(data, length) let copyTo := add(buffer, add(mload(buffer), 0x20)) } lt(data, dataEnd) { data := add(data, 0x20) copyTo := add(copyTo, 0x20) } { // Copy 32B chunks from data to buffer. // This may read over data array boundaries and copy invalid // bytes, which doesn't matter in the end since we will // later set the correct buffer length, and have allocated an // additional word to avoid buffer overflow. mstore(copyTo, mload(data)) } // Update buffer length mstore(buffer, add(mload(buffer), length)) } } /// @notice Appends data to buffer, and update buffer length /// @param buffer the buffer to append the data to /// @param data the data to append /// @dev Performs out-of-bound checks and calls `appendUnchecked`. function appendSafe(bytes memory buffer, bytes memory data) internal pure { uint256 capacity; uint256 length; assembly { capacity := sub(mload(sub(buffer, 0x20)), 0x40) length := mload(buffer) } require( length + data.length <= capacity, "DynamicBuffer: Appending out of bounds." ); appendUnchecked(buffer, data); } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.8; interface IOKPC { enum Phase { INIT, EARLY_BIRDS, FRIENDS, PUBLIC } struct Art { address artist; bytes16 title; uint256 data1; uint256 data2; } struct Commission { address artist; uint256 amount; } struct ClockSpeedXP { uint256 savedSpeed; uint256 lastSaveBlock; uint256 transferCount; uint256 artLastChanged; } function getPaintArt(uint256) external view returns (Art memory); function getGalleryArt(uint256) external view returns (Art memory); function activeArtForOKPC(uint256) external view returns (uint256); function useOffchainMetadata(uint256) external view returns (bool); function clockSpeed(uint256) external view returns (uint256); function artCountForOKPC(uint256) external view returns (uint256); } /* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░░░░███░░████████░░███░░████████░░███░░░░░███░░███████░░███░░████████░░███░░░░░ ░░░░░███░░░░░░░███░░███░░░░░░░███░░███░░░░░███░░███░░░░░░███░░███░░░░░░░███░░░░░ ░░░░░████████░░███░░████████░░███░░███████████░░███░░███████░░███░░████████░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ████████████████████████████████████████████████████████████████████████████████ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░░░░░░░░░ ░░░░░░░░░░ ░░░░░███░░ ██████████ ██████████ ░░░░░███░░ ░░░█████░░ ██ ███ ██ ███ ░░░██░░░░░ ░░░░░░░░░░ ███ █████ ██ ███ ██ ░░░░░░░░░░ ░░░░░░░░░░ ███ ███ ██ ███ █████ ██ ░░░░░░░░░░ ░░░░░███░░ ███ █████ ██ █████ ███ ██ ██ ░░░░░███░░ ░░░█████░░ ███ █████ ██ ███ █████ ██ ░░░██░░░░░ ░░░░░░░░░░ ███ ██ █████ ███ █████ ██ ░░░░░░░░░░ ░░░░░░░░░░ ██ ███ ██ ███ ░░░░░░░░░░ ░░░█████░░ ██████████ █████ ██████████ ░░░░░███░░ ░░░░░███░░ ░░░██░░░░░ ░░░░░░░░░░ █████ █████ █████ █████ ░░░░░░░░░░ ░░░░░░░░░░ █████ █████ █████ █████ ██ █████ █████ ░░░░░░░░░░ ░░░█████░░ █████ █████ █████ ░░░░░███░░ ░░░░░███░░ ░░░██░░░░░ ░░░░░░░░░░ ░░░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ████████████████████████████████████████████████████████████████████████████████ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░░░░████████░░████████░░████████░░░░░░░░░░░░░░░██░░░██░░░██░░░██░░░██░░░██░░░░░ ░░░░░███░░░░░░░███░░███░░████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░░░░███░░░░░░░████████░░███░░███░░░░░░░░░░░░░░░██░░░██░░░██░░░██░░░██░░░██░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ */ //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.8; import {IOKPCParts} from './interfaces/IOKPCParts.sol'; import '@0xsequence/sstore2/contracts/SSTORE2.sol'; contract OKPCParts is IOKPCParts { /* --------------------------------- ****** --------------------------------- */ /* -------------------------------------------------------------------------- */ /* CONFIG */ /* -------------------------------------------------------------------------- */ uint256 public constant NUM_COLORS = 6; uint256 public constant NUM_HEADBANDS = 8; uint256 public constant NUM_SPEAKERS = 8; uint256 public constant NUM_WORDS = 128; /* --------------------------------- ****** --------------------------------- */ /* -------------------------------------------------------------------------- */ /* STORAGE */ /* -------------------------------------------------------------------------- */ Color[NUM_COLORS] public colors; Vector[NUM_HEADBANDS] public headbands; Vector[NUM_SPEAKERS] public speakers; bytes4[NUM_WORDS] public words; /* --------------------------------- ****** --------------------------------- */ /* -------------------------------------------------------------------------- */ /* INITIALIZATION */ /* -------------------------------------------------------------------------- */ constructor() { _initColors(); _initHeadbands(); _initSpeakers(); _initWords(); } /* --------------------------------- ****** --------------------------------- */ /* -------------------------------------------------------------------------- */ /* PARTS */ /* -------------------------------------------------------------------------- */ /// @notice Gets the Color by index. Accepts values between 0 and 5. function getColor(uint256 index) public view override returns (Color memory) { if (index > NUM_COLORS - 1) revert IndexOutOfBounds(index, NUM_COLORS - 1); return colors[index]; } /// @notice Gets the Headband by index. Accepts values between 0 and 7. function getHeadband(uint256 index) public view override returns (Vector memory) { if (index > NUM_HEADBANDS - 1) revert IndexOutOfBounds(index, NUM_HEADBANDS - 1); return headbands[index]; } /// @notice Gets the Speaker by index. Accepts values between 0 and 7. function getSpeaker(uint256 index) public view override returns (Vector memory) { if (index > NUM_SPEAKERS - 1) revert IndexOutOfBounds(index, NUM_SPEAKERS - 1); return speakers[index]; } /// @notice Gets the Word by index. Accepts values between 0 and 127. function getWord(uint256 index) public view override returns (string memory) { if (index > NUM_WORDS - 1) revert IndexOutOfBounds(index, NUM_WORDS - 1); return _toString(words[index]); } /* --------------------------------- ****** --------------------------------- */ /* -------------------------------------------------------------------------- */ /* INITIALIZATION */ /* -------------------------------------------------------------------------- */ /// @notice Initializes the stored Colors. function _initColors() internal { // gray colors[0] = Color( bytes6('CCCCCC'), bytes6('838383'), bytes6('4D4D4D'), 'Gray' ); // green colors[1] = Color( bytes6('54F8B5'), bytes6('00DC82'), bytes6('037245'), 'Green' ); // blue colors[2] = Color( bytes6('80B3FF'), bytes6('2E82FF'), bytes6('003D99'), 'Blue' ); // purple colors[3] = Color( bytes6('DF99FF'), bytes6('C13CFF'), bytes6('750DA5'), 'Purple' ); // yellow colors[4] = Color( bytes6('FBDA9D'), bytes6('F8B73E'), bytes6('795106'), 'Yellow' ); // pink colors[5] = Color( bytes6('FF99D8'), bytes6('FF44B7'), bytes6('99005E'), 'Pink' ); } /// @notice Initializes the stored Headbands. function _initHeadbands() internal { headbands[0] = Vector( 'M2 3H1V0H2V2H4V3H2ZM3 0H5H6V3H5V1H3V0ZM11 0H9V1H11V3H12V0H11ZM14 0H13V3H14H16H17V0H16V2H14V0ZM19 0H21V1H19V3H18V0H19ZM27 0H25H24V3H25V1H27V0ZM20 3V2H22V0H23V3H22H20ZM26 2V3H28H29V0H28V2H26ZM8 3H10V2H8V0H7V3H8Z', 'Crest' ); headbands[1] = Vector( 'M11 1H12V0H11V1ZM11 2H10V1H11V2ZM13 2H11V3H13V2ZM14 1H13V2H14V1ZM16 1V0H14V1H16ZM17 2H16V1H17V2ZM19 2V3H17V2H19ZM19 1H20V2H19V1ZM19 1V0H18V1H19ZM0 1H1V2H0V1ZM1 2H2V3H1V2ZM3 1V0H1V1H3ZM4 2V1H3V2H4ZM5 2H4V3H5V2ZM6 1H5V2H6V1ZM8 1V0H6V1H8ZM8 2H9V1H8V2ZM8 2H7V3H8V2ZM24 1H25V2H24V1ZM22 1V0H24V1H22ZM22 2H21V1H22V2ZM22 2H23V3H22V2ZM26 2V3H25V2H26ZM27 1V2H26V1H27ZM29 1H27V0H29V1ZM29 2V1H30V2H29ZM29 2V3H28V2H29Z', 'Ornate' ); headbands[2] = Vector( 'M3 0H1V1H3V2H1V3H3V2H4V3H6V2H4V1H6V0H4V1H3V0ZM27 0H29V1H27V0ZM27 2V1H26V0H24V1H26V2H24V3H26V2H27ZM27 2H29V3H27V2ZM10 0H12V1H10V0ZM10 2V1H9V0H7V1H9V2H7V3H9V2H10ZM10 2H12V3H10V2ZM18 0H20V1H18V0ZM21 1H20V2H18V3H20V2H21V3H23V2H21V1ZM21 1V0H23V1H21ZM16 0H15V1H14V3H15V2H16V0Z', 'Power' ); headbands[3] = Vector( 'M1 3H2H3V2H2V1H4V3H5H7H8V1H10V3H11H14V2V1H16V2V3H19H20V1H22V3H23H25H26V1H28V2H27V3H28H29V0H28H26H25V2H23V0H22H20H19V2H17V1H18V0H12V1H13V2H11V0H10H8H7V2H5V0H4H2H1V3Z', 'Temple' ); headbands[4] = Vector( 'M2 1H1V0H2V1ZM2 2V1H3V2H2ZM2 2V3H1V2H2ZM28 1H29V0H28V1ZM28 2V1H27V2H28ZM28 2H29V3H28V2ZM4 1H5V2H4V3H5V2H6V1H5V0H4V1ZM25 1H26V0H25V1ZM25 2V1H24V2H25ZM25 2H26V3H25V2ZM7 1H8V2H7V3H8V2H9V1H8V0H7V1ZM22 1H23V0H22V1ZM22 2V1H21V2H22ZM22 2H23V3H22V2ZM10 1H11V2H10V3H11V2H12V1H11V0H10V1ZM16 1H14V0H16V1ZM16 2V1H17V2H16ZM14 2H16V3H14V2ZM14 2V1H13V2H14ZM19 1H20V0H19V1ZM19 2V1H18V2H19ZM19 2H20V3H19V2Z', 'Wreath' ); headbands[5] = Vector( 'M1 1H10V0H1V1ZM12 1H13V2H14V3H16V2H17V1H18V0H16V1V2H14V1V0H12V1ZM11 3H1V2H11V3ZM29 1H20V0H29V1ZM19 3H29V2H19V3Z', 'Valiant' ); headbands[6] = Vector( 'M2 1H3V2H2V1ZM2 1H1V2H2V3H3V2H4V1H3V0H2V1ZM6 1H7V2H6V1ZM6 1H5V2H6V3H7V2H8V1H7V0H6V1ZM11 1H10V0H11V1ZM11 2V1H12V2H11ZM10 2H11V3H10V2ZM10 2V1H9V2H10ZM28 1H27V0H28V1ZM28 2V1H29V2H28ZM27 2H28V3H27V2ZM27 2V1H26V2H27ZM24 1H23V0H24V1ZM24 2V1H25V2H24ZM23 2H24V3H23V2ZM23 2V1H22V2H23ZM20 1H19V0H20V1ZM20 2V1H21V2H20ZM19 2H20V3H19V2ZM19 2V1H18V2H19ZM16 2H14V1H16V2ZM16 2V3H17V2H16ZM16 1V0H17V1H16ZM14 1H13V0H14V1ZM14 2V3H13V2H14Z', 'Tainia' ); headbands[7] = Vector( 'M10 0H14V1H13V2H17V1H16V0H20V1H18V2H19V3H11V2H12V1H10V0ZM3 2H5V3H1V2H2V1H1V0H9V1H8V2H10V3H6V2H7V1H3V2ZM25 2H27V1H23V2H24V3H20V2H22V1H21V0H29V1H28V2H29V3H25V2Z', 'Colossus' ); } /// @notice Initializes the stored Speakers. function _initSpeakers() internal { speakers[0] = Vector( 'M1 1H0V2H1V3H2V2H1V1ZM1 5H0V6H1V7H2V6H1V5ZM0 9H1V10H0V9ZM1 10H2V11H1V10ZM1 13H0V14H1V15H2V14H1V13Z', 'Piezo' ); speakers[1] = Vector( 'M1 1L1 0H0V1H1ZM1 2H2V1H1V2ZM1 2H0V3H1V2ZM1 10L1 11H0V10H1ZM1 9H2V10H1L1 9ZM1 9H0V8H1L1 9ZM1 4L1 5H0V6H1L1 7H2L2 6H1L1 5H2L2 4H1ZM1 13L1 12H2L2 13H1ZM1 14L1 13H0V14H1ZM1 14H2L2 15H1L1 14Z', 'Ambient' ); speakers[2] = Vector( 'M0 2H1V3H2L2 1H1L1 0H0V2ZM1 5H2L2 7H1V6H0V4H1L1 5ZM2 14H1L1 15H0V13H1V12H2L2 14ZM2 10L2 8H1V9H0V11H1L1 10H2Z', 'Hyper' ); speakers[3] = Vector( 'M1 1L1 0H0V1H1ZM1 1H2V2V3H1H0V2H1V1ZM1 5L1 4H2V5H1ZM1 5L1 6H2V7H1H0V6V5H1ZM1 13H0V12H1H2V13V14H1L1 13ZM1 14L1 15H0V14H1ZM2 9V8H1H0V9V10H1V11H2V10H1V9H2Z', 'Crystal' ); speakers[4] = Vector( 'M2 0H1V1H0V2H1V3H2V0ZM2 5H1V4H0V7H1V6H2V5ZM2 9H1V8H0V11H1V10H2V9ZM0 13H1V12H2V15H1V14H0V13Z', 'Taser' ); speakers[5] = Vector( 'M2 0V1V2V3H0V2H1V1V0H2ZM0 4V5V6V7H2V6H1L1 5H2V4H0ZM2 10V11H0V10H1V9H0V8H2V9V10ZM0 12V13H1V14V15H2V14L2 13V12H0Z', 'Buster' ); speakers[6] = Vector( 'M0 0V1L2 1V0H0ZM1 3V2H2V3H1ZM2 5V4H0V5H2ZM1 11V10H2V11H1ZM2 13V12H0V13H2ZM2 15V14H1V15H2ZM2 7V6H1V7H2ZM0 8V9H2V8H0Z', 'Tower' ); speakers[7] = Vector( 'M2 1V2V3H0V2L1 2V1H2ZM1 11V10H0V9H2L2 10V11H1ZM2 14V13H0V14H1V15H2V14ZM1 5V6H0V7H2L2 6V5H1Z', 'Blaster' ); } /// @notice Initializes the stored Words. function _initWords() internal { words = [ bytes4('WAIT'), 'OK', 'INFO', 'HELP', 'WARN', 'ERR', 'OOF', 'WHAT', 'RARE', '200%', 'GATO', 'ABRA', 'POOF', 'FUN', 'BYTE', 'POLY', 'FANG', 'PAIN', 'BOOT', 'DRAW', 'MINT', 'WORM', 'PUP', 'PLUS', 'DOC', 'QUIT', 'BEAT', 'MIDI', 'UPUP', 'HUSH', 'ACK', 'MOON', 'GHST', 'UFO', 'SEE', 'MON', 'TRIP', 'NICE', 'YUP', 'EXIT', 'CUTE', 'OHNO', 'GROW', 'DEAD', 'OPEN', 'THEM', 'DRIP', 'ESC', '404', 'PSA', 'BGS', 'BOMB', 'NOUN', 'SKY', 'SK8', 'CATS', 'CT', 'GAME', 'DAO', 'BRAP', 'LOOK', 'MYTH', 'ZERO', 'QI', '5000', 'LORD', 'DUEL', 'SWRD', 'MEME', 'SAD', 'ORB', 'LIFE', 'PRTY', 'DEF', 'AIR', 'ISLE', 'ROSE', 'ANON', 'OKOK', 'MEOW', 'KING', 'WISE', 'ROZE', 'NOBU', 'DAMN', 'HUNT', 'BETA', 'FORT', 'SWIM', 'HALO', 'UP', 'YUM', 'SNAP', 'APES', 'BIRD', 'NOON', 'VIBE', 'MAKE', 'CRWN', 'PLAY', 'JOY', 'FREN', 'DING', 'GAZE', 'HACK', 'CRY', 'SEER', 'OWL', 'LOUD', 'RISE', 'LOVE', 'SKRT', 'QTPI', 'WAND', 'REKT', 'BEAR', 'CODA', 'ILY', 'SNKE', 'FLY', 'ZKP', 'LUSH', 'SUP', 'GOWN', 'BAG', 'BALM', 'LIVE', 'LVL' ]; } /* --------------------------------- ****** --------------------------------- */ /* -------------------------------------------------------------------------- */ /* HELPERS */ /* -------------------------------------------------------------------------- */ /// @notice Convert a bytes4 to a string. function _toString(bytes4 b) private pure returns (string memory) { uint256 numChars = 0; for (uint256 i; i < 4; i++) { if (b[i] == bytes1(0)) break; numChars++; } bytes memory result = new bytes(numChars); for (uint256 i; i < numChars; i++) result[i] = b[i]; return string(abi.encodePacked(result)); } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.7; interface IOKPCFont { error CharacterNotFound(); error NotSingleCharacter(); function getChar(string memory char) external view returns (string memory); function getChar(bytes1) external view returns (string memory); } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.8; import {IOKPC} from './IOKPC.sol'; import {IOKPCParts} from './IOKPCParts.sol'; interface IOKPCMetadata { error InvalidTokenID(); error NotEnoughPixelData(); struct Parts { IOKPCParts.Vector headband; IOKPCParts.Vector rightSpeaker; IOKPCParts.Vector leftSpeaker; IOKPCParts.Color color; string word; } function tokenURI(uint256 tokenId) external view returns (string memory); function drawOKPC(uint256 tokenId) external view returns (string memory); function drawOKPC( uint256 speed, bytes memory art, Parts memory parts ) external view returns (string memory); function renderArt(bytes memory art, uint256 colorIndex) external view returns (string memory); function getParts(uint256 tokenId) external view returns (Parts memory); function drawArt(bytes memory artData) external pure returns (string memory); } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.8; import {IOKPC} from './IOKPC.sol'; interface IOKPCGenesisArtwork { function getGenesisArtwork(uint256) external view returns (uint256, IOKPC.Art memory); } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; interface IReverseRegistrar { function node(address addr) external view returns (bytes32); } interface IReverseResolver { function name(bytes32 node) external view returns (string memory); } contract ENSNameResolver { IReverseRegistrar constant registrar = IReverseRegistrar(0x084b1c3C81545d370f3634392De611CaaBFf8148); IReverseResolver constant resolver = IReverseResolver(0xA2C122BE93b0074270ebeE7f6b7292C7deB45047); function getENSName(address addr) public view returns (string memory) { try resolver.name(registrar.node(addr)) { return resolver.name(registrar.node(addr)); } catch { return ''; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.7; interface IOKPCParts { // errors error IndexOutOfBounds(uint256 index, uint256 maxIndex); // structures struct Color { bytes6 light; bytes6 regular; bytes6 dark; string name; } struct Vector { string data; string name; } // functions function getColor(uint256 index) external view returns (Color memory); function getHeadband(uint256 index) external view returns (Vector memory); function getSpeaker(uint256 index) external view returns (Vector memory); function getWord(uint256 index) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./utils/Bytecode.sol"; /** @title A key-value storage with auto-generated keys for storing chunks of data with a lower write & read cost. @author Agustin Aguilar <[email protected]> Readme: https://github.com/0xsequence/sstore2#readme */ library SSTORE2 { error WriteError(); /** @notice Stores `_data` and returns `pointer` as key for later retrieval @dev The pointer is a contract address with `_data` as code @param _data to be written @return pointer Pointer to the written `_data` */ function write(bytes memory _data) internal returns (address pointer) { // Append 00 to _data so contract can't be called // Build init code bytes memory code = Bytecode.creationCodeFor( abi.encodePacked( hex'00', _data ) ); // Deploy contract using create assembly { pointer := create(0, add(code, 32), mload(code)) } // Address MUST be non-zero if (pointer == address(0)) revert WriteError(); } /** @notice Reads the contents of the `_pointer` code as data, skips the first byte @dev The function is intended for reading pointers generated by `write` @param _pointer to be read @return data read from `_pointer` contract */ function read(address _pointer) internal view returns (bytes memory) { return Bytecode.codeAt(_pointer, 1, type(uint256).max); } /** @notice Reads the contents of the `_pointer` code as data, skips the first byte @dev The function is intended for reading pointers generated by `write` @param _pointer to be read @param _start number of bytes to skip @return data read from `_pointer` contract */ function read(address _pointer, uint256 _start) internal view returns (bytes memory) { return Bytecode.codeAt(_pointer, _start + 1, type(uint256).max); } /** @notice Reads the contents of the `_pointer` code as data, skips the first byte @dev The function is intended for reading pointers generated by `write` @param _pointer to be read @param _start number of bytes to skip @param _end index before which to end extraction @return data read from `_pointer` contract */ function read(address _pointer, uint256 _start, uint256 _end) internal view returns (bytes memory) { return Bytecode.codeAt(_pointer, _start + 1, _end + 1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library Bytecode { error InvalidCodeAtRange(uint256 _size, uint256 _start, uint256 _end); /** @notice Generate a creation code that results on a contract with `_code` as bytecode @param _code The returning value of the resulting `creationCode` @return creationCode (constructor) for new contract */ function creationCodeFor(bytes memory _code) internal pure returns (bytes memory) { /* 0x00 0x63 0x63XXXXXX PUSH4 _code.length size 0x01 0x80 0x80 DUP1 size size 0x02 0x60 0x600e PUSH1 14 14 size size 0x03 0x60 0x6000 PUSH1 00 0 14 size size 0x04 0x39 0x39 CODECOPY size 0x05 0x60 0x6000 PUSH1 00 0 size 0x06 0xf3 0xf3 RETURN <CODE> */ return abi.encodePacked( hex"63", uint32(_code.length), hex"80_60_0E_60_00_39_60_00_F3", _code ); } /** @notice Returns the size of the code on a given address @param _addr Address that may or may not contain code @return size of the code on the given `_addr` */ function codeSize(address _addr) internal view returns (uint256 size) { assembly { size := extcodesize(_addr) } } /** @notice Returns the code of a given address @dev It will fail if `_end < _start` @param _addr Address that may or may not contain code @param _start number of bytes of code to skip on read @param _end index before which to end extraction @return oCode read from `_addr` deployed bytecode Forked from: https://gist.github.com/KardanovIR/fe98661df9338c842b4a30306d507fbd */ function codeAt(address _addr, uint256 _start, uint256 _end) internal view returns (bytes memory oCode) { uint256 csize = codeSize(_addr); if (csize == 0) return bytes(""); if (_start > csize) return bytes(""); if (_end < _start) revert InvalidCodeAtRange(csize, _start, _end); unchecked { uint256 reqSize = _end - _start; uint256 maxSize = csize - _start; uint256 size = maxSize < reqSize ? maxSize : reqSize; assembly { // allocate output byte array - this could also be done without assembly // by using o_code = new bytes(size) oCode := mload(0x40) // new "memory end" including padding mstore(0x40, add(oCode, and(add(add(size, 0x20), 0x1f), not(0x1f)))) // store length in memory mstore(oCode, size) // actually retrieve the code, this needs assembly extcodecopy(_addr, add(oCode, 0x20), _start, size) } } } }
-------------------------------------------------------------------------- / HELPERS / -------------------------------------------------------------------------- / Convert a bytes4 to a string.
function _toString(bytes4 b) private pure returns (string memory) { uint256 numChars = 0; for (uint256 i; i < 4; i++) { if (b[i] == bytes1(0)) break; numChars++; } bytes memory result = new bytes(numChars); for (uint256 i; i < numChars; i++) result[i] = b[i]; return string(abi.encodePacked(result)); }
595,519
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "../interfaces/IPair.sol"; import "../interfaces/IEnchant.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/ISummoner.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract SoulAura is Ownable { ISummoner summoner = ISummoner(0xce6ccbB1EdAD497B4d53d829DF491aF70065AB5B); ISoulSwapPair pair = ISoulSwapPair(0xa2527Af9DABf3E3B4979d7E0493b5e2C6e63dC57); // SOUL-FTM IEnchant enchant = IEnchant(0x6a1a8368D607c7a808F7BbA4F7aEd1D9EbDE147a); IERC20 soul = IERC20(0xe2fb177009FF39F52C0134E8007FA0e4BaAcBd07); IERC20 seance = IERC20(0x124B06C5ce47De7A6e9EFDA71a946717130079E6); function name() public pure returns (string memory) { return "SoulAura"; } function symbol() public pure returns (string memory) { return "AURA"; } function decimals() public pure returns (uint8) { return 18; } // transfers ownership to the DAO. constructor() { transferOwnership(0x1C63C726926197BD3CB75d86bCFB1DaeBcD87250); } // gets the total voting power = twice the reserves in the LP + enchanted seance. function totalSupply() public view returns (uint) { // SOUL reserves in the SOUL-FTM LP contract. (, uint lp_totalSoul, ) = pair.getReserves(); // total SEANCE staked in ENCHANT. uint enchant_totalSeance = seance.balanceOf(address(enchant)); return lp_totalSoul * 2 + enchant_totalSeance; } function balanceOf(address member) public view returns (uint) { ////////////////////////// // LP BALANCE // ////////////////////////// uint lp_total = pair.totalSupply(); uint lp_totalSoul = soul.balanceOf(address(pair)); // wallet balance. uint lp_walletBalance = pair.balanceOf(member); // staked balance (uint lp_stakedBalance, ) = summoner.userInfo(1, member); // lp balance [user] uint lp_balance = lp_walletBalance + lp_stakedBalance; // LP voting power is 2X the members' SOUL share in the pool. uint lp_power = lp_totalSoul * lp_balance / lp_total * 2; ////////////////////////// // ENCHANT BALANCE // ////////////////////////// uint enchant_total = enchant.totalSupply(); uint enchant_balance = enchant.balanceOf(member); uint enchant_totalSeance = seance.balanceOf(address(enchant)); // enchanted voting power is the members' enchanted SEANCE share. uint enchanted_power = enchant_totalSeance * enchant_balance / enchant_total; ////////////////////////// // SOUL POWER // ////////////////////////// // soul power is the members' SOUL balance. uint soul_power = soul.balanceOf(member); return lp_power + enchanted_power + soul_power; } // gets: member's pooled power function pooledPower(address member) public view returns (uint raw, uint formatted) { uint lp_total = pair.totalSupply(); uint lp_totalSoul = soul.balanceOf(address(pair)); // wallet balance. uint lp_walletBalance = pair.balanceOf(member); // staked balance (uint lp_stakedBalance, ) = summoner.userInfo(1, member); // lp balance [user] uint lp_balance = lp_walletBalance + lp_stakedBalance; // LP voting power is 2X the members' SOUL share in the lp pool. uint lp_power = lp_totalSoul * lp_balance / lp_total * 2; return (lp_power, fromWei(lp_power)); } // gets: member's enchanted power function enchantedPower(address member) public view returns (uint raw, uint formatted) { uint enchant_total = enchant.totalSupply(); uint enchant_balance = enchant.balanceOf(member); uint enchant_totalSeance = seance.balanceOf(address(enchant)); // enchanted voting power is the members' enchanted SEANCE share. uint enchanted_power = enchant_totalSeance * enchant_balance / enchant_total; return (enchanted_power, fromWei(enchanted_power)); } // gets: member's SOUL power function soulPower(address member) public view returns (uint raw, uint formatted) { // soul power is the members' SOUL balance. uint soul_power = soul.balanceOf(member); return (soul_power, fromWei(soul_power)); } // gets: sender's pooled power function pooledPower() public view returns (uint raw, uint formatted) { uint lp_total = pair.totalSupply(); uint lp_totalSoul = soul.balanceOf(address(pair)); // wallet balance. uint lp_walletBalance = pair.balanceOf(msg.sender); // staked balance (uint lp_stakedBalance, ) = summoner.userInfo(1, msg.sender); // lp balance [user] uint lp_balance = lp_walletBalance + lp_stakedBalance; // LP voting power is 2X the sender's SOUL share in the lp pool. uint lp_power = lp_totalSoul * lp_balance / lp_total * 2; return (lp_power, fromWei(lp_power)); } // gets: sender's enchanted power function enchantedPower() public view returns (uint raw, uint formatted) { uint enchant_total = enchant.totalSupply(); uint enchant_balance = enchant.balanceOf(msg.sender); uint enchant_totalSeance = seance.balanceOf(address(enchant)); // enchanted voting power is the sender's enchanted SEANCE share. uint enchanted_power = enchant_totalSeance * enchant_balance / enchant_total; return (enchanted_power, fromWei(enchanted_power)); } // gets: sender's SOUL power function soulPower() public view returns (uint raw, uint formatted) { // soul power is the sender's SOUL balance. uint soul_power = soul.balanceOf(msg.sender); return (soul_power, fromWei(soul_power)); } // disables ERC20 functionality. function allowance(address, address) public pure returns (uint) { return 0; } function transfer(address, uint) public pure returns (bool) { return false; } function approve(address, uint) public pure returns (bool) { return false; } function transferFrom(address, address, uint) public pure returns (bool) { return false; } // conversion helper functions function toWei(uint intNum) public pure returns (uint bigInt) { return intNum * 10**18; } function fromWei(uint bigInt) public pure returns (uint intNum) { return bigInt / 10**18; } }
gets: member's enchanted power enchanted voting power is the members' enchanted SEANCE share.
function enchantedPower(address member) public view returns (uint raw, uint formatted) { uint enchant_total = enchant.totalSupply(); uint enchant_balance = enchant.balanceOf(member); uint enchant_totalSeance = seance.balanceOf(address(enchant)); uint enchanted_power = enchant_totalSeance * enchant_balance / enchant_total; return (enchanted_power, fromWei(enchanted_power)); }
14,094,046
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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; /** * @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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; /* solhint-disable func-name-mixedcase */ import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; interface ISwapManager { event OracleCreated(address indexed _sender, address indexed _newOracle, uint256 _period); function N_DEX() external view returns (uint256); function ROUTERS(uint256 i) external view returns (IUniswapV2Router02); function bestOutputFixedInput( address _from, address _to, uint256 _amountIn ) external view returns ( address[] memory path, uint256 amountOut, uint256 rIdx ); function bestPathFixedInput( address _from, address _to, uint256 _amountIn, uint256 _i ) external view returns (address[] memory path, uint256 amountOut); function bestInputFixedOutput( address _from, address _to, uint256 _amountOut ) external view returns ( address[] memory path, uint256 amountIn, uint256 rIdx ); function bestPathFixedOutput( address _from, address _to, uint256 _amountOut, uint256 _i ) external view returns (address[] memory path, uint256 amountIn); function safeGetAmountsOut( uint256 _amountIn, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function unsafeGetAmountsOut( uint256 _amountIn, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function safeGetAmountsIn( uint256 _amountOut, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function unsafeGetAmountsIn( uint256 _amountOut, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function comparePathsFixedInput( address[] memory pathA, address[] memory pathB, uint256 _amountIn, uint256 _i ) external view returns (address[] memory path, uint256 amountOut); function comparePathsFixedOutput( address[] memory pathA, address[] memory pathB, uint256 _amountOut, uint256 _i ) external view returns (address[] memory path, uint256 amountIn); function ours(address a) external view returns (bool); function oracleCount() external view returns (uint256); function oracleAt(uint256 idx) external view returns (address); function getOracle( address _tokenA, address _tokenB, uint256 _period, uint256 _i ) external view returns (address); function createOrUpdateOracle( address _tokenA, address _tokenB, uint256 _period, uint256 _i ) external returns (address oracleAddr); function consultForFree( address _from, address _to, uint256 _amountIn, uint256 _period, uint256 _i ) external view returns (uint256 amountOut, uint256 lastUpdatedAt); /// get the data we want and pay the gas to update function consult( address _from, address _to, uint256 _amountIn, uint256 _period, uint256 _i ) external returns ( uint256 amountOut, uint256 lastUpdatedAt, bool updated ); function updateOracles() external returns (uint256 updated, uint256 expected); function updateOracles(address[] memory _oracleAddrs) external returns (uint256 updated, uint256 expected); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IConvex { function poolInfo(uint256) external view returns ( address, address, address, address, address, bool ); // deposit lp tokens and stake function deposit( uint256 _pid, uint256 _amount, bool _stake ) external returns (bool); // deposit all lp tokens and stake function depositAll(uint256 _pid, bool _stake) external returns (bool); // withdraw lp tokens function withdraw(uint256 _pid, uint256 _amount) external returns (bool); // withdraw all lp tokens function withdrawAll(uint256 _pid) external returns (bool); // claim crv + extra rewards function earmarkRewards(uint256 _pid) external returns (bool); // claim rewards on stash (msg.sender == stash) function claimRewards(uint256 _pid, address _gauge) external returns (bool); // delegate address votes on dao (needs to be voteDelegate) function vote( uint256 _voteId, address _votingAddress, bool _support ) external returns (bool); function voteGaugeWeight(address[] calldata _gauge, uint256[] calldata _weight) external returns (bool); } interface Rewards { function pid() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function earned(address account) external view returns (uint256); function extraRewardsLength() external view returns (uint256); function extraRewards(uint256) external view returns (address); function rewardPerToken() external view returns (uint256); function rewardPerTokenStored() external view returns (uint256); function rewardRate() external view returns (uint256); function rewardToken() external view returns (address); function rewards(address) external view returns (uint256); function userRewardPerTokenPaid(address) external view returns (uint256); function stakingToken() external view returns (address); function stake(uint256) external returns (bool); function stakeAll() external returns (bool); function stakeFor(address, uint256) external returns (bool); function withdraw(uint256 amount, bool claim) external returns (bool); function withdrawAll(bool claim) external returns (bool); function withdrawAndUnwrap(uint256 amount, bool claim) external returns (bool); function withdrawAllAndUnwrap(bool claim) external; function getReward() external returns (bool); function getReward(address _account, bool _claimExtras) external returns (bool); function donate(uint256 _amount) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IConvexToken { function maxSupply() external view returns (uint256); function totalSupply() external view returns (uint256); function reductionPerCliff() external view returns (uint256); } // SPDX-License-Identifier: MIT /* solhint-disable */ pragma solidity 0.8.3; interface IDepositZap4x { function calc_token_amount( address _pool, uint256[4] memory _amounts, bool is_deposit ) external view returns (uint256); function add_liquidity( address _pool, uint256[4] memory _amounts, uint256 _min_mint_amount ) external; function remove_liquidity( address _pool, uint256 _amount, uint256[4] memory _min_amounts ) external; function remove_liquidity_one_coin( address _pool, uint256 _token_amount, int128 i, uint256 _min_amount ) external; function calc_withdraw_one_coin( address _pool, uint256 _token_amount, int128 i ) external view returns (uint256); } // SPDX-License-Identifier: MIT /* solhint-disable */ pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // Not a complete interface, but should have what we need interface ILiquidityGaugeV2 is IERC20 { function deposit(uint256 _value) external; function deposit(uint256 _value, address addr) external; function withdraw(uint256 _value) external; function claim_rewards(address addr) external; function claimable_tokens(address addr) external returns (uint256); function claimable_reward(address, address) external returns (uint256); function integrate_fraction(address addr) external view returns (uint256); function user_checkpoint(address addr) external returns (bool); function reward_integral(address) external view returns (uint256); function reward_integral_for(address, address) external view returns (uint256); function lp_token() external view returns (address); function reward_count() external view returns (uint256); function reward_tokens(uint256 _i) external view returns (address); } interface ILiquidityGaugeV3 is ILiquidityGaugeV2 { function claimable_reward(address addr, address token) external view override returns (uint256); } /* solhint-enable */ // SPDX-License-Identifier: MIT /* solhint-disable func-name-mixedcase*/ pragma solidity 0.8.3; interface IMetapoolFactory { function get_underlying_coins(address _pool) external view returns (address[8] memory _coins); function get_underlying_decimals(address _pool) external view returns (uint256[8] memory _decimals); } // SPDX-License-Identifier: MIT /* solhint-disable */ pragma solidity 0.8.3; // Not a complete interface, but should have what we need interface IStableSwap { function coins(uint256 i) external view returns (address); function fee() external view returns (uint256); // fee * 1e10 function lp_token() external view returns (address); function A() external view returns (uint256); function A_precise() external view returns (uint256); function balances(uint256 i) external view returns (uint256); function get_virtual_price() external view returns (uint256); function get_dy( int128 i, int128 j, uint256 dx ) external view returns (uint256); function get_dy_underlying( int128 i, int128 j, uint256 dx ) external view returns (uint256); function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external returns (uint256); function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256); function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 _min_amount ) external; } interface IStableSwapV2 { function coins(int128 i) external view returns (address); } interface IStableSwapUnderlying is IStableSwap { function underlying_coins(uint256 i) external view returns (address); function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 _min_amount, bool _use_underlying ) external; } interface IStableSwap2x is IStableSwap { function calc_token_amount(uint256[2] memory _amounts, bool is_deposit) external view returns (uint256); function add_liquidity(uint256[2] memory _amounts, uint256 _min_mint_amount) external; function remove_liquidity(uint256 _amount, uint256[2] memory _min_amounts) external; function remove_liquidity_imbalance(uint256[2] memory _amounts, uint256 _max_burn_amount) external returns (uint256); } interface IStableSwap3x is IStableSwap { function calc_token_amount(uint256[3] memory _amounts, bool is_deposit) external view returns (uint256); function add_liquidity(uint256[3] memory _amounts, uint256 _min_mint_amount) external; function remove_liquidity(uint256 _amount, uint256[3] memory _min_amounts) external; function remove_liquidity_imbalance(uint256[3] memory _amounts, uint256 _max_burn_amount) external returns (uint256); } interface IStableSwap4x is IStableSwap { function calc_token_amount(uint256[4] memory _amounts, bool is_deposit) external view returns (uint256); function add_liquidity(uint256[4] memory _amounts, uint256 _min_mint_amount) external; function remove_liquidity(uint256 _amount, uint256[4] memory _min_amounts) external; function remove_liquidity_imbalance(uint256[4] memory _amounts, uint256 _max_burn_amount) external returns (uint256); } interface IStableSwap2xUnderlying is IStableSwap2x, IStableSwapUnderlying { function add_liquidity( uint256[2] calldata amounts, uint256 min_mint_amount, bool use_underlying ) external; function remove_liquidity_imbalance( uint256[2] calldata amounts, uint256 max_burn_amount, bool use_underlying ) external; function remove_liquidity( uint256 amount, uint256[2] calldata min_amounts, bool use_underlying ) external; } interface IStableSwap3xUnderlying is IStableSwap3x, IStableSwapUnderlying { function add_liquidity( uint256[3] calldata amounts, uint256 min_mint_amount, bool use_underlying ) external; function remove_liquidity_imbalance( uint256[3] calldata amounts, uint256 max_burn_amount, bool use_underlying ) external; function remove_liquidity( uint256 amount, uint256[3] calldata min_amounts, bool use_underlying ) external; } interface IStableSwap4xUnderlying is IStableSwap4x, IStableSwapUnderlying { function add_liquidity( uint256[4] calldata amounts, uint256 min_mint_amount, bool use_underlying ) external; function remove_liquidity_imbalance( uint256[4] calldata amounts, uint256 max_burn_amount, bool use_underlying ) external; function remove_liquidity( uint256 amount, uint256[4] calldata min_amounts, bool use_underlying ) external; } /* solhint-enable */ // SPDX-License-Identifier: MIT /* solhint-disable */ pragma solidity 0.8.3; // Not a complete interface, but should have what we need interface ITokenMinter { function minted(address arg0, address arg1) external view returns (uint256); function mint(address gauge_addr) external; } /* solhint-enable */ // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IStrategy { function rebalance() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function feeCollector() external view returns (address); function isReservedToken(address _token) external view returns (bool); function keepers() external view returns (address[] memory); function migrate(address _newStrategy) external; function token() external view returns (address); function totalValue() external view returns (uint256); function totalValueCurrent() external returns (uint256); function pool() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IVesperPool is IERC20 { function deposit() external payable; function deposit(uint256 _share) external; function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool); function excessDebt(address _strategy) external view returns (uint256); function permit( address, address, uint256, uint256, uint8, bytes32, bytes32 ) external; function poolRewards() external returns (address); function reportEarning( uint256 _profit, uint256 _loss, uint256 _payback ) external; function reportLoss(uint256 _loss) external; function resetApproval() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function withdrawETH(uint256 _amount) external; function whitelistedWithdraw(uint256 _amount) external; function governor() external view returns (address); function keepers() external view returns (address[] memory); function isKeeper(address _address) external view returns (bool); function maintainers() external view returns (address[] memory); function isMaintainer(address _address) external view returns (bool); function feeCollector() external view returns (address); function pricePerShare() external view returns (uint256); function strategy(address _strategy) external view returns ( bool _active, uint256 _interestFee, uint256 _debtRate, uint256 _lastRebalance, uint256 _totalDebt, uint256 _totalLoss, uint256 _totalProfit, uint256 _debtRatio ); function stopEverything() external view returns (bool); function token() external view returns (IERC20); function tokensHere() external view returns (uint256); function totalDebtOf(address _strategy) external view returns (uint256); function totalValue() external view returns (uint256); function withdrawFee() external view returns (uint256); // Function to get pricePerShare from V2 pools function getPricePerShare() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "../dependencies/openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "../interfaces/bloq/ISwapManager.sol"; import "../interfaces/vesper/IStrategy.sol"; import "../interfaces/vesper/IVesperPool.sol"; abstract contract Strategy is IStrategy, Context { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint256 internal constant MAX_UINT_VALUE = type(uint256).max; // solhint-disable-next-line var-name-mixedcase address internal WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IERC20 public immutable collateralToken; address public receiptToken; address public immutable override pool; address public override feeCollector; ISwapManager public swapManager; uint256 public oraclePeriod = 3600; // 1h uint256 public oracleRouterIdx = 0; // Uniswap V2 uint256 public swapSlippage = 10000; // 100% Don't use oracles by default EnumerableSet.AddressSet private _keepers; event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector); event UpdatedSwapManager(address indexed previousSwapManager, address indexed newSwapManager); event UpdatedSwapSlippage(uint256 oldSwapSlippage, uint256 newSwapSlippage); event UpdatedOracleConfig(uint256 oldPeriod, uint256 newPeriod, uint256 oldRouterIdx, uint256 newRouterIdx); constructor( address _pool, address _swapManager, address _receiptToken ) { require(_pool != address(0), "pool-address-is-zero"); require(_swapManager != address(0), "sm-address-is-zero"); swapManager = ISwapManager(_swapManager); pool = _pool; collateralToken = IVesperPool(_pool).token(); receiptToken = _receiptToken; require(_keepers.add(_msgSender()), "add-keeper-failed"); } modifier onlyGovernor { require(_msgSender() == IVesperPool(pool).governor(), "caller-is-not-the-governor"); _; } modifier onlyKeeper() { require(_keepers.contains(_msgSender()), "caller-is-not-a-keeper"); _; } modifier onlyPool() { require(_msgSender() == pool, "caller-is-not-vesper-pool"); _; } /** * @notice Add given address in keepers list. * @param _keeperAddress keeper address to add. */ function addKeeper(address _keeperAddress) external onlyGovernor { require(_keepers.add(_keeperAddress), "add-keeper-failed"); } /// @notice Return list of keepers function keepers() external view override returns (address[] memory) { return _keepers.values(); } /** * @notice Migrate all asset and vault ownership,if any, to new strategy * @dev _beforeMigration hook can be implemented in child strategy to do extra steps. * @param _newStrategy Address of new strategy */ function migrate(address _newStrategy) external virtual override onlyPool { require(_newStrategy != address(0), "new-strategy-address-is-zero"); require(IStrategy(_newStrategy).pool() == pool, "not-valid-new-strategy"); _beforeMigration(_newStrategy); IERC20(receiptToken).safeTransfer(_newStrategy, IERC20(receiptToken).balanceOf(address(this))); collateralToken.safeTransfer(_newStrategy, collateralToken.balanceOf(address(this))); } /** * @notice Remove given address from keepers list. * @param _keeperAddress keeper address to remove. */ function removeKeeper(address _keeperAddress) external onlyGovernor { require(_keepers.remove(_keeperAddress), "remove-keeper-failed"); } /** * @notice Update fee collector * @param _feeCollector fee collector address */ function updateFeeCollector(address _feeCollector) external onlyGovernor { require(_feeCollector != address(0), "fee-collector-address-is-zero"); require(_feeCollector != feeCollector, "fee-collector-is-same"); emit UpdatedFeeCollector(feeCollector, _feeCollector); feeCollector = _feeCollector; } /** * @notice Update swap manager address * @param _swapManager swap manager address */ function updateSwapManager(address _swapManager) external onlyGovernor { require(_swapManager != address(0), "sm-address-is-zero"); require(_swapManager != address(swapManager), "sm-is-same"); emit UpdatedSwapManager(address(swapManager), _swapManager); swapManager = ISwapManager(_swapManager); } function updateSwapSlippage(uint256 _newSwapSlippage) external onlyGovernor { require(_newSwapSlippage <= 10000, "invalid-slippage-value"); emit UpdatedSwapSlippage(swapSlippage, _newSwapSlippage); swapSlippage = _newSwapSlippage; } function updateOracleConfig(uint256 _newPeriod, uint256 _newRouterIdx) external onlyGovernor { require(_newRouterIdx < swapManager.N_DEX(), "invalid-router-index"); if (_newPeriod == 0) _newPeriod = oraclePeriod; require(_newPeriod > 59, "invalid-oracle-period"); emit UpdatedOracleConfig(oraclePeriod, _newPeriod, oracleRouterIdx, _newRouterIdx); oraclePeriod = _newPeriod; oracleRouterIdx = _newRouterIdx; } /// @dev Approve all required tokens function approveToken() external onlyKeeper { _approveToken(0); _approveToken(MAX_UINT_VALUE); } function setupOracles() external onlyKeeper { _setupOracles(); } /** * @dev Withdraw collateral token from lending pool. * @param _amount Amount of collateral token */ function withdraw(uint256 _amount) external override onlyPool { _withdraw(_amount); } /** * @dev Rebalance profit, loss and investment of this strategy */ function rebalance() external virtual override onlyKeeper { (uint256 _profit, uint256 _loss, uint256 _payback) = _generateReport(); IVesperPool(pool).reportEarning(_profit, _loss, _payback); _reinvest(); } /** * @dev sweep given token to feeCollector of strategy * @param _fromToken token address to sweep */ function sweepERC20(address _fromToken) external override onlyKeeper { require(feeCollector != address(0), "fee-collector-not-set"); require(_fromToken != address(collateralToken), "not-allowed-to-sweep-collateral"); require(!isReservedToken(_fromToken), "not-allowed-to-sweep"); if (_fromToken == ETH) { Address.sendValue(payable(feeCollector), address(this).balance); } else { uint256 _amount = IERC20(_fromToken).balanceOf(address(this)); IERC20(_fromToken).safeTransfer(feeCollector, _amount); } } /// @notice Returns address of token correspond to collateral token function token() external view override returns (address) { return receiptToken; } /** * @notice Calculate total value of asset under management * @dev Report total value in collateral token */ function totalValue() public view virtual override returns (uint256 _value); /** * @notice Calculate total value of asset under management (in real-time) * @dev Report total value in collateral token */ function totalValueCurrent() external virtual override returns (uint256) { return totalValue(); } /// @notice Check whether given token is reserved or not. Reserved tokens are not allowed to sweep. function isReservedToken(address _token) public view virtual override returns (bool); /** * @notice some strategy may want to prepare before doing migration. Example In Maker old strategy want to give vault ownership to new strategy * @param _newStrategy . */ function _beforeMigration(address _newStrategy) internal virtual; /** * @notice Generate report for current profit and loss. Also liquidate asset to payback * excess debt, if any. * @return _profit Calculate any realized profit and convert it to collateral, if not already. * @return _loss Calculate any loss that strategy has made on investment. Convert into collateral token. * @return _payback If strategy has any excess debt, we have to liquidate asset to payback excess debt. */ function _generateReport() internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _payback ) { uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this)); uint256 _totalDebt = IVesperPool(pool).totalDebtOf(address(this)); _profit = _realizeProfit(_totalDebt); _loss = _realizeLoss(_totalDebt); _payback = _liquidate(_excessDebt); } function _calcAmtOutAfterSlippage(uint256 _amount, uint256 _slippage) internal pure returns (uint256) { return (_amount * (10000 - _slippage)) / (10000); } function _simpleOraclePath(address _from, address _to) internal view returns (address[] memory path) { if (_from == WETH || _to == WETH) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = WETH; path[2] = _to; } } function _consultOracle( address _from, address _to, uint256 _amt ) internal returns (uint256, bool) { for (uint256 i = 0; i < swapManager.N_DEX(); i++) { (bool _success, bytes memory _returnData) = address(swapManager).call( abi.encodePacked(swapManager.consult.selector, abi.encode(_from, _to, _amt, oraclePeriod, i)) ); if (_success) { (uint256 rate, uint256 lastUpdate, ) = abi.decode(_returnData, (uint256, uint256, bool)); if ((lastUpdate > (block.timestamp - oraclePeriod)) && (rate != 0)) return (rate, true); return (0, false); } } return (0, false); } function _getOracleRate(address[] memory path, uint256 _amountIn) internal returns (uint256 amountOut) { require(path.length > 1, "invalid-oracle-path"); amountOut = _amountIn; bool isValid; for (uint256 i = 0; i < path.length - 1; i++) { (amountOut, isValid) = _consultOracle(path[i], path[i + 1], amountOut); require(isValid, "invalid-oracle-rate"); } } /** * @notice Safe swap via Uniswap / Sushiswap (better rate of the two) * @dev There are many scenarios when token swap via Uniswap can fail, so this * method will wrap Uniswap call in a 'try catch' to make it fail safe. * however, this method will throw minAmountOut is not met * @param _from address of from token * @param _to address of to token * @param _amountIn Amount to be swapped * @param _minAmountOut minimum amount out */ function _safeSwap( address _from, address _to, uint256 _amountIn, uint256 _minAmountOut ) internal { (address[] memory path, uint256 amountOut, uint256 rIdx) = swapManager.bestOutputFixedInput(_from, _to, _amountIn); if (_minAmountOut == 0) _minAmountOut = 1; if (amountOut != 0) { swapManager.ROUTERS(rIdx).swapExactTokensForTokens( _amountIn, _minAmountOut, path, address(this), block.timestamp ); } } // These methods can be implemented by the inheriting strategy. /* solhint-disable no-empty-blocks */ function _claimRewardsAndConvertTo(address _toToken) internal virtual {} /** * @notice Set up any oracles that are needed for this strategy. */ function _setupOracles() internal virtual {} /* solhint-enable */ // These methods must be implemented by the inheriting strategy function _withdraw(uint256 _amount) internal virtual; function _approveToken(uint256 _amount) internal virtual; /** * @notice Withdraw collateral to payback excess debt in pool. * @param _excessDebt Excess debt of strategy in collateral token * @return _payback amount in collateral token. Usually it is equal to excess debt. */ function _liquidate(uint256 _excessDebt) internal virtual returns (uint256 _payback); /** * @notice Calculate earning and withdraw/convert it into collateral token. * @param _totalDebt Total collateral debt of this strategy * @return _profit Profit in collateral token */ function _realizeProfit(uint256 _totalDebt) internal virtual returns (uint256 _profit); /** * @notice Calculate loss * @param _totalDebt Total collateral debt of this strategy * @return _loss Realized loss in collateral token */ function _realizeLoss(uint256 _totalDebt) internal virtual returns (uint256 _loss); /** * @notice Reinvest collateral. * @dev Once we file report back in pool, we might have some collateral in hand * which we want to reinvest aka deposit in lender/provider. */ function _reinvest() internal virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "../../curve/4Pool/Crv4MetaPoolStrategy.sol"; import "../ConvexStrategyBase.sol"; /// @title This strategy will deposit collateral token in Curve 4MetaPool and stake lp token to convex. abstract contract Convex4MetaPoolStrategy is Crv4MetaPoolStrategy, ConvexStrategyBase { using SafeERC20 for IERC20; constructor( address _pool, address _swapManager, address _metapool, address _gauge, uint256 _collateralIdx, uint256 _convexPoolId, string memory _name ) Crv4MetaPoolStrategy(_pool, _swapManager, _metapool, _gauge, _collateralIdx, _name) ConvexStrategyBase(_metapool, _convexPoolId) { oracleRouterIdx = 0; } /// @dev convex pool can add new rewards. This method refresh list. function setRewardTokens( address[] memory /*_rewardTokens*/ ) external override onlyKeeper { rewardTokens = _getRewardTokens(); _approveToken(0); _approveToken(MAX_UINT_VALUE); _setupOracles(); } function updateClaimRewards(bool _isClaimRewards) external onlyGovernor { isClaimRewards = _isClaimRewards; } function _approveToken(uint256 _amount) internal virtual override { IERC20(crvLp).safeApprove(BOOSTER, _amount); super._approveToken(_amount); } function _stakeAllLp() internal override { uint256 balance = IERC20(crvLp).balanceOf(address(this)); if (balance != 0) { require(IConvex(BOOSTER).deposit(convexPoolId, balance, true), "booster-deposit-failed"); } } function _unstakeAllLp() internal override { Rewards(cvxCrvRewards).withdrawAllAndUnwrap(isClaimRewards); } function _unstakeLp(uint256 _amount) internal override { if (_amount != 0) { require(Rewards(cvxCrvRewards).withdrawAndUnwrap(_amount, false), "withdraw-and-unwrap-failed"); } } function _claimRewards() internal override { require(Rewards(cvxCrvRewards).getReward(address(this), true), "reward-claim-failed"); } function totalStaked() public view override returns (uint256 total) { total = Rewards(cvxCrvRewards).balanceOf(address(this)); } function totalLp() public view override returns (uint256 total) { total = IERC20(crvLp).balanceOf(address(this)) + Rewards(cvxCrvRewards).balanceOf(address(this)); } /// @dev Claimable rewards estimated into pool's collateral value function claimableRewardsInCollateral() public view virtual override returns (uint256 rewardAsCollateral) { ClaimableRewardInfo[] memory _claimableRewardsInfo = _claimableRewards(); for (uint256 i = 0; i < _claimableRewardsInfo.length; i++) { if (_claimableRewardsInfo[i].amount != 0) { (, uint256 _reward, ) = swapManager.bestOutputFixedInput( _claimableRewardsInfo[i].token, address(collateralToken), _claimableRewardsInfo[i].amount ); rewardAsCollateral += _reward; } } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./Convex4MetaPoolStrategy.sol"; //solhint-disable no-empty-blocks contract Convex4MetaPoolStrategyFRAXPool is Convex4MetaPoolStrategy { // FRAX-3CRV Metapool // Composed of [ FRAX , [ DAI, USDC, USDT ]] address internal constant METAPOOL = 0xd632f22692FaC7611d2AA1C0D552930D43CAEd3B; // Gauge for FRAX-3CRV Metapool address internal constant GAUGE = 0x72E158d38dbd50A483501c24f792bDAAA3e7D55C; // Convex Pool ID for FRAX-3CRV uint256 internal constant CONVEX_POOL_ID = 32; constructor( address _pool, address _swapManager, uint256 _collateralIdx, string memory _name ) Convex4MetaPoolStrategy(_pool, _swapManager, METAPOOL, GAUGE, _collateralIdx, CONVEX_POOL_ID, _name) { oracleRouterIdx = 1; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../../interfaces/convex/IConvex.sol"; import "../../interfaces/convex/IConvexToken.sol"; // Convex Strategies common variables and helper functions abstract contract ConvexStrategyBase { using SafeERC20 for IERC20; address public constant CVX = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; address private constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant BOOSTER = 0xF403C135812408BFbE8713b5A23a04b3D48AAE31; address public immutable cvxCrvRewards; uint256 public immutable convexPoolId; bool public isClaimRewards; uint256 internal constant SUSHISWAP_ROUTER_INDEX = 1; struct ClaimableRewardInfo { address token; uint256 amount; } constructor(address _crvLp, uint256 _convexPoolId) { (address _lp, , , address _reward, , ) = IConvex(BOOSTER).poolInfo(_convexPoolId); require(_lp == address(_crvLp), "incorrect-lp-token"); cvxCrvRewards = _reward; convexPoolId = _convexPoolId; } function _getRewardTokens() internal view returns (address[] memory) { uint256 extraRewardCount; for (uint256 i = 0; i < Rewards(cvxCrvRewards).extraRewardsLength(); i++) { Rewards rewardContract = Rewards(Rewards(cvxCrvRewards).extraRewards(i)); // Some pool has CVX as extra rewards but other do not. CVX still reward token if (rewardContract.rewardToken() != CRV && rewardContract.rewardToken() != CVX) { extraRewardCount++; } } address[] memory _rewardTokens = new address[](extraRewardCount + 2); _rewardTokens[0] = CRV; _rewardTokens[1] = CVX; uint256 index = 2; for (uint256 i = 0; i < Rewards(cvxCrvRewards).extraRewardsLength(); i++) { Rewards rewardContract = Rewards(Rewards(cvxCrvRewards).extraRewards(i)); // CRV and CVX already added in array if (rewardContract.rewardToken() != CRV && rewardContract.rewardToken() != CVX) { _rewardTokens[index] = rewardContract.rewardToken(); index++; } } return _rewardTokens; } /// @dev Returns a list of (token, amount) for all rewards claimable in a Convex Pool function _claimableRewards() internal view returns (ClaimableRewardInfo[] memory) { uint256 _extraRewardCount = Rewards(cvxCrvRewards).extraRewardsLength(); ClaimableRewardInfo[] memory _claimableRewardsInfo = new ClaimableRewardInfo[](_extraRewardCount + 2); uint256 _baseReward = Rewards(cvxCrvRewards).earned(address(this)); // CVX rewards are minted proportionally to baseReward (CRV) uint256 _cvxReward = _calculateCVXRewards(_baseReward); _claimableRewardsInfo[0] = ClaimableRewardInfo(CRV, _baseReward); _claimableRewardsInfo[1] = ClaimableRewardInfo(CVX, _cvxReward); // Don't care if there are additional CRV, or CVX in extraRewards // total amount will be summed together in claimableRewardsInCollateral() for (uint256 i = 0; i < _extraRewardCount; i++) { Rewards _rewardContract = Rewards(Rewards(cvxCrvRewards).extraRewards(i)); _claimableRewardsInfo[2 + i] = ClaimableRewardInfo( _rewardContract.rewardToken(), _rewardContract.earned(address(this)) ); } return _claimableRewardsInfo; } // TODO: review this again. There may be substitute function _calculateCVXRewards(uint256 _claimableCrvRewards) internal view returns (uint256 _total) { // CVX Rewards are minted based on CRV rewards claimed upon withdraw // This will calculate the CVX amount based on CRV rewards accrued // without having to claim CRV rewards first // ref 1: https://github.com/convex-eth/platform/blob/main/contracts/contracts/Cvx.sol#L61-L76 // ref 2: https://github.com/convex-eth/platform/blob/main/contracts/contracts/Booster.sol#L458-L466 uint256 _reductionPerCliff = IConvexToken(CVX).reductionPerCliff(); uint256 _totalSupply = IConvexToken(CVX).totalSupply(); uint256 _maxSupply = IConvexToken(CVX).maxSupply(); uint256 _cliff = _totalSupply / _reductionPerCliff; uint256 _totalCliffs = 1000; if (_cliff < _totalCliffs) { //for reduction% take inverse of current cliff uint256 _reduction = _totalCliffs - _cliff; //reduce _total = (_claimableCrvRewards * _reduction) / _totalCliffs; //supply cap check uint256 _amtTillMax = _maxSupply - _totalSupply; if (_total > _amtTillMax) { _total = _amtTillMax; } } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../../../interfaces/vesper/IVesperPool.sol"; import "../../Strategy.sol"; import "../CrvPoolStrategyBase.sol"; /// @title This strategy will deposit collateral token in Curve a 4Pool Metapool and earn interest. abstract contract Crv4MetaPoolStrategy is CrvPoolStrategyBase { using SafeERC20 for IERC20; // No. of pooled tokens in the metapool uint256 private constant N = 4; // Curve Metapool Factory address private constant FACTORY = 0x0959158b6040D32d04c301A72CBFD6b39E21c9AE; // Curve DepositZap Contract address internal constant DEPOSIT_ZAP = 0xA79828DF1850E8a3A3064576f380D90aECDD3359; constructor( address _pool, address _swapManager, address _metapool, address _gauge, uint256 _collateralIdx, string memory _name ) CrvPoolStrategyBase(_pool, _metapool, _metapool, _gauge, _swapManager, _collateralIdx, N, _name) { require(ILiquidityGaugeV2(_gauge).lp_token() == _metapool, "invalid-gauge"); } function _init( address _crvPool, uint256 /* _n */ ) internal virtual override { coins = IMetapoolFactory(FACTORY).get_underlying_coins(_crvPool); coinDecimals = IMetapoolFactory(FACTORY).get_underlying_decimals(_crvPool); } function _approveToken(uint256 _amount) internal virtual override { super._approveToken(_amount); collateralToken.safeApprove(DEPOSIT_ZAP, _amount); IERC20(crvLp).safeApprove(DEPOSIT_ZAP, _amount); } function _depositToCurve(uint256 _amt) internal virtual override returns (bool) { if (_amt != 0) { uint256[4] memory _depositAmounts; _depositAmounts[collIdx] = _amt; uint256 expectedOut = _calcAmtOutAfterSlippage( IDepositZap4x(DEPOSIT_ZAP).calc_token_amount(crvLp, _depositAmounts, true), crvSlippage ); uint256 _minLpAmount = ((_amt * _getSafeUsdRate()) / crvPool.get_virtual_price()) * 10**(18 - coinDecimals[collIdx]); if (expectedOut > _minLpAmount) _minLpAmount = expectedOut; // solhint-disable-next-line no-empty-blocks try IDepositZap4x(DEPOSIT_ZAP).add_liquidity(crvLp, _depositAmounts, _minLpAmount) {} catch Error( string memory _reason ) { emit DepositFailed(_reason); return false; } } return true; } function _withdrawAsFromCrvPool( uint256 _lpAmount, uint256 _minAmt, uint256 _i ) internal virtual override { IDepositZap4x(DEPOSIT_ZAP).remove_liquidity_one_coin(crvLp, _lpAmount, SafeCast.toInt128(int256(_i)), _minAmt); } function getLpValueAs(uint256 _lpAmount, uint256 _i) public view virtual override returns (uint256) { return (_lpAmount != 0) ? IDepositZap4x(DEPOSIT_ZAP).calc_withdraw_one_coin(crvLp, _lpAmount, SafeCast.toInt128(int256(_i))) : 0; } function _claimRewards() internal virtual override { ITokenMinter(CRV_MINTER).mint(crvGauge); ILiquidityGaugeV2(crvGauge).claim_rewards(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "../../interfaces/curve/IStableSwap.sol"; import "../../interfaces/curve/ILiquidityGauge.sol"; import "../../interfaces/curve/ITokenMinter.sol"; import "../../interfaces/curve/IMetapoolFactory.sol"; import "../../interfaces/curve/IDepositZap.sol"; abstract contract CrvBase { using SafeERC20 for IERC20; address public constant CRV_MINTER = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // solhint-disable-next-line var-name-mixedcase address public CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52; IStableSwapUnderlying public immutable crvPool; address public immutable crvLp; address public immutable crvGauge; constructor( address _pool, address _lp, address _gauge ) { require(_pool != address(0x0), "CRVMgr: invalid curve pool"); require(_lp != address(0x0), "CRVMgr: invalid lp token"); require(_gauge != address(0x0), "CRVMgr: invalid gauge"); crvPool = IStableSwapUnderlying(_pool); crvLp = _lp; crvGauge = _gauge; } function _minimumLpPrice(uint256 _safeRate) internal view returns (uint256) { return ((crvPool.get_virtual_price() * _safeRate) / 1e18); } function _withdrawAsFromCrvPool( uint256 _lpAmount, uint256 _minAmt, uint256 i ) internal virtual { crvPool.remove_liquidity_one_coin(_lpAmount, SafeCast.toInt128(int256(i)), _minAmt); } function _withdrawAllAs(uint256 i) internal virtual { uint256 lpAmt = IERC20(crvLp).balanceOf(address(this)); if (lpAmt != 0) { crvPool.remove_liquidity_one_coin(lpAmt, SafeCast.toInt128(int256(i)), 0); } } function calcWithdrawLpAs(uint256 _amtNeeded, uint256 i) public view returns (uint256 lpToWithdraw, uint256 unstakeAmt) { uint256 lp = getLp(); uint256 tlp = totalLp(); lpToWithdraw = (_amtNeeded * tlp) / getLpValueAs(tlp, i); lpToWithdraw = (lpToWithdraw > tlp) ? tlp : lpToWithdraw; if (lpToWithdraw > lp) { unstakeAmt = lpToWithdraw - lp; } } function getLpValueAs(uint256 _lpAmount, uint256 i) public view virtual returns (uint256) { return (_lpAmount != 0) ? crvPool.calc_withdraw_one_coin(_lpAmount, SafeCast.toInt128(int256(i))) : 0; } // While this is inaccurate in terms of slippage, this gives us the // best estimate (least manipulatable value) to calculate share price function getLpValue(uint256 _lpAmount) public view virtual returns (uint256) { return (_lpAmount != 0) ? (crvPool.get_virtual_price() * _lpAmount) / 1e18 : 0; } function setCheckpoint() external { _setCheckpoint(); } // requires that gauge has approval for lp token function _stakeAllLp() internal virtual { uint256 balance = IERC20(crvLp).balanceOf(address(this)); if (balance != 0) { ILiquidityGaugeV2(crvGauge).deposit(balance); } } function _unstakeAllLp() internal virtual { _unstakeLp(IERC20(crvGauge).balanceOf(address(this))); } function _unstakeLp(uint256 _amount) internal virtual { if (_amount != 0) { ILiquidityGaugeV2(crvGauge).withdraw(_amount); } } function _claimRewards() internal virtual { ITokenMinter(CRV_MINTER).mint(crvGauge); } function _setCheckpoint() internal virtual { ILiquidityGaugeV2(crvGauge).user_checkpoint(address(this)); } function totalStaked() public view virtual returns (uint256 total) { total = IERC20(crvGauge).balanceOf(address(this)); } function totalLp() public view virtual returns (uint256 total) { total = getLp() + IERC20(crvGauge).balanceOf(address(this)); } // Gets LP value not staked in gauge function getLp() public view virtual returns (uint256 total) { total = IERC20(crvLp).balanceOf(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "../../interfaces/vesper/IVesperPool.sol"; import "../Strategy.sol"; import "./CrvBase.sol"; /// @title This strategy will deposit collateral token in a Curve Pool and earn interest. abstract contract CrvPoolStrategyBase is CrvBase, Strategy { using SafeERC20 for IERC20; // solhint-disable-next-line var-name-mixedcase string public NAME; string public constant VERSION = "4.0.0"; mapping(address => bool) internal reservedToken; uint256 public immutable collIdx; uint256 public usdRate; uint256 public usdRateTimestamp; address[] public coins; uint256[] public coinDecimals; address[] public rewardTokens; bool public depositError; uint256 public crvSlippage = 10; // 10000 is 100%; 10 is 0.1% uint256 public decimalConversionFactor; // It will be used in converting value to/from 18 decimals // No. of pooled tokens in the Pool uint256 internal immutable n; event UpdatedCrvSlippage(uint256 oldCrvSlippage, uint256 newCrvSlippage); event DepositFailed(string reason); constructor( address _pool, address _crvPool, address _crvLp, address _crvGauge, address _swapManager, uint256 _collateralIdx, uint256 _n, string memory _name ) CrvBase(_crvPool, _crvLp, _crvGauge) // 3Pool Manager Strategy(_pool, _swapManager, _crvLp) { require(_collateralIdx < _n, "invalid-collateral"); n = _n; reservedToken[_crvLp] = true; reservedToken[CRV] = true; collIdx = _collateralIdx; _init(_crvPool, _n); require(coins[_collateralIdx] == address(IVesperPool(_pool).token()), "collateral-mismatch"); // Assuming token supports 18 or less decimals. _init will initialize coins array uint256 _decimals = IERC20Metadata(coins[_collateralIdx]).decimals(); decimalConversionFactor = 10**(18 - _decimals); NAME = _name; rewardTokens.push(CRV); } /// @dev Rewards token in gauge can be updated any time. Governor can set reward tokens /// Different version of gauge has different method to read reward tokens better governor set it function setRewardTokens(address[] memory _rewardTokens) external virtual onlyGovernor { rewardTokens = _rewardTokens; for (uint256 i = 0; i < _rewardTokens.length; i++) { require( _rewardTokens[i] != receiptToken && _rewardTokens[i] != address(collateralToken) && _rewardTokens[i] != pool && _rewardTokens[i] != crvLp, "Invalid reward token" ); reservedToken[_rewardTokens[i]] = true; } _approveToken(0); _approveToken(MAX_UINT_VALUE); _setupOracles(); } function updateCrvSlippage(uint256 _newCrvSlippage) external onlyGovernor { require(_newCrvSlippage < 10000, "invalid-slippage-value"); emit UpdatedCrvSlippage(crvSlippage, _newCrvSlippage); crvSlippage - _newCrvSlippage; } /// @dev Claimable rewards estimated into pool's collateral value function claimableRewardsInCollateral() public view virtual returns (uint256 rewardAsCollateral) { //Total Mintable - Previously minted uint256 claimable = ILiquidityGaugeV2(crvGauge).integrate_fraction(address(this)) - ITokenMinter(CRV_MINTER).minted(address(this), crvGauge); if (claimable != 0) { (, rewardAsCollateral, ) = swapManager.bestOutputFixedInput(CRV, address(collateralToken), claimable); } } /// @dev Convert from 18 decimals to token defined decimals. function convertFrom18(uint256 _amount) public view returns (uint256) { return _amount / decimalConversionFactor; } /// @dev Check whether given token is reserved or not. Reserved tokens are not allowed to sweep. function isReservedToken(address _token) public view override returns (bool) { return reservedToken[_token]; } /** * @notice Calculate total value of asset under management * @dev Report total value in collateral token */ function totalValue() public view virtual override returns (uint256 _value) { _value = collateralToken.balanceOf(address(this)) + convertFrom18(_calcAmtOutAfterSlippage(getLpValue(totalLp()), crvSlippage)) + claimableRewardsInCollateral(); } function _setupOracles() internal virtual override { _safeCreateOrUpdateOracle(CRV, WETH); for (uint256 i = 0; i < n; i++) { _safeCreateOrUpdateOracle(coins[i], WETH); } for (uint256 i = 0; i < rewardTokens.length; i++) { _safeCreateOrUpdateOracle(rewardTokens[i], WETH); } } /** * @dev Creates Oracle pair preventing revert if it doesn't exist in a DEX */ function _safeCreateOrUpdateOracle(address _tokenA, address _tokenB) internal { for (uint256 i = 0; i < swapManager.N_DEX(); i++) { // solhint-disable no-empty-blocks try swapManager.createOrUpdateOracle(_tokenA, _tokenB, oraclePeriod, i) { break; } catch Error( string memory /* reason */ ) {} // solhint-enable no-empty-blocks } } // given the rates of 3 stablecoins compared with a common denominator // return the lowest divided by the highest function _getSafeUsdRate() internal returns (uint256) { // use a stored rate if we've looked it up recently if (usdRateTimestamp > block.timestamp - oraclePeriod && usdRate != 0) return usdRate; // otherwise, calculate a rate and store it. uint256 lowest; uint256 highest; for (uint256 i = 0; i < n; i++) { // get the rate for $1 (uint256 rate, bool isValid) = _consultOracle(coins[i], WETH, 10**coinDecimals[i]); if (isValid) { if (lowest == 0 || rate < lowest) { lowest = rate; } if (highest < rate) { highest = rate; } } } // We only need to check one of them because if a single valid rate is returned, // highest == lowest and highest > 0 && lowest > 0 require(lowest != 0, "no-oracle-rates"); usdRateTimestamp = block.timestamp; usdRate = (lowest * 1e18) / highest; return usdRate; } function _approveToken(uint256 _amount) internal virtual override { collateralToken.safeApprove(pool, _amount); collateralToken.safeApprove(address(crvPool), _amount); for (uint256 j = 0; j < swapManager.N_DEX(); j++) { for (uint256 i = 0; i < rewardTokens.length; i++) { IERC20(rewardTokens[i]).safeApprove(address(swapManager.ROUTERS(j)), _amount); } collateralToken.safeApprove(address(swapManager.ROUTERS(j)), _amount); } IERC20(crvLp).safeApprove(crvGauge, _amount); } function _init(address _crvPool, uint256 _n) internal virtual { for (uint256 i = 0; i < _n; i++) { coins.push(IStableSwapUnderlying(_crvPool).coins(i)); coinDecimals.push(IERC20Metadata(coins[i]).decimals()); } } function _reinvest() internal override { depositError = false; uint256 amt = collateralToken.balanceOf(address(this)); depositError = !_depositToCurve(amt); _stakeAllLp(); } function _depositToCurve(uint256 amt) internal virtual returns (bool) { if (amt != 0) { uint256[3] memory depositAmounts; depositAmounts[collIdx] = amt; uint256 expectedOut = _calcAmtOutAfterSlippage( IStableSwap3xUnderlying(address(crvPool)).calc_token_amount(depositAmounts, true), crvSlippage ); uint256 minLpAmount = ((amt * _getSafeUsdRate()) / crvPool.get_virtual_price()) * 10**(18 - coinDecimals[collIdx]); if (expectedOut > minLpAmount) minLpAmount = expectedOut; // solhint-disable-next-line no-empty-blocks try IStableSwap3xUnderlying(address(crvPool)).add_liquidity(depositAmounts, minLpAmount) {} catch Error( string memory reason ) { emit DepositFailed(reason); return false; } } return true; } function _withdraw(uint256 _amount) internal override { // This adds some gas but will save loss on exchange fees uint256 balanceHere = collateralToken.balanceOf(address(this)); if (_amount > balanceHere) { _unstakeAndWithdrawAsCollateral(_amount - balanceHere); } collateralToken.safeTransfer(pool, _amount); } function _unstakeAndWithdrawAsCollateral(uint256 _amount) internal returns (uint256 toWithdraw) { if (_amount == 0) return 0; uint256 i = collIdx; (uint256 lpToWithdraw, uint256 unstakeAmt) = calcWithdrawLpAs(_amount, i); _unstakeLp(unstakeAmt); uint256 minAmtOut = convertFrom18( (lpToWithdraw * _calcAmtOutAfterSlippage(_minimumLpPrice(_getSafeUsdRate()), crvSlippage)) / 1e18 ); _withdrawAsFromCrvPool(lpToWithdraw, minAmtOut, i); toWithdraw = collateralToken.balanceOf(address(this)); if (toWithdraw > _amount) toWithdraw = _amount; } /** * @notice some strategy may want to prepare before doing migration. Example In Maker old strategy want to give vault ownership to new strategy */ function _beforeMigration( address /*_newStrategy*/ ) internal override { _unstakeAllLp(); } /** * @notice Curve pool may have more than one reward token. Child contract should override _claimRewards */ function _claimRewardsAndConvertTo(address _toToken) internal virtual override { _claimRewards(); for (uint256 i = 0; i < rewardTokens.length; i++) { uint256 _amt = IERC20(rewardTokens[i]).balanceOf(address(this)); if (_amt != 0) { uint256 _minAmtOut; if (swapSlippage < 10000) { (uint256 _minWethOut, bool _isValid) = _consultOracle(rewardTokens[i], WETH, _amt); (uint256 _minTokenOut, bool _isValidTwo) = _consultOracle(WETH, _toToken, _minWethOut); require(_isValid, "stale-reward-oracle"); require(_isValidTwo, "stale-collateral-oracle"); _minAmtOut = _calcAmtOutAfterSlippage(_minTokenOut, swapSlippage); } _safeSwap(rewardTokens[i], _toToken, _amt, _minAmtOut); } } } /** * @notice Withdraw collateral to payback excess debt in pool. * @param _excessDebt Excess debt of strategy in collateral token * @param _extra additional amount to unstake and withdraw, in collateral token * @return _payback amount in collateral token. Usually it is equal to excess debt. */ function _liquidate(uint256 _excessDebt, uint256 _extra) internal returns (uint256 _payback) { _payback = _unstakeAndWithdrawAsCollateral(_excessDebt + _extra); // we dont want to return a value greater than we need to if (_payback > _excessDebt) _payback = _excessDebt; } function _realizeLoss(uint256 _totalDebt) internal view override returns (uint256 _loss) { uint256 _collateralBalance = convertFrom18(_calcAmtOutAfterSlippage(getLpValue(totalLp()), crvSlippage)); if (_collateralBalance < _totalDebt) { _loss = _totalDebt - _collateralBalance; } } function _realizeGross(uint256 _totalDebt) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _toUnstake ) { uint256 baseline = collateralToken.balanceOf(address(this)); _claimRewardsAndConvertTo(address(collateralToken)); uint256 newBalance = collateralToken.balanceOf(address(this)); _profit = newBalance - baseline; uint256 _collateralBalance = baseline + convertFrom18(_calcAmtOutAfterSlippage(getLpValue(totalLp()), crvSlippage)); if (_collateralBalance > _totalDebt) { _profit += _collateralBalance - _totalDebt; } else { _loss = _totalDebt - _collateralBalance; } if (_profit > _loss) { _profit = _profit - _loss; _loss = 0; if (_profit > newBalance) _toUnstake = _profit - newBalance; } else { _loss = _loss - _profit; _profit = 0; } } function _generateReport() internal virtual override returns ( uint256 _profit, uint256 _loss, uint256 _payback ) { uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this)); uint256 _totalDebt = IVesperPool(pool).totalDebtOf(address(this)); uint256 _toUnstake; (_profit, _loss, _toUnstake) = _realizeGross(_totalDebt); // only make call to unstake and withdraw once _payback = _liquidate(_excessDebt, _toUnstake); } function rebalance() external virtual override onlyKeeper { (uint256 _profit, uint256 _loss, uint256 _payback) = _generateReport(); IVesperPool(pool).reportEarning(_profit, _loss, _payback); _reinvest(); if (!depositError) { uint256 _depositLoss = _realizeLoss(IVesperPool(pool).totalDebtOf(address(this))); IVesperPool(pool).reportLoss(_depositLoss); } } // Unused /* solhint-disable no-empty-blocks */ function _liquidate(uint256 _excessDebt) internal override returns (uint256 _payback) {} function _realizeProfit(uint256 _totalDebt) internal override returns (uint256 _profit) {} }
Curve pool may have more than one reward token. Child contract should override _claimRewards/
function _claimRewardsAndConvertTo(address _toToken) internal virtual override { _claimRewards(); for (uint256 i = 0; i < rewardTokens.length; i++) { uint256 _amt = IERC20(rewardTokens[i]).balanceOf(address(this)); if (_amt != 0) { uint256 _minAmtOut; if (swapSlippage < 10000) { (uint256 _minWethOut, bool _isValid) = _consultOracle(rewardTokens[i], WETH, _amt); (uint256 _minTokenOut, bool _isValidTwo) = _consultOracle(WETH, _toToken, _minWethOut); require(_isValid, "stale-reward-oracle"); require(_isValidTwo, "stale-collateral-oracle"); _minAmtOut = _calcAmtOutAfterSlippage(_minTokenOut, swapSlippage); } _safeSwap(rewardTokens[i], _toToken, _amt, _minAmtOut); } } }
5,825,350
pragma solidity ^0.4.23; import "raiden/Utils.sol"; import "raiden/Token.sol"; import "raiden/TokenNetwork.sol"; contract TokenNetworkRegistry is Utils { /* * Data structures */ string constant public contract_version = "0.3._"; address public secret_registry_address; uint256 public chain_id; uint256 public settlement_timeout_min; uint256 public settlement_timeout_max; // Token address => TokenNetwork address mapping(address => address) public token_to_token_networks; /* * Events */ event TokenNetworkCreated(address indexed token_address, address indexed token_network_address); /* * Constructor */ constructor( address _secret_registry_address, uint256 _chain_id, uint256 _settlement_timeout_min, uint256 _settlement_timeout_max ) public { require(_chain_id > 0); require(_settlement_timeout_min > 0); require(_settlement_timeout_max > 0); require(_settlement_timeout_max > _settlement_timeout_min); require(_secret_registry_address != 0x0); require(contractExists(_secret_registry_address)); secret_registry_address = _secret_registry_address; chain_id = _chain_id; settlement_timeout_min = _settlement_timeout_min; settlement_timeout_max = _settlement_timeout_max; } /* * External Functions */ function createERC20TokenNetwork(address _token_address) external returns (address token_network_address) { require(token_to_token_networks[_token_address] == 0x0); // Token contract checks are in the corresponding TokenNetwork contract token_network_address = new TokenNetwork( _token_address, secret_registry_address, chain_id, settlement_timeout_min, settlement_timeout_max ); token_to_token_networks[_token_address] = token_network_address; emit TokenNetworkCreated(_token_address, token_network_address); return token_network_address; } }
Token contract checks are in the corresponding TokenNetwork contract
function createERC20TokenNetwork(address _token_address) external returns (address token_network_address) { require(token_to_token_networks[_token_address] == 0x0); token_network_address = new TokenNetwork( _token_address, secret_registry_address, chain_id, settlement_timeout_min, settlement_timeout_max ); token_to_token_networks[_token_address] = token_network_address; emit TokenNetworkCreated(_token_address, token_network_address); return token_network_address; }
12,727,965
//Address: 0xd275b50f71badf4fa2f911e80e1e420730ab403e //Contract name: DragonCrowdsaleCore //Balance: 0 Ether //Verification Date: 12/25/2017 //Transacion Count: 7 // CODE STARTS HERE pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract DragonPricing is Ownable { DragonCrowdsaleCore dragoncrowdsalecore; uint public firstroundprice = .000000000083333333 ether; uint public secondroundprice = .000000000100000000 ether; uint public thirdroundprice = .000000000116686114 ether; uint public price; function DragonPricing() { price = firstroundprice; } function crowdsalepricing( address tokenholder, uint amount, uint crowdsaleCounter ) returns ( uint , uint ) { uint award; uint donation = 0; return ( DragonAward ( amount, crowdsaleCounter ) ,donation ); } function precrowdsalepricing( address tokenholder, uint amount ) returns ( uint, uint ) { uint award; uint donation; require ( presalePackage( amount ) == true ); ( award, donation ) = DragonAwardPresale ( amount ); return ( award, donation ); } function presalePackage ( uint amount ) internal returns ( bool ) { if( amount != .3333333 ether && amount != 3.3333333 ether && amount != 33.3333333 ether ) return false; return true; } function DragonAwardPresale ( uint amount ) internal returns ( uint , uint ){ if ( amount == .3333333 ether ) return ( 10800000000 , 800000000 ); if ( amount == 3.3333333 ether ) return ( 108800000000 , 8800000000 ); if ( amount == 33.3333333 ether ) return ( 1088800000000 , 88800000000 ); } function DragonAward ( uint amount, uint crowdsaleCounter ) internal returns ( uint ){ //uint crowdsaleCounter = dragoncrowdsalecore.crowdsaleCounter(); if ( crowdsaleCounter > 1000000000000000 && crowdsaleCounter < 2500000000000000 ) price = secondroundprice; if ( crowdsaleCounter >= 2500000000000000 ) price = thirdroundprice; return ( amount / price ); } function setFirstRoundPricing ( uint _pricing ) onlyOwner { firstroundprice = _pricing; } function setSecondRoundPricing ( uint _pricing ) onlyOwner { secondroundprice = _pricing; } function setThirdRoundPricing ( uint _pricing ) onlyOwner { thirdroundprice = _pricing; } } contract Dragon { function transfer(address receiver, uint amount)returns(bool ok); function balanceOf( address _address )returns(uint256); } contract DragonCrowdsaleCore is Ownable, DragonPricing { using SafeMath for uint; // address public owner; address public beneficiary; address public charity; address public advisor; address public front; bool public advisorset; uint public tokensSold; uint public etherRaised; uint public presold; uint public presoldMax; uint public crowdsaleCounter; uint public advisorTotal; uint public advisorCut; Dragon public tokenReward; mapping ( address => bool ) public alreadyParticipated; modifier onlyFront() { require (msg.sender == front ); _; } function DragonCrowdsaleCore(){ tokenReward = Dragon( 0x814f67fa286f7572b041d041b1d99b432c9155ee ); // Dragon Token Address owner = msg.sender; beneficiary = msg.sender; charity = msg.sender; advisor = msg.sender; advisorset = false; presold = 0; presoldMax = 3500000000000000; crowdsaleCounter = 0; advisorCut = 0; advisorTotal = 1667 ether; } // runs during precrowdsale - can only be called by main crowdsale contract function precrowdsale ( address tokenholder ) onlyFront payable { require ( presold < presoldMax ); uint award; // amount of dragons to credit to tokenholder uint donation; // donation to charity require ( alreadyParticipated[ tokenholder ] != true ) ; alreadyParticipated[ tokenholder ] = true; DragonPricing pricingstructure = new DragonPricing(); ( award, donation ) = pricingstructure.precrowdsalepricing( tokenholder , msg.value ); tokenReward.transfer ( charity , donation ); // send dragons to charity presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(donation); //add charity donation to total number of tokens sold tokenReward.transfer ( tokenholder , award ); // immediate transfer of dragons to token buyer if ( advisorCut < advisorTotal ) { advisorSiphon();} else { beneficiary.transfer ( msg.value ); } //send ether to beneficiary etherRaised = etherRaised.add( msg.value ); // tallies ether raised tokensSold = tokensSold.add(award); // tallies total dragons sold } // runs when crowdsale is active - can only be called by main crowdsale contract function crowdsale ( address tokenholder ) onlyFront payable { uint award; // amount of dragons to send to tokenholder uint donation; // donation to charity DragonPricing pricingstructure = new DragonPricing(); ( award , donation ) = pricingstructure.crowdsalepricing( tokenholder, msg.value, crowdsaleCounter ); crowdsaleCounter += award; tokenReward.transfer ( tokenholder , award ); // immediate transfer to token holders if ( advisorCut < advisorTotal ) { advisorSiphon();} // send advisor his share else { beneficiary.transfer ( msg.value ); } //send all ether to beneficiary etherRaised = etherRaised.add( msg.value ); //etherRaised += msg.value; // tallies ether raised tokensSold = tokensSold.add(award); //tokensSold += award; // tallies total dragons sold } // pays the advisor part of the incoming ether function advisorSiphon() internal { uint share = msg.value/10; uint foradvisor = share; if ( (advisorCut + share) > advisorTotal ) foradvisor = advisorTotal.sub( advisorCut ); advisor.transfer ( foradvisor ); // advisor gets 10% of the incoming ether advisorCut = advisorCut.add( foradvisor ); beneficiary.transfer( share * 9 ); // the ether balance goes to the benfeciary if ( foradvisor != share ) beneficiary.transfer( share.sub(foradvisor) ); // if 10% of the incoming ether exceeds the total advisor is supposed to get , then this gives them a smaller share to not exceed max } // use this to set the crowdsale beneficiary address function transferBeneficiary ( address _newbeneficiary ) onlyOwner { require ( _newbeneficiary != 0x00 ); beneficiary = _newbeneficiary; } // use this to set the charity address function transferCharity ( address _charity ) onlyOwner { require ( _charity != 0x00 ); charity = _charity; } // sets crowdsale address function setFront ( address _front ) onlyOwner { require ( _front != 0x00 ); front = _front; } // sets advisors address function setAdvisor ( address _advisor ) onlyOwner { require ( _advisor != 0x00 ); require ( advisorset == false ); advisorset = true; advisor = _advisor; } //empty the crowdsale contract of Dragons and forward balance to beneficiary function withdrawCrowdsaleDragons() onlyOwner{ uint256 balance = tokenReward.balanceOf( address( this ) ); tokenReward.transfer( beneficiary, balance ); } //manually send different dragon packages function manualSend ( address tokenholder, uint packagenumber ) onlyOwner { require ( tokenholder != 0x00 ); if ( packagenumber != 1 && packagenumber != 2 && packagenumber != 3 ) revert(); uint award; uint donation; if ( packagenumber == 1 ) { award = 10800000000; donation = 800000000; } if ( packagenumber == 2 ) { award = 108800000000; donation = 8800000000; } if ( packagenumber == 3 ) { award = 1088800000000; donation = 88800000000; } tokenReward.transfer ( tokenholder , award ); tokenReward.transfer ( charity , donation ); presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(award); // tallies total dragons sold tokensSold = tokensSold.add(donation); // tallies total dragons sold } }
uint crowdsaleCounter = dragoncrowdsalecore.crowdsaleCounter();
function DragonAward ( uint amount, uint crowdsaleCounter ) internal returns ( uint ){ if ( crowdsaleCounter > 1000000000000000 && crowdsaleCounter < 2500000000000000 ) price = secondroundprice; if ( crowdsaleCounter >= 2500000000000000 ) price = thirdroundprice; return ( amount / price ); }
12,799,359
./full_match/1/0x6BAa28FE15A0ec75a92Dc8a9E356B39Fbe0bbbe3/sources/contracts/Meditations.sol
_transfer override adds logic to track transfer counts as well as the prior owner. This override updates mappings and then calls the overridden function. _from is the address the token is being sent from. _to is the address the token is being sent to. _tokenId is the token being transferred./
function _transfer( address _from, address _to, uint256 _tokenId ) internal virtual override { transferCountOf[_tokenId]++; lastTransferOf[_tokenId] = block.timestamp; super._transfer(_from, _to, _tokenId); }
8,294,860
./full_match/42/0x225ea51550882702DD6F2C247B912daA54D9b3c7/sources/browser/IlkRegistry.sol
Authed edit function
function file(bytes32 ilk, bytes32 what, string calldata data) external auth { if (what == "name") ilkData[ilk].name = data; else if (what == "symbol") ilkData[ilk].symbol = data; else revert("IlkRegistry/file-unrecognized-param-string"); }
9,597,338
// Sources flattened with hardhat v2.6.0 https://hardhat.org // File contracts/interfaces/IArmorMaster.sol pragma solidity ^0.6.0; interface IArmorMaster { function registerModule(bytes32 _key, address _module) external; function getModule(bytes32 _key) external view returns(address); function keep() external; } // File contracts/general/Ownable.sol pragma solidity ^0.6.6; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". * * @dev Completely default OpenZeppelin. */ contract Ownable { address private _owner; address private _pendingOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function initializeOwnable() internal { require(_owner == address(0), "already initialized"); _owner = msg.sender; emit OwnershipTransferred(address(0), 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(), "msg.sender is not owner"); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _pendingOwner = newOwner; } function receiveOwnership() public { require(msg.sender == _pendingOwner, "only pending owner can call this function"); _transferOwnership(_pendingOwner); _pendingOwner = address(0); } /** * @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; } uint256[50] private __gap; } // File contracts/general/Bytes32.sol pragma solidity ^0.6.6; library Bytes32 { function toString(bytes32 x) internal pure returns (string memory) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint256 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 (uint256 j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } } // File contracts/general/ArmorModule.sol pragma solidity ^0.6.0; /** * @dev Each arCore contract is a module to enable simple communication and interoperability. ArmorMaster.sol is master. **/ contract ArmorModule { IArmorMaster internal _master; using Bytes32 for bytes32; modifier onlyOwner() { require(msg.sender == Ownable(address(_master)).owner(), "only owner can call this function"); _; } modifier doKeep() { _master.keep(); _; } modifier onlyModule(bytes32 _module) { string memory message = string(abi.encodePacked("only module ", _module.toString()," can call this function")); require(msg.sender == getModule(_module), message); _; } /** * @dev Used when multiple can call. **/ modifier onlyModules(bytes32 _moduleOne, bytes32 _moduleTwo) { string memory message = string(abi.encodePacked("only module ", _moduleOne.toString()," or ", _moduleTwo.toString()," can call this function")); require(msg.sender == getModule(_moduleOne) || msg.sender == getModule(_moduleTwo), message); _; } function initializeModule(address _armorMaster) internal { require(address(_master) == address(0), "already initialized"); require(_armorMaster != address(0), "master cannot be zero address"); _master = IArmorMaster(_armorMaster); } function changeMaster(address _newMaster) external onlyOwner { _master = IArmorMaster(_newMaster); } function getModule(bytes32 _key) internal view returns(address) { return _master.getModule(_key); } } // File contracts/libraries/SafeMath.sol pragma solidity ^0.6.6; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error * * @dev Default OpenZeppelin */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File contracts/general/BalanceWrapper.sol pragma solidity ^0.6.6; contract BalanceWrapper { using SafeMath for uint256; uint256 internal _totalSupply; mapping(address => uint256) internal _balances; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function _addStake(address user, uint256 amount) internal { _totalSupply = _totalSupply.add(amount); _balances[user] = _balances[user].add(amount); } function _removeStake(address user, uint256 amount) internal { _totalSupply = _totalSupply.sub(amount); _balances[user] = _balances[user].sub(amount); } } // File contracts/libraries/Math.sol pragma solidity ^0.6.6; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File contracts/interfaces/IPlanManager.sol pragma solidity ^0.6.6; interface IPlanManager { // Mapping = protocol => cover amount struct Plan { uint64 startTime; uint64 endTime; uint128 length; } struct ProtocolPlan { uint64 protocolId; uint192 amount; } // Event to notify frontend of plan update. event PlanUpdate(address indexed user, address[] protocols, uint256[] amounts, uint256 endTime); function userCoverageLimit(address _user, address _protocol) external view returns(uint256); function markup() external view returns(uint256); function nftCoverPrice(address _protocol) external view returns(uint256); function initialize(address _armorManager) external; function changePrice(address _scAddress, uint256 _pricePerAmount) external; function updatePlan(address[] calldata _protocols, uint256[] calldata _coverAmounts) external; function checkCoverage(address _user, address _protocol, uint256 _hacktime, uint256 _amount) external view returns (uint256, bool); function coverageLeft(address _protocol) external view returns(uint256); function getCurrentPlan(address _user) external view returns(uint256 idx, uint128 start, uint128 end); function updateExpireTime(address _user, uint256 _expiry) external; function planRedeemed(address _user, uint256 _planIndex, address _protocol) external; function totalUsedCover(address _scAddress) external view returns (uint256); } // File contracts/interfaces/IRewardManagerV2.sol pragma solidity ^0.6.6; interface IRewardManagerV2 { function initialize(address _armorMaster, uint256 _rewardCycleBlocks) external; function deposit( address _user, address _protocol, uint256 _amount, uint256 _nftId ) external; function withdraw( address _user, address _protocol, uint256 _amount, uint256 _nftId ) external; function updateAllocPoint(address _protocol, uint256 _allocPoint) external; function initPool(address _protocol) external; function notifyRewardAmount() external payable; } // File contracts/core/RewardManagerV2.sol // SPDX-License-Identifier: (c) Armor.Fi DAO, 2021 pragma solidity ^0.6.6; /** * @dev RewardManagerV2 is a updated RewardManager to distribute rewards. * based on total used cover per protocols. **/ contract RewardManagerV2 is BalanceWrapper, ArmorModule, IRewardManagerV2 { /** * @dev Universal requirements: * - Calculate reward per protocol by totalUsedCover. * - onlyGov functions must only ever be able to be accessed by governance. * - Total of refBals must always equal refTotal. * - depositor should always be address(0) if contract is not locked. * - totalTokens must always equal pToken.balanceOf( address(this) ) - (refTotal + sum(feesToLiq) ). **/ event RewardPaid(address indexed user, address indexed protocol, uint256 reward, uint256 timestamp); event BalanceAdded( address indexed user, address indexed protocol, uint256 indexed nftId, uint256 amount, uint256 totalStaked, uint256 timestamp ); event BalanceWithdrawn( address indexed user, address indexed protocol, uint256 indexed nftId, uint256 amount, uint256 totalStaked, uint256 timestamp ); struct UserInfo { uint256 amount; // How much cover staked uint256 rewardDebt; // Reward debt. } struct PoolInfo { address protocol; // Address of protocol contract. uint256 totalStaked; // Total staked amount in the pool uint256 allocPoint; // Allocation of protocol - same as totalUsedCover. uint256 accEthPerShare; // Accumulated ETHs per share, times 1e12. uint256 rewardDebt; // Pool Reward debt. } // Total alloc point - sum of totalUsedCover for initialized pools uint256 public totalAllocPoint; // Accumlated ETHs per alloc, times 1e12. uint256 public accEthPerAlloc; // Last reward updated block uint256 public lastRewardBlock; // Reward per block - updates when reward notified uint256 public rewardPerBlock; // Time when all reward will be distributed - updates when reward notified uint256 public rewardCycleEnd; // Currently used reward in cycle - used to calculate remaining reward at the reward notification uint256 public usedReward; // reward cycle period uint256 public rewardCycle; // last reward amount uint256 public lastReward; // Reward info for each protocol mapping(address => PoolInfo) public poolInfo; // Reward info for user in each protocol mapping(address => mapping(address => UserInfo)) public userInfo; /** * @notice Controller immediately initializes contract with this. * @dev - Must set all included variables properly. * - Update last reward block as initialized block. * @param _armorMaster Address of ArmorMaster. * @param _rewardCycleBlocks Block amounts in one cycle. **/ function initialize(address _armorMaster, uint256 _rewardCycleBlocks) external override { initializeModule(_armorMaster); require(_rewardCycleBlocks > 0, "Invalid cycle blocks"); rewardCycle = _rewardCycleBlocks; lastRewardBlock = block.number; } /** * @notice Only BalanceManager can call this function to notify reward. * @dev - Reward must be greater than 0. * - Must update reward info before notify. * - Must contain remaining reward of previous cycle * - Update reward cycle info **/ function notifyRewardAmount() external payable override onlyModule("BALANCE") { require(msg.value > 0, "Invalid reward"); updateReward(); uint256 remainingReward = lastReward > usedReward ? lastReward.sub(usedReward) : 0; lastReward = msg.value.add(remainingReward); usedReward = 0; rewardCycleEnd = block.number.add(rewardCycle); rewardPerBlock = lastReward.div(rewardCycle); } /** * @notice Update RewardManagerV2 reward information. * @dev - Skip if already updated. * - Skip if totalAllocPoint is zero or reward not notified yet. **/ function updateReward() public { if (block.number <= lastRewardBlock || rewardCycleEnd <= lastRewardBlock) { return; } if (rewardCycleEnd == 0 || totalAllocPoint == 0) { lastRewardBlock = block.number; return; } uint256 reward = Math .min(rewardCycleEnd, block.number) .sub(lastRewardBlock) .mul(rewardPerBlock); usedReward = usedReward.add(reward); accEthPerAlloc = accEthPerAlloc.add( reward.mul(1e12).div(totalAllocPoint) ); lastRewardBlock = block.number; } /** * @notice Only Plan and Stake manager can call this function. * @dev - Must update reward info before initialize pool. * - Cannot initlize again. * - Must update pool rewardDebt and totalAllocPoint. * @param _protocol Protocol address. **/ function initPool(address _protocol) public override onlyModules("PLAN", "STAKE") { require(_protocol != address(0), "zero address!"); PoolInfo storage pool = poolInfo[_protocol]; require(pool.protocol == address(0), "already initialized"); updateReward(); pool.protocol = _protocol; pool.allocPoint = IPlanManager(_master.getModule("PLAN")) .totalUsedCover(_protocol); totalAllocPoint = totalAllocPoint.add(pool.allocPoint); pool.rewardDebt = pool.allocPoint.mul(accEthPerAlloc).div(1e12); } /** * @notice Update alloc point when totalUsedCover updates. * @dev - Only Plan Manager can call this function. * - Init pool if not initialized. * @param _protocol Protocol address. * @param _allocPoint New allocPoint. **/ function updateAllocPoint(address _protocol, uint256 _allocPoint) external override onlyModule("PLAN") { PoolInfo storage pool = poolInfo[_protocol]; if (poolInfo[_protocol].protocol == address(0)) { initPool(_protocol); } else { updatePool(_protocol); totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add( _allocPoint ); pool.allocPoint = _allocPoint; pool.rewardDebt = pool.allocPoint.mul(accEthPerAlloc).div(1e12); } } /** * @notice StakeManager call this function to deposit for user. * @dev - Must update pool info * - Must give pending reward to user. * - Emit `BalanceAdded` event. * @param _user User address. * @param _protocol Protocol address. * @param _amount Stake amount. * @param _nftId NftId. **/ function deposit( address _user, address _protocol, uint256 _amount, uint256 _nftId ) external override onlyModule("STAKE") { PoolInfo storage pool = poolInfo[_protocol]; UserInfo storage user = userInfo[_protocol][_user]; if (pool.protocol == address(0)) { initPool(_protocol); } else { updatePool(_protocol); if (user.amount > 0) { uint256 pending = user .amount .mul(pool.accEthPerShare) .div(1e12) .sub(user.rewardDebt); safeRewardTransfer(_user, _protocol, pending); } } user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accEthPerShare).div(1e12); pool.totalStaked = pool.totalStaked.add(_amount); emit BalanceAdded( _user, _protocol, _nftId, _amount, pool.totalStaked, block.timestamp ); } /** * @notice StakeManager call this function to withdraw for user. * @dev - Must update pool info * - Must give pending reward to user. * - Emit `BalanceWithdrawn` event. * @param _user User address. * @param _protocol Protocol address. * @param _amount Withdraw amount. * @param _nftId NftId. **/ function withdraw( address _user, address _protocol, uint256 _amount, uint256 _nftId ) public override onlyModule("STAKE") { PoolInfo storage pool = poolInfo[_protocol]; UserInfo storage user = userInfo[_protocol][_user]; require(user.amount >= _amount, "insufficient to withdraw"); updatePool(_protocol); uint256 pending = user.amount.mul(pool.accEthPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { safeRewardTransfer(_user, _protocol, pending); } user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accEthPerShare).div(1e12); pool.totalStaked = pool.totalStaked.sub(_amount); emit BalanceWithdrawn( _user, _protocol, _nftId, _amount, pool.totalStaked, block.timestamp ); } /** * @notice Claim pending reward. * @dev - Must update pool info * - Emit `RewardPaid` event. * @param _protocol Protocol address. **/ function claimReward(address _protocol) public { PoolInfo storage pool = poolInfo[_protocol]; UserInfo storage user = userInfo[_protocol][msg.sender]; updatePool(_protocol); uint256 pending = user.amount.mul(pool.accEthPerShare).div(1e12).sub( user.rewardDebt ); user.rewardDebt = user.amount.mul(pool.accEthPerShare).div(1e12); if (pending > 0) { safeRewardTransfer(msg.sender, _protocol, pending); } } /** * @notice Claim pending reward of several protocols. * @dev - Must update pool info of each protocol * - Emit `RewardPaid` event per protocol. * @param _protocols Array of protocol addresses. **/ function claimRewardInBatch(address[] calldata _protocols) external { for (uint256 i = 0; i < _protocols.length; i += 1) { claimReward(_protocols[i]); } } /** * @notice Update pool info. * @dev - Skip if already updated. * - Skip if totalStaked is zero. * @param _protocol Protocol address. **/ function updatePool(address _protocol) public { PoolInfo storage pool = poolInfo[_protocol]; if (block.number <= lastRewardBlock) { return; } if (pool.totalStaked == 0) { return; } updateReward(); uint256 poolReward = pool.allocPoint.mul(accEthPerAlloc).div(1e12).sub( pool.rewardDebt ); pool.accEthPerShare = pool.accEthPerShare.add( poolReward.mul(1e12).div(pool.totalStaked) ); pool.rewardDebt = pool.allocPoint.mul(accEthPerAlloc).div(1e12); } /** * @notice Check contract balance to avoid tx failure. **/ function safeRewardTransfer(address _to, address _protocol, uint256 _amount) internal { uint256 reward = Math.min(address(this).balance, _amount); payable(_to).transfer(reward); emit RewardPaid(_to, _protocol, reward, block.timestamp); } /** * @notice Get pending reward amount. * @param _user User address. * @param _protocol Protocol address. * @return pending reward amount **/ function getPendingReward(address _user, address _protocol) public view returns (uint256) { if (rewardCycleEnd == 0 || totalAllocPoint == 0) { return 0; } uint256 reward = Math .min(rewardCycleEnd, block.number) .sub(lastRewardBlock) .mul(rewardPerBlock); uint256 _accEthPerAlloc = accEthPerAlloc.add( reward.mul(1e12).div(totalAllocPoint) ); PoolInfo memory pool = poolInfo[_protocol]; if (pool.protocol == address(0) || pool.totalStaked == 0) { return 0; } uint256 poolReward = pool.allocPoint.mul(_accEthPerAlloc).div(1e12).sub( pool.rewardDebt ); uint256 _accEthPerShare = pool.accEthPerShare.add( poolReward.mul(1e12).div(pool.totalStaked) ); UserInfo memory user = userInfo[_protocol][_user]; return user.amount.mul(_accEthPerShare).div(1e12).sub(user.rewardDebt); } /** * @notice Get pending total reward amount for several protocols. * @param _user User address. * @param _protocols Array of protocol addresses. * @return pending reward amount **/ function getTotalPendingReward(address _user, address[] memory _protocols) external view returns (uint256) { uint256 reward; for (uint256 i = 0; i < _protocols.length; i += 1) { reward = reward.add(getPendingReward(_user, _protocols[i])); } return reward; } }
Transfers control of the contract to a newOwner. newOwner The address to transfer ownership to./
function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private __gap;
24,220
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "./IPool.sol"; import "./ModaAware.sol"; import "./ModaCorePool.sol"; import "./EscrowedModaERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "abdk-libraries-solidity/ABDKMath64x64.sol"; /** * @title Moda Pool Factory * * @notice Moda Pool Factory manages Moda Yield farming pools, provides a single * public interface to access the pools, provides an interface for the pools * to mint yield rewards, access pool-related info, update weights, etc. * * @notice The factory is authorized (via its owner) to register new pools, change weights * of the existing pools, removing the pools (by changing their weights to zero) * * @dev The factory requires ROLE_TOKEN_CREATOR permission on the Moda token to mint yield * (see `mintYieldTo` function) * * @author Kevin Brown, based on Illuvium Pool Factory Contract by Pedro Bergamini, reviewed by Basil Gorin */ contract ModaPoolFactory is Ownable, ModaAware { // @dev FACTORY_UID defined to add another check to ensure compliance with the contract. function FACTORY_UID() public pure returns (uint256) { return ModaConstants.FACTORY_UID; } /// @dev Auxiliary data structure used only in getPoolData() view function struct PoolData { // @dev pool token address (like Moda, or an LP token) address poolToken; // @dev pool address (like deployed core pool instance) address poolAddress; // @dev pool weight (200 for Moda pools, 800 for Moda/ETH pools - set during deployment) uint32 weight; // @dev flash pool flag bool isFlashPool; } /** * @dev Moda/second determines yield farming reward base * used by the yield pools controlled by the factory */ uint256 public initialModaPerSecond; /** * @dev The yield is distributed proportionally to pool weights; * total weight is here to help in determining the proportion */ uint32 public totalWeight; /** * @dev Moda/second decreases by 3% every period; * updates are lazy calculated via a compound interest function. */ uint32 public immutable secondsPerUpdate; /** * @dev Start timestamp is when the pool starts. */ uint public startTimestamp; /** * @dev End timestamp is the last time when Moda/second can be decreased; * it is implied that yield farming stops after that block */ uint public endTimestamp; /// @dev Maps pool token address (like Moda) -> pool address (like core pool instance) mapping(address => address) public pools; /// @dev Keeps track of registered pool addresses, maps pool address -> exists flag mapping(address => bool) public poolExists; /** * @dev Fired in createPool() and registerPool() * * @param _by an address which executed an action * @param poolToken pool token address (like Moda or a Moda / ETH LP token) * @param poolAddress deployed pool instance address * @param weight pool weight * @param isFlashPool flag indicating if pool is a flash pool */ event PoolRegistered( address indexed _by, address indexed poolToken, address indexed poolAddress, uint64 weight, bool isFlashPool ); /** * @dev Fired in changePoolWeight() * * @param _by an address which executed an action * @param poolAddress deployed pool instance address * @param weight new pool weight */ event WeightUpdated(address indexed _by, address indexed poolAddress, uint32 weight); /** * @dev Creates/deploys a factory instance * * @param _moda Moda ERC20 token address * @param _modaPerSecond initial Moda/second value for rewards * @param _secondsPerUpdate how frequently the rewards gets updated (decreased by 3%), blocks * @param _startTimestamp timestamp to measure _secondsPerUpdate from * @param _endTimestamp timestamp when farming stops and rewards cannot be updated anymore */ constructor( address _moda, uint192 _modaPerSecond, uint32 _secondsPerUpdate, uint32 _startTimestamp, uint32 _endTimestamp ) ModaAware(_moda) { // verify the inputs are set require(_modaPerSecond > 0, "Moda/second not set"); require(_secondsPerUpdate > 0, "seconds/update not set"); require(_startTimestamp > 0, "start timestamp not set"); require(_endTimestamp > _startTimestamp, "invalid end timestamp: must be greater than init timestamp"); // save the inputs into internal state variables initialModaPerSecond = _modaPerSecond; secondsPerUpdate = _secondsPerUpdate; startTimestamp = _startTimestamp; endTimestamp = _endTimestamp; } /** * @notice Given a pool token retrieves corresponding pool address * * @dev A shortcut for `pools` mapping * * @param poolToken pool token address (like Moda) to query pool address for * @return pool address for the token specified */ function getPoolAddress(address poolToken) external view returns (address) { // read the mapping and return return pools[poolToken]; } /** * @notice Reads pool information for the pool defined by its pool token address, * designed to simplify integration with the front ends * * @param _poolToken pool token address to query pool information for * @return pool information packed in a PoolData struct */ function getPoolData(address _poolToken) public view returns (PoolData memory) { // get the pool address from the mapping address poolAddr = pools[_poolToken]; // throw if there is no pool registered for the token specified require(poolAddr != address(0), "pool not found"); // read pool information from the pool smart contract // via the pool interface (IPool) address poolToken = IPool(poolAddr).poolToken(); bool isFlashPool = IPool(poolAddr).isFlashPool(); uint32 weight = IPool(poolAddr).weight(); // create the in-memory structure and return it return PoolData({ poolToken: poolToken, poolAddress: poolAddr, weight: weight, isFlashPool: isFlashPool }); } /** * @dev Creates a core pool (ModaCorePool) and registers it within the factory * * @dev Can be executed by the pool factory owner only * * @param poolStartTimestamp init timestamp to be used for the pool creation time * @param weight weight of the pool to be created */ function createCorePool( uint256 poolStartTimestamp, uint32 weight ) external virtual onlyOwner { // create/deploy new core pool instance IPool pool = new ModaCorePool( moda, address(this), address(0), moda, weight, poolStartTimestamp ); // register it within this factory registerPool(address(pool)); } /** * @dev Registers an already deployed pool instance within the factory * * @dev Can be executed by the pool factory owner only * * @param poolAddr address of the already deployed pool instance */ function registerPool(address poolAddr) public onlyOwner { // read pool information from the pool smart contract // via the pool interface (IPool) address poolToken = IPool(poolAddr).poolToken(); bool isFlashPool = IPool(poolAddr).isFlashPool(); uint32 weight = IPool(poolAddr).weight(); // ensure that the pool is not already registered within the factory require(pools[poolToken] == address(0), "this pool is already registered"); // create pool structure, register it within the factory pools[poolToken] = poolAddr; poolExists[poolAddr] = true; // update total pool weight of the factory totalWeight += weight; // emit an event emit PoolRegistered(msg.sender, poolToken, poolAddr, weight, isFlashPool); } /** * @notice Calculates compound interest */ function compound(uint principal, uint periods) public pure returns (uint) { return ABDKMath64x64.mulu( // Rate is -3% per period, e.g. 97/100. ABDKMath64x64.pow(ABDKMath64x64.div(97, 100), periods), principal ); } /** * @notice Calculates the effective moda per second at a future timestamp. */ function modaPerSecondAt(uint time) public view returns (uint256) { // If we're before the start, just return initial. if (time < startTimestamp) return initialModaPerSecond; // If we're at the end, we don't continue to decrease. if (time > endTimestamp) time = endTimestamp; // How many times do we need to decrease the rewards // between the last time we've calculated and now? uint periods = (time - startTimestamp) / secondsPerUpdate; // Calculate the resulting amount after applying that many decreases. return compound(initialModaPerSecond, periods); } /** * @dev Mints Moda tokens; executed by Moda Pool only * * @dev Requires factory to have ROLE_TOKEN_CREATOR permission * on the Moda ERC20 token instance * * @param _to an address to mint tokens to * @param _amount amount of Moda tokens to mint */ function mintYieldTo(address _to, uint256 _amount) external { // verify that sender is a pool registered withing the factory require(poolExists[msg.sender], "pool is not registered with this factory"); // mint Moda tokens as required mintModa(_to, _amount); } /** * @dev Changes the weight of the pool; * executed by the pool itself or by the factory owner * * @param poolAddr address of the pool to change weight for * @param weight new weight value to set to */ function changePoolWeight(address poolAddr, uint32 weight) external { // verify function is executed either by factory owner or by the pool itself require(msg.sender == owner() || poolExists[msg.sender]); // recalculate total weight totalWeight = totalWeight + weight - IPool(poolAddr).weight(); // set the new pool weight IPool(poolAddr).setWeight(weight); // emit an event emit WeightUpdated(msg.sender, poolAddr, weight); } }
Calculates the effective moda per second at a future timestamp./ If we're before the start, just return initial. If we're at the end, we don't continue to decrease. How many times do we need to decrease the rewards between the last time we've calculated and now? Calculate the resulting amount after applying that many decreases.
function modaPerSecondAt(uint time) public view returns (uint256) { if (time < startTimestamp) return initialModaPerSecond; if (time > endTimestamp) time = endTimestamp; uint periods = (time - startTimestamp) / secondsPerUpdate; return compound(initialModaPerSecond, periods); }
15,806,351
//Address: 0x9df10486168cb25278c7ec72a3090e34f7aac29a //Contract name: GPowerToken //Balance: 0 Ether //Verification Date: 1/11/2018 //Transacion Count: 5 // CODE STARTS HERE pragma solidity ^0.4.18; //*** Owner ***// contract owned { address public owner; //*** OwnershipTransferred ***// event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function owned() public { owner = msg.sender; } //*** Change Owner ***// function changeOwner(address newOwner) onlyOwner public { owner = newOwner; } //*** Transfer OwnerShip ***// function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } //*** Only Owner ***// modifier onlyOwner { require(msg.sender == owner); _; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } //*** GraphenePowerToken ***// contract GPowerToken is owned{ //************** Token ************// string public standard = 'Token 1'; string public name = 'GPower'; string public symbol = 'GRP'; uint8 public decimals = 18; uint256 public totalSupply =0; //*** Pre-sale ***// uint preSaleStart=1513771200; uint preSaleEnd=1515585600; uint256 preSaleTotalTokens=30000000; uint256 preSaleTokenCost=6000; address preSaleAddress; bool public enablePreSale=false; //*** ICO ***// uint icoStart; uint256 icoSaleTotalTokens=400000000; address icoAddress; bool public enableIco=false; //*** Advisers,Consultants ***// uint256 advisersConsultantTokens=15000000; address advisersConsultantsAddress; //*** Bounty ***// uint256 bountyTokens=15000000; address bountyAddress; //*** Founders ***// uint256 founderTokens=40000000; address founderAddress; //*** Walet ***// address public wallet; //*** TranferCoin ***// bool public transfersEnabled = false; bool public stopSale=false; uint256 newCourceSale=0; //*** Balance ***// mapping (address => uint256) public balanceOf; mapping (address => uint256) public balanceOfPreSale; //*** Alowed ***// mapping (address => mapping (address => uint256)) allowed; //*** Tranfer ***// event Transfer(address from, address to, uint256 value); //*** Approval ***// event Approval(address indexed _owner, address indexed _spender, uint256 _value); //*** Destruction ***// event Destruction(uint256 _amount); //*** Burn ***// event Burn(address indexed from, uint256 value); //*** Issuance ***// event Issuance(uint256 _amount); function GPowerToken() public{ preSaleAddress=0xC07850969A0EC345A84289f9C5bb5F979f27110f; icoAddress=0x1C21Cf57BF4e2dd28883eE68C03a9725056D29F1; advisersConsultantsAddress=0xe8B6dA1B801b7F57e3061C1c53a011b31C9315C7; bountyAddress=0xD53E82Aea770feED8e57433D3D61674caEC1D1Be; founderAddress=0xDA0D3Dad39165EA2d7386f18F96664Ee2e9FD8db; totalSupply =(500000000*1000000000000000000); } //*** Payable ***// function() payable public { require(msg.value>0); require(msg.sender != 0x0); if(!stopSale){ uint256 weiAmount; uint256 tokens; wallet=owner; if(newCourceSale>0){ weiAmount=newCourceSale; } if(isPreSale()){ wallet=preSaleAddress; weiAmount=6000; } else if(isIco()){ wallet=icoAddress; if((icoStart+(7*24*60*60)) >= now){ weiAmount=4000; } else if((icoStart+(14*24*60*60)) >= now){ weiAmount=3750; } else if((icoStart+(21*24*60*60)) >= now){ weiAmount=3500; } else if((icoStart+(28*24*60*60)) >= now){ weiAmount=3250; } else if((icoStart+(35*24*60*60)) >= now){ weiAmount=3000; } else{ weiAmount=2000; } } else{ weiAmount=4000; } tokens=msg.value*weiAmount/1000000000000000000; Transfer(this, msg.sender, tokens*1000000000000000000); balanceOf[msg.sender]+=tokens*1000000000000000000; totalSupply-=tokens*1000000000000000000; wallet.transfer(msg.value); } else{ require(0>1); } } /* Send coins */ function transfer(address _to, uint256 _value) public returns (bool success) { if(transfersEnabled || msg.sender==owner){ require(balanceOf[msg.sender] >= _value*1000000000000000000); // Subtract from the sender balanceOf[msg.sender]-= _value*1000000000000000000; balanceOf[_to] += _value*1000000000000000000; Transfer(msg.sender, _to, _value*1000000000000000000); return true; } else{ return false; } } //*** Transfer From ***// function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if(transfersEnabled || msg.sender==owner){ // Check if the sender has enough require(balanceOf[_from] >= _value*1000000000000000000); // Check allowed // Subtract from the sender balanceOf[_from] -= _value*1000000000000000000; // Add the same to the recipient balanceOf[_to] += _value*1000000000000000000; Transfer(_from, _to, _value*1000000000000000000); return true; } else{ return false; } } //*** Transfer OnlyOwner ***// function transferOwner(address _to,uint256 _value) public onlyOwner returns(bool success){ // Subtract from the sender totalSupply-=_value*1000000000000000000; // Add the same to the recipient balanceOf[_to] = (balanceOf[_to] + _value*1000000000000000000); Transfer(this, _to, _value*1000000000000000000); return true; } function transferArrayBalanceForPreSale(address[] addrs,uint256[] values) public onlyOwner returns(bool result){ for(uint i=0;i<addrs.length;i++){ transfer(addrs[i],values[i]*1000000000000000000); } return true; } function transferBalanceForPreSale(address addrs,uint256 value) public onlyOwner returns(bool result){ transfer(addrs,value*1000000000000000000); return true; } //*** Burn Owner***// function burnOwner(uint256 _value) public onlyOwner returns (bool success) { destroyOwner(msg.sender, _value*1000000000000000000); Burn(msg.sender, _value*1000000000000000000); return true; } //*** Destroy Owner ***// function destroyOwner(address _from, uint256 _amount) public onlyOwner{ balanceOf[_from] =(balanceOf[_from] - _amount*1000000000000000000); totalSupply = (totalSupply - _amount*1000000000000000000); Transfer(_from, this, _amount*1000000000000000000); Destruction(_amount*1000000000000000000); } //*** Kill Balance ***// function killTotalSupply() onlyOwner public { totalSupply=0; } //*** Get Balance for owner(tranfer for sale) ***// function GetBalanceOwnerForTransfer(uint256 value) onlyOwner public{ require(msg.sender==owner); if(totalSupply>=value*1000000000000000000){ balanceOf[this]-= value*1000000000000000000; balanceOf[owner] += value*1000000000000000000; totalSupply-=value*1000000000000000000; Transfer(this,owner,value*1000000000000000000); } } //*** Kill Tokens For GPower***// function killTokensForGPower() onlyOwner public{ if(bountyTokens>0){ Transfer(this,bountyAddress,bountyTokens*1000000000000000000); Transfer(this,founderAddress,founderTokens*1000000000000000000); Transfer(this,advisersConsultantsAddress,advisersConsultantTokens*1000000000000000000); balanceOf[bountyAddress]+=(bountyTokens*1000000000000000000); balanceOf[founderAddress]+=(founderTokens*1000000000000000000); balanceOf[advisersConsultantsAddress]+=advisersConsultantTokens*1000000000000000000; totalSupply-=((bountyTokens+founderTokens+advisersConsultantTokens)*1000000000000000000); bountyTokens=0; founderTokens=0; advisersConsultantTokens=0; } } //*** Contract Balance ***// function contractBalance() constant public returns (uint256 balance) { return balanceOf[this]; } //*** Set Params For Sale ***// function setParamsStopSale(bool _value) public onlyOwner{ stopSale=_value; } //*** Set ParamsTransfer ***// function setParamsTransfer(bool _value) public onlyOwner{ transfersEnabled=_value; } //*** Set ParamsICO ***// function setParamsIco(bool _value) public onlyOwner returns(bool result){ enableIco=_value; return true; } //*** Set ParamsPreSale ***// function setParamsPreSale(bool _value) public onlyOwner returns(bool result){ enablePreSale=_value; return true; } //*** Set CourceSale ***// function setCourceSale(uint256 value) public onlyOwner{ newCourceSale=value; } //*** Is ico ***// function isIco() constant public returns (bool ico) { bool result=((icoStart+(35*24*60*60)) >= now); if(enableIco){ return true; } else{ return result; } } //*** Is PreSale ***// function isPreSale() constant public returns (bool preSale) { bool result=(preSaleEnd >= now); if(enablePreSale){ return true; } else{ return result; } } }
Set Params For Sale
function setParamsStopSale(bool _value) public onlyOwner{ stopSale=_value; }
12,662,264
pragma solidity ^0.4.24; contract RSEvents { // 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 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 genAmount ); // 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 genAmount ); // 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 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 ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract modularGoalbonanzaPlus is RSEvents {} contract GoalbonanzaPlus is modularGoalbonanzaPlus { using SafeMath for *; using NameFilter for string; using RSKeysCalc for uint256; GoalbonanzaInterfaceForForwarder constant private TeamGoalbonanza = GoalbonanzaInterfaceForForwarder(0xffcbd472aa93a45f2f9e61945b2b190d0795317b); GoalbonanzaBookInterface constant private GoalbonanzaBook = GoalbonanzaBookInterface(0x0376a6E256DD4B2419973964fCd5d3CB49B53Aef); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "GoalbonanzaPlus Multiple Rounds"; string constant public symbol = "GB+"; uint256 private rndGap_ = 0; // TODO: check time uint256 constant private rndInit_ = 30 minutes; // 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_ = 30 minutes; // 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 //**************** 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 => RSdatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => RSdatasets.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 => RSdatasets.Round) public round_; // (rID => data) round data //**************** // TEAM FEE DATA //**************** uint256 public fees_ = 50; // fee distribution uint256 public potSplit_ = 45; // pot split distribution //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (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"); _; } /** * @dev prevents contracts from interacting with GoalbonanzaPlus */ modifier isHuman() { address _addr = msg.sender; require (_addr == tx.origin); 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, "too little money"); require(_eth <= 100000000000000000000000, "too much money"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (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 RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, _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 */ function buyXid(uint256 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.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; } // buy core buyCore(_pID, _affCode, _eventData_); } function buyXaddr(address _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.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; } } // buy core buyCore(_pID, _affID, _eventData_); } function buyXname(bytes32 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.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; } } // buy core buyCore(_pID, _affID, _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 _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data RSdatasets.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; } // reload core reLoadCore(_pID, _affCode, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data RSdatasets.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; } } // reload core reLoadCore(_pID, _affID, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data RSdatasets.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; } } // reload core reLoadCore(_pID, _affID, _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 RSdatasets.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 RSEvents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _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 RSEvents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = GoalbonanzaBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = GoalbonanzaBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = GoalbonanzaBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, 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 + rndGap_ && (_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 + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).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_)) / 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 total keys * @return time ends * @return time started * @return current pot * @return current player ID in lead * @return current player in leads address * @return current player in leads name * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].keys, //0 round_[_rID].end, //1 round_[_rID].strt, //2 round_[_rID].pot, //3 (round_[_rID].plyr * 10), //6 check here plyr_[round_[_rID].plyr].addr, //5 plyr_[round_[_rID].plyr].name, //6 airDropTracker_ + (airDropPot_ * 1000) //7 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- * @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, RSdatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _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 RSEvents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _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 _eth, RSdatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_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, _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 RSEvents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _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, RSdatasets.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) > 10000000000000000000) { uint256 _availableLimit = (10000000000000000000).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; // 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 1 prize was won _eventData_.compressedData += 100000000000000000000000000000000; } // 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); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _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 _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 + rndGap_ && (_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 + rndGap_ && (_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(GoalbonanzaBook), "only GoalbonanzaBook can call this function"); 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(GoalbonanzaBook), "only GoalbonanzaBook can call this function"); 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(RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of GoalbonanzaPlus if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = GoalbonanzaBook.getPlayerID(msg.sender); bytes32 _name = GoalbonanzaBook.getPlayerName(_pID); uint256 _laff = GoalbonanzaBook.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 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, RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.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(RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; // grab our pot amount // add airdrop pot into the final pot 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(45)) / 100; uint256 _com = (_pot / 10); uint256 _gen = (_pot.mul(potSplit_)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)); // 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 = _com.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards if (!address(TeamGoalbonanza).call.value(_com)(bytes4(keccak256("deposit()")))) { _gen = _gen.add(_com); _com = 0; } // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); 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, RSdatasets.EventReturns memory _eventData_) private returns(RSdatasets.EventReturns) { // pay 15% out to community rewards uint256 _com = _eth * 15 / 100; // 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 RSEvents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { // no affiliates, add to community _com += _aff; } if (!address(TeamGoalbonanza).call.value(_com)(bytes4(keccak256("deposit()")))) { // This ensures TeamGoalbonanza cannot influence the outcome // bank migrations by breaking outgoing transactions. } return(_eventData_); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _keys, RSdatasets.EventReturns memory _eventData_) private returns(RSdatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 1000); airDropPot_ = airDropPot_.add(_air); // calculate pot (24.9%) uint256 _pot = (_eth.mul(249) / 1000); // 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 _eth, uint256 _keys, RSdatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit RSEvents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _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 owner can activate // TODO: set owner require( (msg.sender == 0xcd0fce8d255349092496f131f2900df25f0569f8), "only owner can activate" ); // can only be ran once require(activated_ == false, "GoalbonanzaPlus already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now - rndGap_; round_[1].end = now + rndInit_; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library RSdatasets { //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 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 } struct Round { uint256 plyr; // pID of player 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 } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library RSKeysCalc { 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 GoalbonanzaInterfaceForForwarder { function deposit() external payable returns(bool); } interface GoalbonanzaBookInterface { 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); } 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 * - 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)); } }
withdraws all of your earnings. -functionhash- 0x3ccfd60b/ setup local rID grab time fetch player ID setup temp var for player eth check to see if round has ended and no one has run round end yet set up our tx event data end the round (distributes pot) get their earnings gib moni build event data fire withdraw and distribute event in any other situation get their earnings gib moni fire withdraw event
function withdraw() isActivated() isHuman() public { uint256 _rID = rID_; uint256 _now = now; uint256 _pID = pIDxAddr_[msg.sender]; uint256 _eth; if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { RSdatasets.EventReturns memory _eventData_; round_[_rID].ended = true; _eventData_ = endRound(_eventData_); _eth = withdrawEarnings(_pID); if (_eth > 0) plyr_[_pID].addr.transfer(_eth); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit RSEvents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); _eth = withdrawEarnings(_pID); if (_eth > 0) plyr_[_pID].addr.transfer(_eth); emit RSEvents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } }
12,171,687
pragma solidity ^0.5.0; // Copyright 2019 OpenST Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ---------------------------------------------------------------------------- // // http://www.simpletoken.org/ // // ---------------------------------------------------------------------------- import "../utilitytoken/contracts/organization/contracts/Organized.sol"; import "./StakerProxy.sol"; import "./EIP20GatewayInterface.sol"; import "../lib/EIP20Interface.sol"; import "../lib/Mutex.sol"; /** * @title OSTComposer implements Organized contract. Reentrancy is prevented * by using Mutex contract. * * @notice It facilitates the staker to get the OSTPrime on sidechains. */ contract OSTComposer is Organized, Mutex { /* Constants */ bytes32 constant public STAKEREQUEST_INTENT_TYPEHASH = keccak256( abi.encode( "StakeRequest(uint256 amount,address beneficiary,uint256 gasPrice,uint256 gasLimit,uint256 nonce,address staker,address gateway)" ) ); /* Events */ /** Emitted whenever a request stake is called. */ event StakeRequested( uint256 amount, address beneficiary, uint256 gasPrice, uint256 gasLimit, uint256 nonce, address indexed staker, address stakerProxy, address gateway, bytes32 stakeRequestHash ); /** Emitted whenever a revoke stake is called. */ event StakeRevoked( address indexed staker, bytes32 stakeRequestHash ); /** Emitted whenever a reject stake is called. */ event StakeRejected( address indexed staker, bytes32 stakeRequestHash ); /* Public Variables */ /* Mapping of staker to gateway to store stake request hash. */ mapping (address => mapping(address => bytes32)) public stakeRequestHashes; /* Mapping of staker addresses to their StakerProxy. */ mapping (address => StakerProxy) public stakerProxies; /* Stores boolean based on stake request hash. */ mapping (bytes32 => bool) public stakeRequests; /* Private Variables */ /** Domain separator encoding per EIP 712. */ bytes32 private constant EIP712_DOMAIN_TYPEHASH = keccak256( "EIP712Domain(address verifyingContract)" ); /** Domain separator per EIP 712. */ bytes32 private DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, address(this) ) ); /* Modifiers */ /** Requires that caller is valid proxy address. */ modifier onlyStakerProxy(address _owner) { StakerProxy stakerProxy = stakerProxies[_owner]; require( address(stakerProxy) == msg.sender, "Caller is invalid proxy address." ); _; } /* Special Functions */ /** * @notice Contract constructor. * * @param _organization Address of an organization contract. */ constructor( OrganizationInterface _organization ) Organized(_organization) public { } /* External Functions */ /** * @notice Staker calls the method to show its intention of staking. In order * to stake, the staked amount must first be transferred to * OSTComposer. Staker should approve OSTComposer for token * transfer. * * @param _amount Amount that is to be staked. * @param _beneficiary The address in the auxiliary chain where the utility * tokens will be minted. * @param _gasPrice Gas price that staker is ready to pay to get the stake * and mint process done. * @param _gasLimit Gas limit that staker is ready to pay. * @param _nonce Staker nonce specific to gateway. * @param _gateway Address of the gateway to stake. * * @return stakeRequestHash_ A unique hash for stake request. */ function requestStake( uint256 _amount, address _beneficiary, uint256 _gasPrice, uint256 _gasLimit, uint256 _nonce, EIP20GatewayInterface _gateway ) external mutex returns (bytes32 stakeRequestHash_) { require( _amount > uint256(0), "Stake amount must not be zero." ); require( _beneficiary != address(0), "Beneficiary address must not be zero." ); require( stakeRequestHashes[msg.sender][address(_gateway)] == bytes32(0), "Request for this staker at this gateway is already in process." ); stakeRequestHash_ = hashStakeRequest( _amount, _beneficiary, _gasPrice, _gasLimit, _nonce, msg.sender, address(_gateway) ); stakeRequestHashes[msg.sender][address(_gateway)] = stakeRequestHash_; StakerProxy stakerProxy = stakerProxies[msg.sender]; if(address(stakerProxy) == address(0)) { stakerProxy = new StakerProxy(msg.sender); stakerProxies[msg.sender] = stakerProxy; } require( _gateway.getNonce(address(stakerProxy)) == _nonce, "Incorrect staker nonce." ); stakeRequests[stakeRequestHash_] = true; EIP20Interface valueToken = _gateway.token(); require( valueToken.transferFrom(msg.sender, address(this), _amount), "Value token transfer returned false." ); emit StakeRequested( _amount, _beneficiary, _gasPrice, _gasLimit, _nonce, msg.sender, address(stakerProxy), address(_gateway), stakeRequestHash_ ); } /** * @notice Facilitator calls the method to initiate the stake process. * Staked amount from composer and bounty amount from facilitator * is then transferred to the StakerProxy contract of the staker. * * @param _amount Amount that is to be staked. * @param _beneficiary The address in the auxiliary chain where the utility * tokens will be minted. * @param _gasPrice Gas price that staker is ready to pay to get the stake * and mint process done. * @param _gasLimit Gas limit that staker is ready to pay. * @param _nonce Staker nonce specific to gateway. * @param _staker StakerProxy contract address of staker. * @param _gateway Address of the gateway to stake. * @param _hashLock Hashlock provided by the facilitator. * * @return messageHash_ Hash unique for each request. */ function acceptStakeRequest( uint256 _amount, address _beneficiary, uint256 _gasPrice, uint256 _gasLimit, uint256 _nonce, address _staker, EIP20GatewayInterface _gateway, bytes32 _hashLock ) external onlyWorker returns(bytes32 messageHash_) { StakerProxy stakerProxy = stakerProxies[_staker]; require( address(stakerProxy) != address(0), "StakerProxy address is null." ); bytes32 stakeRequestHash = hashStakeRequest( _amount, _beneficiary, _gasPrice, _gasLimit, _nonce, _staker, address(_gateway) ); require( stakeRequests[stakeRequestHash], "Stake request must exists." ); delete stakeRequestHashes[_staker][address(_gateway)]; delete stakeRequests[stakeRequestHash]; EIP20Interface valueToken = _gateway.token(); require( valueToken.transfer(address(stakerProxy), _amount), "Staked amount must be transferred to the staker proxy." ); EIP20Interface baseToken = _gateway.baseToken(); uint256 bounty = _gateway.bounty(); require( baseToken.transferFrom(msg.sender, address(stakerProxy), bounty), "Bounty amount must be transferred to stakerProxy." ); messageHash_ = stakerProxy.stake( _amount, _beneficiary, _gasPrice, _gasLimit, _nonce, _hashLock, _gateway ); } /** * @notice It can only be called by Staker of the stake request. It deletes the * previously requested stake request. * * @param _amount Amount that is to be staked. * @param _beneficiary The address in the auxiliary chain where the utility * tokens will be minted. * @param _gasPrice Gas price that staker is ready to pay to get the stake * and mint process done. * @param _gasLimit Gas limit that staker is ready to pay. * @param _nonce Staker nonce specific to gateway. * @param _gateway Address of the gateway to stake. */ function revokeStakeRequest( uint256 _amount, address _beneficiary, uint256 _gasPrice, uint256 _gasLimit, uint256 _nonce, EIP20GatewayInterface _gateway ) external { address staker = msg.sender; bytes32 stakeRequestHash = hashStakeRequest( _amount, _beneficiary, _gasPrice, _gasLimit, _nonce, staker, address(_gateway) ); require( stakeRequests[stakeRequestHash], "Only valid staker can revoke the stake request." ); removeStakeRequest(staker, _amount, _gateway, stakeRequestHash); emit StakeRevoked(staker, stakeRequestHash); } /** * @notice It can only be called by Facilitator. It deletes the previously * requested stake request. * * @param _amount Amount that is to be staked. * @param _beneficiary The address in the auxiliary chain where the utility * tokens will be minted. * @param _gasPrice Gas price that staker is ready to pay to get the stake * and mint process done. * @param _gasLimit Gas limit that staker is ready to pay. * @param _nonce Staker nonce specific to gateway. * @param _staker StakerProxy contract address of staker. * @param _gateway Address of the gateway to stake. */ function rejectStakeRequest( uint256 _amount, address _beneficiary, uint256 _gasPrice, uint256 _gasLimit, uint256 _nonce, address _staker, EIP20GatewayInterface _gateway ) external onlyWorker { bytes32 stakeRequestHash = hashStakeRequest( _amount, _beneficiary, _gasPrice, _gasLimit, _nonce, _staker, address(_gateway) ); require( stakeRequests[stakeRequestHash], "Invalid stake request hash." ); removeStakeRequest(_staker, _amount, _gateway, stakeRequestHash); emit StakeRejected(_staker, stakeRequestHash); } /** * @notice It can only be called by owner of the staker proxy. It * deletes the StakerProxy contract of the staker and calls self * destruct on StakerProxy contract. */ function destructStakerProxy() external { StakerProxy stakerProxy = stakerProxies[msg.sender]; require( address(stakerProxy) != address(0), "Staker proxy does not exist for the caller." ); // Resetting the proxy address of the staker. delete stakerProxies[msg.sender]; stakerProxy.selfDestruct(); } /* Private Functions */ /** * @notice It is used by revokeStakeRequest and removeStakeRequest methods. * It transfers the value tokens to staker and deletes * `stakeRequestHashes` storage references. * * @param _staker StakerProxy contract address of staker. * @param _amount Amount that is to be staked. * @param _gateway Address of the gateway to stake. * @param _stakeRequestHash Stake request intent hash. */ function removeStakeRequest( address _staker, uint256 _amount, EIP20GatewayInterface _gateway, bytes32 _stakeRequestHash ) private { delete stakeRequestHashes[_staker][address(_gateway)]; delete stakeRequests[_stakeRequestHash]; EIP20Interface valueToken = _gateway.token(); require( valueToken.transfer(_staker, _amount), "Staked amount must be transferred to staker." ); } /** * @notice It returns hashing of stake request as per EIP-712. * * @dev Hashing of stakeRequest should confirm with EIP-712. * As specified by EIP 712, it requires * - an initial byte * - the version byte for structured data * - the domain separator * - hash obtained from params * * See: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md */ function hashStakeRequest( uint256 _amount, address _beneficiary, uint256 _gasPrice, uint256 _gasLimit, uint256 _nonce, address _staker, address _gateway ) private view returns(bytes32 stakeRequestIntentHash_) { bytes32 hash = keccak256( abi.encodePacked( STAKEREQUEST_INTENT_TYPEHASH, _amount, _beneficiary, _gasPrice, _gasLimit, _nonce, _staker, _gateway )); // See: https://github.com/ethereum/EIPs/blob/master/assets/eip-712/Example.sol stakeRequestIntentHash_ = keccak256( abi.encodePacked( byte(0x19), // the initial 0x19 byte byte(0x01), // the version byte for structured data DOMAIN_SEPARATOR, hash ) ); } }
Facilitator calls the method to initiate the stake process. Staked amount from composer and bounty amount from facilitator is then transferred to the StakerProxy contract of the staker. _amount Amount that is to be staked. _beneficiary The address in the auxiliary chain where the utility tokens will be minted. _gasPrice Gas price that staker is ready to pay to get the stake and mint process done. _gasLimit Gas limit that staker is ready to pay. _nonce Staker nonce specific to gateway. _staker StakerProxy contract address of staker. _gateway Address of the gateway to stake. _hashLock Hashlock provided by the facilitator. return messageHash_ Hash unique for each request./
function acceptStakeRequest( uint256 _amount, address _beneficiary, uint256 _gasPrice, uint256 _gasLimit, uint256 _nonce, address _staker, EIP20GatewayInterface _gateway, bytes32 _hashLock ) external onlyWorker returns(bytes32 messageHash_) { StakerProxy stakerProxy = stakerProxies[_staker]; require( address(stakerProxy) != address(0), "StakerProxy address is null." ); bytes32 stakeRequestHash = hashStakeRequest( _amount, _beneficiary, _gasPrice, _gasLimit, _nonce, _staker, address(_gateway) ); require( stakeRequests[stakeRequestHash], "Stake request must exists." ); delete stakeRequestHashes[_staker][address(_gateway)]; delete stakeRequests[stakeRequestHash]; EIP20Interface valueToken = _gateway.token(); require( valueToken.transfer(address(stakerProxy), _amount), "Staked amount must be transferred to the staker proxy." ); EIP20Interface baseToken = _gateway.baseToken(); uint256 bounty = _gateway.bounty(); require( baseToken.transferFrom(msg.sender, address(stakerProxy), bounty), "Bounty amount must be transferred to stakerProxy." ); messageHash_ = stakerProxy.stake( _amount, _beneficiary, _gasPrice, _gasLimit, _nonce, _hashLock, _gateway ); }
12,962,256
pragma solidity ^0.4.25; pragma experimental ABIEncoderV2; /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Modifiable * @notice A contract with basic modifiers */ contract Modifiable { // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier notNullAddress(address _address) { require(_address != address(0)); _; } modifier notThisAddress(address _address) { require(_address != address(this)); _; } modifier notNullOrThisAddress(address _address) { require(_address != address(0)); require(_address != address(this)); _; } modifier notSameAddresses(address _address1, address _address2) { if (_address1 != _address2) _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title SelfDestructible * @notice Contract that allows for self-destruction */ contract SelfDestructible { // // Variables // ----------------------------------------------------------------------------------------------------------------- bool public selfDestructionDisabled; // // Events // ----------------------------------------------------------------------------------------------------------------- event SelfDestructionDisabledEvent(address wallet); event TriggerSelfDestructionEvent(address wallet); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the address of the destructor role function destructor() public view returns (address); /// @notice Disable self-destruction of this contract /// @dev This operation can not be undone function disableSelfDestruction() public { // Require that sender is the assigned destructor require(destructor() == msg.sender); // Disable self-destruction selfDestructionDisabled = true; // Emit event emit SelfDestructionDisabledEvent(msg.sender); } /// @notice Destroy this contract function triggerSelfDestruction() public { // Require that sender is the assigned destructor require(destructor() == msg.sender); // Require that self-destruction has not been disabled require(!selfDestructionDisabled); // Emit event emit TriggerSelfDestructionEvent(msg.sender); // Self-destruct and reward destructor selfdestruct(msg.sender); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Ownable * @notice A modifiable that has ownership roles */ contract Ownable is Modifiable, SelfDestructible { // // Variables // ----------------------------------------------------------------------------------------------------------------- address public deployer; address public operator; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetDeployerEvent(address oldDeployer, address newDeployer); event SetOperatorEvent(address oldOperator, address newOperator); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address _deployer) internal notNullOrThisAddress(_deployer) { deployer = _deployer; operator = _deployer; } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Return the address that is able to initiate self-destruction function destructor() public view returns (address) { return deployer; } /// @notice Set the deployer of this contract /// @param newDeployer The address of the new deployer function setDeployer(address newDeployer) public onlyDeployer notNullOrThisAddress(newDeployer) { if (newDeployer != deployer) { // Set new deployer address oldDeployer = deployer; deployer = newDeployer; // Emit event emit SetDeployerEvent(oldDeployer, newDeployer); } } /// @notice Set the operator of this contract /// @param newOperator The address of the new operator function setOperator(address newOperator) public onlyOperator notNullOrThisAddress(newOperator) { if (newOperator != operator) { // Set new operator address oldOperator = operator; operator = newOperator; // Emit event emit SetOperatorEvent(oldOperator, newOperator); } } /// @notice Gauge whether message sender is deployer or not /// @return true if msg.sender is deployer, else false function isDeployer() internal view returns (bool) { return msg.sender == deployer; } /// @notice Gauge whether message sender is operator or not /// @return true if msg.sender is operator, else false function isOperator() internal view returns (bool) { return msg.sender == operator; } /// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on /// on the other hand /// @return true if msg.sender is operator, else false function isDeployerOrOperator() internal view returns (bool) { return isDeployer() || isOperator(); } // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier onlyDeployer() { require(isDeployer()); _; } modifier notDeployer() { require(!isDeployer()); _; } modifier onlyOperator() { require(isOperator()); _; } modifier notOperator() { require(!isOperator()); _; } modifier onlyDeployerOrOperator() { require(isDeployerOrOperator()); _; } modifier notDeployerOrOperator() { require(!isDeployerOrOperator()); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Servable * @notice An ownable that contains registered services and their actions */ contract Servable is Ownable { // // Types // ----------------------------------------------------------------------------------------------------------------- struct ServiceInfo { bool registered; uint256 activationTimestamp; mapping(bytes32 => bool) actionsEnabledMap; bytes32[] actionsList; } // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(address => ServiceInfo) internal registeredServicesMap; uint256 public serviceActivationTimeout; // // Events // ----------------------------------------------------------------------------------------------------------------- event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds); event RegisterServiceEvent(address service); event RegisterServiceDeferredEvent(address service, uint256 timeout); event DeregisterServiceEvent(address service); event EnableServiceActionEvent(address service, string action); event DisableServiceActionEvent(address service, string action); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the service activation timeout /// @param timeoutInSeconds The set timeout in unit of seconds function setServiceActivationTimeout(uint256 timeoutInSeconds) public onlyDeployer { serviceActivationTimeout = timeoutInSeconds; // Emit event emit ServiceActivationTimeoutEvent(timeoutInSeconds); } /// @notice Register a service contract whose activation is immediate /// @param service The address of the service contract to be registered function registerService(address service) public onlyDeployer notNullOrThisAddress(service) { _registerService(service, 0); // Emit event emit RegisterServiceEvent(service); } /// @notice Register a service contract whose activation is deferred by the service activation timeout /// @param service The address of the service contract to be registered function registerServiceDeferred(address service) public onlyDeployer notNullOrThisAddress(service) { _registerService(service, serviceActivationTimeout); // Emit event emit RegisterServiceDeferredEvent(service, serviceActivationTimeout); } /// @notice Deregister a service contract /// @param service The address of the service contract to be deregistered function deregisterService(address service) public onlyDeployer notNullOrThisAddress(service) { require(registeredServicesMap[service].registered); registeredServicesMap[service].registered = false; // Emit event emit DeregisterServiceEvent(service); } /// @notice Enable a named action in an already registered service contract /// @param service The address of the registered service contract /// @param action The name of the action to be enabled function enableServiceAction(address service, string action) public onlyDeployer notNullOrThisAddress(service) { require(registeredServicesMap[service].registered); bytes32 actionHash = hashString(action); require(!registeredServicesMap[service].actionsEnabledMap[actionHash]); registeredServicesMap[service].actionsEnabledMap[actionHash] = true; registeredServicesMap[service].actionsList.push(actionHash); // Emit event emit EnableServiceActionEvent(service, action); } /// @notice Enable a named action in a service contract /// @param service The address of the service contract /// @param action The name of the action to be disabled function disableServiceAction(address service, string action) public onlyDeployer notNullOrThisAddress(service) { bytes32 actionHash = hashString(action); require(registeredServicesMap[service].actionsEnabledMap[actionHash]); registeredServicesMap[service].actionsEnabledMap[actionHash] = false; // Emit event emit DisableServiceActionEvent(service, action); } /// @notice Gauge whether a service contract is registered /// @param service The address of the service contract /// @return true if service is registered, else false function isRegisteredService(address service) public view returns (bool) { return registeredServicesMap[service].registered; } /// @notice Gauge whether a service contract is registered and active /// @param service The address of the service contract /// @return true if service is registered and activate, else false function isRegisteredActiveService(address service) public view returns (bool) { return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp; } /// @notice Gauge whether a service contract action is enabled which implies also registered and active /// @param service The address of the service contract /// @param action The name of action function isEnabledServiceAction(address service, string action) public view returns (bool) { bytes32 actionHash = hashString(action); return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash]; } // // Internal functions // ----------------------------------------------------------------------------------------------------------------- function hashString(string _string) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_string)); } // // Private functions // ----------------------------------------------------------------------------------------------------------------- function _registerService(address service, uint256 timeout) private { if (!registeredServicesMap[service].registered) { registeredServicesMap[service].registered = true; registeredServicesMap[service].activationTimestamp = block.timestamp + timeout; } } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier onlyActiveService() { require(isRegisteredActiveService(msg.sender)); _; } modifier onlyEnabledServiceAction(string action) { require(isEnabledServiceAction(msg.sender, action)); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Community vote * @notice An oracle for relevant decisions made by the community. */ contract CommunityVote is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(address => bool) doubleSpenderByWallet; uint256 maxDriipNonce; uint256 maxNullNonce; bool dataAvailable; // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { dataAvailable = true; } // // Results functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the double spender status of given wallet /// @param wallet The wallet address for which to check double spender status /// @return true if wallet is double spender, false otherwise function isDoubleSpenderWallet(address wallet) public view returns (bool) { return doubleSpenderByWallet[wallet]; } /// @notice Get the max driip nonce to be accepted in settlements /// @return the max driip nonce function getMaxDriipNonce() public view returns (uint256) { return maxDriipNonce; } /// @notice Get the max null settlement nonce to be accepted in settlements /// @return the max driip nonce function getMaxNullNonce() public view returns (uint256) { return maxNullNonce; } /// @notice Get the data availability status /// @return true if data is available function isDataAvailable() public view returns (bool) { return dataAvailable; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title CommunityVotable * @notice An ownable that has a community vote property */ contract CommunityVotable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- CommunityVote public communityVote; bool public communityVoteFrozen; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetCommunityVoteEvent(CommunityVote oldCommunityVote, CommunityVote newCommunityVote); event FreezeCommunityVoteEvent(); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the community vote contract /// @param newCommunityVote The (address of) CommunityVote contract instance function setCommunityVote(CommunityVote newCommunityVote) public onlyDeployer notNullAddress(newCommunityVote) notSameAddresses(newCommunityVote, communityVote) { require(!communityVoteFrozen); // Set new community vote CommunityVote oldCommunityVote = communityVote; communityVote = newCommunityVote; // Emit event emit SetCommunityVoteEvent(oldCommunityVote, newCommunityVote); } /// @notice Freeze the community vote from further updates /// @dev This operation can not be undone function freezeCommunityVote() public onlyDeployer { communityVoteFrozen = true; // Emit event emit FreezeCommunityVoteEvent(); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier communityVoteInitialized() { require(communityVote != address(0)); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Beneficiary * @notice A recipient of ethers and tokens */ contract Beneficiary { /// @notice Receive ethers to the given wallet's given balance type /// @param wallet The address of the concerned wallet /// @param balanceType The target balance type of the wallet function receiveEthersTo(address wallet, string balanceType) public payable; /// @notice Receive token to the given wallet's given balance type /// @dev The wallet must approve of the token transfer prior to calling this function /// @param wallet The address of the concerned wallet /// @param balanceType The target balance type of the wallet /// @param amount The amount to deposit /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721") function receiveTokensTo(address wallet, string balanceType, int256 amount, address currencyCt, uint256 currencyId, string standard) public; } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title MonetaryTypesLib * @dev Monetary data types */ library MonetaryTypesLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Currency { address ct; uint256 id; } struct Figure { int256 amount; Currency currency; } struct NoncedAmount { uint256 nonce; int256 amount; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title AccrualBeneficiary * @notice A beneficiary of accruals */ contract AccrualBeneficiary is Beneficiary { // // Functions // ----------------------------------------------------------------------------------------------------------------- event CloseAccrualPeriodEvent(); // // Functions // ----------------------------------------------------------------------------------------------------------------- function closeAccrualPeriod(MonetaryTypesLib.Currency[]) public { emit CloseAccrualPeriodEvent(); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Benefactor * @notice An ownable that contains registered beneficiaries */ contract Benefactor is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- address[] internal beneficiaries; mapping(address => uint256) internal beneficiaryIndexByAddress; // // Events // ----------------------------------------------------------------------------------------------------------------- event RegisterBeneficiaryEvent(address beneficiary); event DeregisterBeneficiaryEvent(address beneficiary); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Register the given beneficiary /// @param beneficiary Address of beneficiary to be registered function registerBeneficiary(address beneficiary) public onlyDeployer notNullAddress(beneficiary) returns (bool) { if (beneficiaryIndexByAddress[beneficiary] > 0) return false; beneficiaries.push(beneficiary); beneficiaryIndexByAddress[beneficiary] = beneficiaries.length; // Emit event emit RegisterBeneficiaryEvent(beneficiary); return true; } /// @notice Deregister the given beneficiary /// @param beneficiary Address of beneficiary to be deregistered function deregisterBeneficiary(address beneficiary) public onlyDeployer notNullAddress(beneficiary) returns (bool) { if (beneficiaryIndexByAddress[beneficiary] == 0) return false; uint256 idx = beneficiaryIndexByAddress[beneficiary] - 1; if (idx < beneficiaries.length - 1) { // Remap the last item in the array to this index beneficiaries[idx] = beneficiaries[beneficiaries.length - 1]; beneficiaryIndexByAddress[beneficiaries[idx]] = idx + 1; } beneficiaries.length--; beneficiaryIndexByAddress[beneficiary] = 0; // Emit event emit DeregisterBeneficiaryEvent(beneficiary); return true; } /// @notice Gauge whether the given address is the one of a registered beneficiary /// @param beneficiary Address of beneficiary /// @return true if beneficiary is registered, else false function isRegisteredBeneficiary(address beneficiary) public view returns (bool) { return beneficiaryIndexByAddress[beneficiary] > 0; } /// @notice Get the count of registered beneficiaries /// @return The count of registered beneficiaries function registeredBeneficiariesCount() public view returns (uint256) { return beneficiaries.length; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library */ /** * @title SafeMathIntLib * @dev Math operations with safety checks that throw on error */ library SafeMathIntLib { int256 constant INT256_MIN = int256((uint256(1) << 255)); int256 constant INT256_MAX = int256(~((uint256(1) << 255))); // //Functions below accept positive and negative integers and result must not overflow. // function div(int256 a, int256 b) internal pure returns (int256) { require(a != INT256_MIN || b != - 1); return a / b; } function mul(int256 a, int256 b) internal pure returns (int256) { require(a != - 1 || b != INT256_MIN); // overflow require(b != - 1 || a != INT256_MIN); // overflow int256 c = a * b; require((b == 0) || (c / b == a)); return c; } function sub(int256 a, int256 b) internal pure returns (int256) { require((b >= 0 && a - b <= a) || (b < 0 && a - b > a)); return a - b; } function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } // //Functions below only accept positive integers and result must be greater or equal to zero too. // function div_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b > 0); return a / b; } function mul_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0); int256 c = a * b; require(a == 0 || c / a == b); require(c >= 0); return c; } function sub_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0 && b <= a); return a - b; } function add_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0); int256 c = a + b; require(c >= a); return c; } // //Conversion and validation functions. // function abs(int256 a) public pure returns (int256) { return a < 0 ? neg(a) : a; } function neg(int256 a) public pure returns (int256) { return mul(a, - 1); } function toNonZeroInt256(uint256 a) public pure returns (int256) { require(a > 0 && a < (uint256(1) << 255)); return int256(a); } function toInt256(uint256 a) public pure returns (int256) { require(a >= 0 && a < (uint256(1) << 255)); return int256(a); } function toUInt256(int256 a) public pure returns (uint256) { require(a >= 0); return uint256(a); } function isNonZeroPositiveInt256(int256 a) public pure returns (bool) { return (a > 0); } function isPositiveInt256(int256 a) public pure returns (bool) { return (a >= 0); } function isNonZeroNegativeInt256(int256 a) public pure returns (bool) { return (a < 0); } function isNegativeInt256(int256 a) public pure returns (bool) { return (a <= 0); } // //Clamping functions. // function clamp(int256 a, int256 min, int256 max) public pure returns (int256) { if (a < min) return min; return (a > max) ? max : a; } function clampMin(int256 a, int256 min) public pure returns (int256) { return (a < min) ? min : a; } function clampMax(int256 a, int256 max) public pure returns (int256) { return (a > max) ? max : a; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library ConstantsLib { // Get the fraction that represents the entirety, equivalent of 100% function PARTS_PER() public pure returns (int256) { return 1e18; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title AccrualBenefactor * @notice A benefactor whose registered beneficiaries obtain a predefined fraction of total amount */ contract AccrualBenefactor is Benefactor { using SafeMathIntLib for int256; // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(address => int256) private _beneficiaryFractionMap; int256 public totalBeneficiaryFraction; // // Events // ----------------------------------------------------------------------------------------------------------------- event RegisterAccrualBeneficiaryEvent(address beneficiary, int256 fraction); event DeregisterAccrualBeneficiaryEvent(address beneficiary); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Register the given beneficiary for the entirety fraction /// @param beneficiary Address of beneficiary to be registered function registerBeneficiary(address beneficiary) public onlyDeployer notNullAddress(beneficiary) returns (bool) { return registerFractionalBeneficiary(beneficiary, ConstantsLib.PARTS_PER()); } /// @notice Register the given beneficiary for the given fraction /// @param beneficiary Address of beneficiary to be registered /// @param fraction Fraction of benefits to be given function registerFractionalBeneficiary(address beneficiary, int256 fraction) public onlyDeployer notNullAddress(beneficiary) returns (bool) { require(fraction > 0); require(totalBeneficiaryFraction.add(fraction) <= ConstantsLib.PARTS_PER()); if (!super.registerBeneficiary(beneficiary)) return false; _beneficiaryFractionMap[beneficiary] = fraction; totalBeneficiaryFraction = totalBeneficiaryFraction.add(fraction); // Emit event emit RegisterAccrualBeneficiaryEvent(beneficiary, fraction); return true; } /// @notice Deregister the given beneficiary /// @param beneficiary Address of beneficiary to be deregistered function deregisterBeneficiary(address beneficiary) public onlyDeployer notNullAddress(beneficiary) returns (bool) { if (!super.deregisterBeneficiary(beneficiary)) return false; totalBeneficiaryFraction = totalBeneficiaryFraction.sub(_beneficiaryFractionMap[beneficiary]); _beneficiaryFractionMap[beneficiary] = 0; // Emit event emit DeregisterAccrualBeneficiaryEvent(beneficiary); return true; } /// @notice Get the fraction of benefits that is granted the given beneficiary /// @param beneficiary Address of beneficiary /// @return The beneficiary's fraction function beneficiaryFraction(address beneficiary) public view returns (int256) { return _beneficiaryFractionMap[beneficiary]; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title TransferController * @notice A base contract to handle transfers of different currency types */ contract TransferController { // // Events // ----------------------------------------------------------------------------------------------------------------- event CurrencyTransferred(address from, address to, uint256 value, address currencyCt, uint256 currencyId); // // Functions // ----------------------------------------------------------------------------------------------------------------- function isFungible() public view returns (bool); /// @notice MUST be called with DELEGATECALL function receive(address from, address to, uint256 value, address currencyCt, uint256 currencyId) public; /// @notice MUST be called with DELEGATECALL function approve(address to, uint256 value, address currencyCt, uint256 currencyId) public; /// @notice MUST be called with DELEGATECALL function dispatch(address from, address to, uint256 value, address currencyCt, uint256 currencyId) public; //---------------------------------------- function getReceiveSignature() public pure returns (bytes4) { return bytes4(keccak256("receive(address,address,uint256,address,uint256)")); } function getApproveSignature() public pure returns (bytes4) { return bytes4(keccak256("approve(address,uint256,address,uint256)")); } function getDispatchSignature() public pure returns (bytes4) { return bytes4(keccak256("dispatch(address,address,uint256,address,uint256)")); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title TransferControllerManager * @notice Handles the management of transfer controllers */ contract TransferControllerManager is Ownable { // // Constants // ----------------------------------------------------------------------------------------------------------------- struct CurrencyInfo { bytes32 standard; bool blacklisted; } // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(bytes32 => address) public registeredTransferControllers; mapping(address => CurrencyInfo) public registeredCurrencies; // // Events // ----------------------------------------------------------------------------------------------------------------- event RegisterTransferControllerEvent(string standard, address controller); event ReassociateTransferControllerEvent(string oldStandard, string newStandard, address controller); event RegisterCurrencyEvent(address currencyCt, string standard); event DeregisterCurrencyEvent(address currencyCt); event BlacklistCurrencyEvent(address currencyCt); event WhitelistCurrencyEvent(address currencyCt); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- function registerTransferController(string standard, address controller) external onlyDeployer notNullAddress(controller) { require(bytes(standard).length > 0); bytes32 standardHash = keccak256(abi.encodePacked(standard)); require(registeredTransferControllers[standardHash] == address(0)); registeredTransferControllers[standardHash] = controller; // Emit event emit RegisterTransferControllerEvent(standard, controller); } function reassociateTransferController(string oldStandard, string newStandard, address controller) external onlyDeployer notNullAddress(controller) { require(bytes(newStandard).length > 0); bytes32 oldStandardHash = keccak256(abi.encodePacked(oldStandard)); bytes32 newStandardHash = keccak256(abi.encodePacked(newStandard)); require(registeredTransferControllers[oldStandardHash] != address(0)); require(registeredTransferControllers[newStandardHash] == address(0)); registeredTransferControllers[newStandardHash] = registeredTransferControllers[oldStandardHash]; registeredTransferControllers[oldStandardHash] = address(0); // Emit event emit ReassociateTransferControllerEvent(oldStandard, newStandard, controller); } function registerCurrency(address currencyCt, string standard) external onlyOperator notNullAddress(currencyCt) { require(bytes(standard).length > 0); bytes32 standardHash = keccak256(abi.encodePacked(standard)); require(registeredCurrencies[currencyCt].standard == bytes32(0)); registeredCurrencies[currencyCt].standard = standardHash; // Emit event emit RegisterCurrencyEvent(currencyCt, standard); } function deregisterCurrency(address currencyCt) external onlyOperator { require(registeredCurrencies[currencyCt].standard != 0); registeredCurrencies[currencyCt].standard = bytes32(0); registeredCurrencies[currencyCt].blacklisted = false; // Emit event emit DeregisterCurrencyEvent(currencyCt); } function blacklistCurrency(address currencyCt) external onlyOperator { require(registeredCurrencies[currencyCt].standard != bytes32(0)); registeredCurrencies[currencyCt].blacklisted = true; // Emit event emit BlacklistCurrencyEvent(currencyCt); } function whitelistCurrency(address currencyCt) external onlyOperator { require(registeredCurrencies[currencyCt].standard != bytes32(0)); registeredCurrencies[currencyCt].blacklisted = false; // Emit event emit WhitelistCurrencyEvent(currencyCt); } /** @notice The provided standard takes priority over assigned interface to currency */ function transferController(address currencyCt, string standard) public view returns (TransferController) { if (bytes(standard).length > 0) { bytes32 standardHash = keccak256(abi.encodePacked(standard)); require(registeredTransferControllers[standardHash] != address(0)); return TransferController(registeredTransferControllers[standardHash]); } require(registeredCurrencies[currencyCt].standard != bytes32(0)); require(!registeredCurrencies[currencyCt].blacklisted); address controllerAddress = registeredTransferControllers[registeredCurrencies[currencyCt].standard]; require(controllerAddress != address(0)); return TransferController(controllerAddress); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title TransferControllerManageable * @notice An ownable with a transfer controller manager */ contract TransferControllerManageable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- TransferControllerManager public transferControllerManager; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetTransferControllerManagerEvent(TransferControllerManager oldTransferControllerManager, TransferControllerManager newTransferControllerManager); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the currency manager contract /// @param newTransferControllerManager The (address of) TransferControllerManager contract instance function setTransferControllerManager(TransferControllerManager newTransferControllerManager) public onlyDeployer notNullAddress(newTransferControllerManager) notSameAddresses(newTransferControllerManager, transferControllerManager) { //set new currency manager TransferControllerManager oldTransferControllerManager = transferControllerManager; transferControllerManager = newTransferControllerManager; // Emit event emit SetTransferControllerManagerEvent(oldTransferControllerManager, newTransferControllerManager); } /// @notice Get the transfer controller of the given currency contract address and standard function transferController(address currencyCt, string standard) internal view returns (TransferController) { return transferControllerManager.transferController(currencyCt, standard); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier transferControllerManagerInitialized() { require(transferControllerManager != address(0)); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library */ /** * @title SafeMathUintLib * @dev Math operations with safety checks that throw on error */ library SafeMathUintLib { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } // //Clamping functions. // function clamp(uint256 a, uint256 min, uint256 max) public pure returns (uint256) { return (a > max) ? max : ((a < min) ? min : a); } function clampMin(uint256 a, uint256 min) public pure returns (uint256) { return (a < min) ? min : a; } function clampMax(uint256 a, uint256 max) public pure returns (uint256) { return (a > max) ? max : a; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library CurrenciesLib { using SafeMathUintLib for uint256; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Currencies { MonetaryTypesLib.Currency[] currencies; mapping(address => mapping(uint256 => uint256)) indexByCurrency; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function add(Currencies storage self, address currencyCt, uint256 currencyId) internal { // Index is 1-based if (0 == self.indexByCurrency[currencyCt][currencyId]) { self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId)); self.indexByCurrency[currencyCt][currencyId] = self.currencies.length; } } function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId) internal { // Index is 1-based uint256 index = self.indexByCurrency[currencyCt][currencyId]; if (0 < index) removeByIndex(self, index - 1); } function removeByIndex(Currencies storage self, uint256 index) internal { require(index < self.currencies.length); address currencyCt = self.currencies[index].ct; uint256 currencyId = self.currencies[index].id; if (index < self.currencies.length - 1) { self.currencies[index] = self.currencies[self.currencies.length - 1]; self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1; } self.currencies.length--; self.indexByCurrency[currencyCt][currencyId] = 0; } function count(Currencies storage self) internal view returns (uint256) { return self.currencies.length; } function has(Currencies storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return 0 != self.indexByCurrency[currencyCt][currencyId]; } function getByIndex(Currencies storage self, uint256 index) internal view returns (MonetaryTypesLib.Currency) { require(index < self.currencies.length); return self.currencies[index]; } function getByIndices(Currencies storage self, uint256 low, uint256 up) internal view returns (MonetaryTypesLib.Currency[]) { require(0 < self.currencies.length); require(low <= up); up = up.clampMax(self.currencies.length - 1); MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1); for (uint256 i = low; i <= up; i++) _currencies[i - low] = self.currencies[i]; return _currencies; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library FungibleBalanceLib { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Record { int256 amount; uint256 blockNumber; } struct Balance { mapping(address => mapping(uint256 => int256)) amountByCurrency; mapping(address => mapping(uint256 => Record[])) recordsByCurrency; CurrenciesLib.Currencies inUseCurrencies; CurrenciesLib.Currencies everUsedCurrencies; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function get(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256) { return self.amountByCurrency[currencyCt][currencyId]; } function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256) { (int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber); return amount; } function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = amount; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function transfer(Balance storage _from, Balance storage _to, int256 amount, address currencyCt, uint256 currencyId) internal { sub(_from, amount, currencyCt, currencyId); add(_to, amount, currencyCt, currencyId); } function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function transfer_nn(Balance storage _from, Balance storage _to, int256 amount, address currencyCt, uint256 currencyId) internal { sub_nn(_from, amount, currencyCt, currencyId); add_nn(_to, amount, currencyCt, currencyId); } function recordsCount(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.recordsByCurrency[currencyCt][currencyId].length; } function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256, uint256) { uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber); return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0); } function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index) internal view returns (int256, uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (0, 0); index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1); Record storage record = self.recordsByCurrency[currencyCt][currencyId][index]; return (record.amount, record.blockNumber); } function lastRecord(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256, uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (0, 0); Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1]; return (record.amount, record.blockNumber); } function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.inUseCurrencies.has(currencyCt, currencyId); } function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.everUsedCurrencies.has(currencyCt, currencyId); } function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId) internal { if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId)) self.inUseCurrencies.removeByCurrency(currencyCt, currencyId); else if (!self.inUseCurrencies.has(currencyCt, currencyId)) { self.inUseCurrencies.add(currencyCt, currencyId); self.everUsedCurrencies.add(currencyCt, currencyId); } } function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return 0; for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--) if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber) return i; return 0; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library TxHistoryLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct AssetEntry { int256 amount; uint256 blockNumber; address currencyCt; //0 for ethers uint256 currencyId; } struct TxHistory { AssetEntry[] deposits; mapping(address => mapping(uint256 => AssetEntry[])) currencyDeposits; AssetEntry[] withdrawals; mapping(address => mapping(uint256 => AssetEntry[])) currencyWithdrawals; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function addDeposit(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId) internal { AssetEntry memory deposit = AssetEntry(amount, block.number, currencyCt, currencyId); self.deposits.push(deposit); self.currencyDeposits[currencyCt][currencyId].push(deposit); } function addWithdrawal(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId) internal { AssetEntry memory withdrawal = AssetEntry(amount, block.number, currencyCt, currencyId); self.withdrawals.push(withdrawal); self.currencyWithdrawals[currencyCt][currencyId].push(withdrawal); } //---- function deposit(TxHistory storage self, uint index) internal view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { require(index < self.deposits.length); amount = self.deposits[index].amount; blockNumber = self.deposits[index].blockNumber; currencyCt = self.deposits[index].currencyCt; currencyId = self.deposits[index].currencyId; } function depositsCount(TxHistory storage self) internal view returns (uint256) { return self.deposits.length; } function currencyDeposit(TxHistory storage self, address currencyCt, uint256 currencyId, uint index) internal view returns (int256 amount, uint256 blockNumber) { require(index < self.currencyDeposits[currencyCt][currencyId].length); amount = self.currencyDeposits[currencyCt][currencyId][index].amount; blockNumber = self.currencyDeposits[currencyCt][currencyId][index].blockNumber; } function currencyDepositsCount(TxHistory storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.currencyDeposits[currencyCt][currencyId].length; } //---- function withdrawal(TxHistory storage self, uint index) internal view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { require(index < self.withdrawals.length); amount = self.withdrawals[index].amount; blockNumber = self.withdrawals[index].blockNumber; currencyCt = self.withdrawals[index].currencyCt; currencyId = self.withdrawals[index].currencyId; } function withdrawalsCount(TxHistory storage self) internal view returns (uint256) { return self.withdrawals.length; } function currencyWithdrawal(TxHistory storage self, address currencyCt, uint256 currencyId, uint index) internal view returns (int256 amount, uint256 blockNumber) { require(index < self.currencyWithdrawals[currencyCt][currencyId].length); amount = self.currencyWithdrawals[currencyCt][currencyId][index].amount; blockNumber = self.currencyWithdrawals[currencyCt][currencyId][index].blockNumber; } function currencyWithdrawalsCount(TxHistory storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.currencyWithdrawals[currencyCt][currencyId].length; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title RevenueFund * @notice The target of all revenue earned in driip settlements and from which accrued revenue is split amongst * accrual beneficiaries. */ contract RevenueFund is Ownable, AccrualBeneficiary, AccrualBenefactor, TransferControllerManageable { using FungibleBalanceLib for FungibleBalanceLib.Balance; using TxHistoryLib for TxHistoryLib.TxHistory; using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; // // Variables // ----------------------------------------------------------------------------------------------------------------- FungibleBalanceLib.Balance periodAccrual; CurrenciesLib.Currencies periodCurrencies; FungibleBalanceLib.Balance aggregateAccrual; CurrenciesLib.Currencies aggregateCurrencies; TxHistoryLib.TxHistory private txHistory; // // Events // ----------------------------------------------------------------------------------------------------------------- event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId); event CloseAccrualPeriodEvent(); event RegisterServiceEvent(address service); event DeregisterServiceEvent(address service); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Fallback function that deposits ethers function() public payable { receiveEthersTo(msg.sender, ""); } /// @notice Receive ethers to /// @param wallet The concerned wallet address function receiveEthersTo(address wallet, string) public payable { int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value); // Add to balances periodAccrual.add(amount, address(0), 0); aggregateAccrual.add(amount, address(0), 0); // Add currency to stores of currencies periodCurrencies.add(address(0), 0); aggregateCurrencies.add(address(0), 0); // Add to transaction history txHistory.addDeposit(amount, address(0), 0); // Emit event emit ReceiveEvent(wallet, amount, address(0), 0); } /// @notice Receive tokens /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokens(string balanceType, int256 amount, address currencyCt, uint256 currencyId, string standard) public { receiveTokensTo(msg.sender, balanceType, amount, currencyCt, currencyId, standard); } /// @notice Receive tokens to /// @param wallet The address of the concerned wallet /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokensTo(address wallet, string, int256 amount, address currencyCt, uint256 currencyId, string standard) public { require(amount.isNonZeroPositiveInt256()); // Execute transfer TransferController controller = transferController(currencyCt, standard); require( address(controller).delegatecall( controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId ) ); // Add to balances periodAccrual.add(amount, currencyCt, currencyId); aggregateAccrual.add(amount, currencyCt, currencyId); // Add currency to stores of currencies periodCurrencies.add(currencyCt, currencyId); aggregateCurrencies.add(currencyCt, currencyId); // Add to transaction history txHistory.addDeposit(amount, currencyCt, currencyId); // Emit event emit ReceiveEvent(wallet, amount, currencyCt, currencyId); } /// @notice Get the period accrual balance of the given currency /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The current period's accrual balance function periodAccrualBalance(address currencyCt, uint256 currencyId) public view returns (int256) { return periodAccrual.get(currencyCt, currencyId); } /// @notice Get the aggregate accrual balance of the given currency, including contribution from the /// current accrual period /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The aggregate accrual balance function aggregateAccrualBalance(address currencyCt, uint256 currencyId) public view returns (int256) { return aggregateAccrual.get(currencyCt, currencyId); } /// @notice Get the count of currencies recorded in the accrual period /// @return The number of currencies in the current accrual period function periodCurrenciesCount() public view returns (uint256) { return periodCurrencies.count(); } /// @notice Get the currencies with indices in the given range that have been recorded in the current accrual period /// @param low The lower currency index /// @param up The upper currency index /// @return The currencies of the given index range in the current accrual period function periodCurrenciesByIndices(uint256 low, uint256 up) public view returns (MonetaryTypesLib.Currency[]) { return periodCurrencies.getByIndices(low, up); } /// @notice Get the count of currencies ever recorded /// @return The number of currencies ever recorded function aggregateCurrenciesCount() public view returns (uint256) { return aggregateCurrencies.count(); } /// @notice Get the currencies with indices in the given range that have ever been recorded /// @param low The lower currency index /// @param up The upper currency index /// @return The currencies of the given index range ever recorded function aggregateCurrenciesByIndices(uint256 low, uint256 up) public view returns (MonetaryTypesLib.Currency[]) { return aggregateCurrencies.getByIndices(low, up); } /// @notice Get the count of deposits /// @return The count of deposits function depositsCount() public view returns (uint256) { return txHistory.depositsCount(); } /// @notice Get the deposit at the given index /// @return The deposit at the given index function deposit(uint index) public view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { return txHistory.deposit(index); } /// @notice Close the current accrual period of the given currencies /// @param currencies The concerned currencies function closeAccrualPeriod(MonetaryTypesLib.Currency[] currencies) public onlyOperator { require(ConstantsLib.PARTS_PER() == totalBeneficiaryFraction); // Execute transfer for (uint256 i = 0; i < currencies.length; i++) { MonetaryTypesLib.Currency memory currency = currencies[i]; int256 remaining = periodAccrual.get(currency.ct, currency.id); if (0 >= remaining) continue; for (uint256 j = 0; j < beneficiaries.length; j++) { address beneficiaryAddress = beneficiaries[j]; if (beneficiaryFraction(beneficiaryAddress) > 0) { int256 transferable = periodAccrual.get(currency.ct, currency.id) .mul(beneficiaryFraction(beneficiaryAddress)) .div(ConstantsLib.PARTS_PER()); if (transferable > remaining) transferable = remaining; if (transferable > 0) { // Transfer ETH to the beneficiary if (currency.ct == address(0)) AccrualBeneficiary(beneficiaryAddress).receiveEthersTo.value(uint256(transferable))(address(0), ""); // Transfer token to the beneficiary else { TransferController controller = transferController(currency.ct, ""); require( address(controller).delegatecall( controller.getApproveSignature(), beneficiaryAddress, uint256(transferable), currency.ct, currency.id ) ); AccrualBeneficiary(beneficiaryAddress).receiveTokensTo(address(0), "", transferable, currency.ct, currency.id, ""); } remaining = remaining.sub(transferable); } } } // Roll over remaining to next accrual period periodAccrual.set(remaining, currency.ct, currency.id); } // Close accrual period of accrual beneficiaries for (j = 0; j < beneficiaries.length; j++) { beneficiaryAddress = beneficiaries[j]; // Require that beneficiary fraction is strictly positive if (0 >= beneficiaryFraction(beneficiaryAddress)) continue; // Close accrual period AccrualBeneficiary(beneficiaryAddress).closeAccrualPeriod(currencies); } // Emit event emit CloseAccrualPeriodEvent(); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title NullSettlementState * @notice Where null settlement state is managed */ contract NullSettlementState is Ownable, Servable, CommunityVotable { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; // // Constants // ----------------------------------------------------------------------------------------------------------------- string constant public SET_MAX_NULL_NONCE_ACTION = "set_max_null_nonce"; string constant public SET_MAX_NONCE_WALLET_CURRENCY_ACTION = "set_max_nonce_wallet_currency"; // // Variables // ----------------------------------------------------------------------------------------------------------------- uint256 public maxNullNonce; mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyMaxNonce; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetMaxNullNonceEvent(uint256 maxNullNonce); event SetMaxNonceByWalletAndCurrencyEvent(address wallet, MonetaryTypesLib.Currency currency, uint256 maxNullNonce); event updateMaxNullNonceFromCommunityVoteEvent(uint256 maxDriipNonce); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the max null nonce /// @param _maxNullNonce The max nonce function setMaxNullNonce(uint256 _maxNullNonce) public onlyEnabledServiceAction(SET_MAX_NULL_NONCE_ACTION) { maxNullNonce = _maxNullNonce; // Emit event emit SetMaxNullNonceEvent(_maxNullNonce); } /// @notice Get the max null nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The max nonce function maxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency currency) public view returns (uint256) { return walletCurrencyMaxNonce[wallet][currency.ct][currency.id]; } /// @notice Set the max null nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @param _maxNullNonce The max nonce function setMaxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency currency, uint256 _maxNullNonce) public onlyEnabledServiceAction(SET_MAX_NONCE_WALLET_CURRENCY_ACTION) { walletCurrencyMaxNonce[wallet][currency.ct][currency.id] = _maxNullNonce; // Emit event emit SetMaxNonceByWalletAndCurrencyEvent(wallet, currency, _maxNullNonce); } /// @notice Update the max null settlement nonce property from CommunityVote contract function updateMaxNullNonceFromCommunityVote() public { uint256 _maxNullNonce = communityVote.getMaxNullNonce(); if (0 == _maxNullNonce) return; maxNullNonce = _maxNullNonce; // Emit event emit updateMaxNullNonceFromCommunityVoteEvent(maxNullNonce); } }
Get the max null nonce of the given wallet and currency wallet The address of the concerned wallet currency The concerned currency return The max nonce
function maxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency currency) public view returns (uint256) { return walletCurrencyMaxNonce[wallet][currency.ct][currency.id]; }
948,958
./partial_match/42/0xC31518D4fbA20E3618F6e7B24D1Bada43837Ed45/sources/GebProxyDebtAuctionActions.sol
Mints protocol tokens for your proxy and then the proxy sends all of its balance to msg.sender coinJoin CoinJoin auctionHouse Auction house address auctionId Auction ID
function settleAuction(address coinJoin, address auctionHouse, uint auctionId) public { DebtAuctionHouseLike debtAuctionHouse = DebtAuctionHouseLike(auctionHouse); debtAuctionHouse.settleAuction(auctionId); claimProxyFunds(address(CoinJoinLike(coinJoin).systemCoin())); claimProxyFunds(debtAuctionHouse.protocolToken()); }
3,338,865
pragma solidity ^0.5.16; import "../CToken.sol"; import "../ErrorReporter.sol"; import "../PriceOracle.sol"; import "../ComptrollerInterface.sol"; import "../Unitroller.sol"; import "./CWComptrollerStorage.sol"; /** * @title CloudWalk's Comptroller Contract * @author Compound (CloudWalk) */ contract CWComptroller is CWComptrollerV4Storage, ComptrollerInterface, ComptrollerErrorReporter, ExponentialNoError { /// @notice Emitted when an admin supports a market event MarketListed(CToken cToken); /// @notice Emitted when an account enters a market event MarketEntered(CToken cToken, address account); /// @notice Emitted when an account exits a market event MarketExited(CToken cToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(CToken cToken, string action, bool pauseState); /// @notice Emitted when borrow cap for a cToken is changed event NewBorrowCap(CToken indexed cToken, uint newBorrowCap); /// @notice Emitted when borrow cap guardian is changed event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian); /// @notice Emitted when market.onlyTrustedSuppliers config is changed event OnlyTrustedSuppliers(CToken indexed cToken, bool state); /// @notice Emitted when market.onlyTrustedBorrowers config is changed event OnlyTrustedBorrowers(CToken indexed cToken, bool state); // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 1.0e18; // 1.0 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, CToken cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) public returns (uint[] memory) { uint len = cTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint(addToMarketInternal(cToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param cToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(cToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration CToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 CToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(cToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[cToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } (bool exists, ) = CToken(cToken).getTrustedSupplier(minter); if (exists) { (Error err, , uint shortfall) = getTrustedSupplierLiquidityInternal(minter, CToken(cToken), mintAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.TRUSTED_SUPPLY_ALLOWANCE_OVERFLOW); } } else if (markets[cToken].onlyTrustedSuppliers) { return uint(Error.UNTRUSTED_SUPPLIER_ACCOUNT); } return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param cToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address cToken, address minter, uint actualMintAmount, uint mintTokens) external { // Shh - currently unused cToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint) { uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } return uint(Error.NO_ERROR); } function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external { // Shh - currently unused cToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { // only cTokens may call borrowAllowed if borrower not in market require(msg.sender == cToken, "sender must be cToken"); // attempt to add borrower to the market Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[cToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint(Error.PRICE_ERROR); } uint borrowCap = borrowCaps[cToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = CToken(cToken).totalBorrows(); uint nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (bool exists, ) = CToken(cToken).getTrustedBorrower(borrower); if (exists) { (Error err, , uint shortfall) = getTrustedBorrowerLiquidityInternal(borrower, CToken(cToken), borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.TRUSTED_BORROW_ALLOWANCE_OVERFLOW); } } else if (markets[cToken].onlyTrustedBorrowers) { return uint(Error.UNTRUSTED_BORROWER_ACCOUNT); } else { (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } } return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param cToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address cToken, address borrower, uint borrowAmount) external { // Shh - currently unused cToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param cToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address cToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external { // Shh - currently unused cToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused liquidator; if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower); uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { // Shh - currently unused cTokenBorrowed; cTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { // Shh - currently unused cTokenCollateral; cTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(cToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } return uint(Error.NO_ERROR); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param cToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer */ function transferVerify(address cToken, address src, address dst, uint transferTokens) external { // Shh - currently unused cToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint cTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Read the balances and exchange rate from the cToken (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); // sumCollateral += tokensToDenom * cTokenBalance vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral); // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa})); denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa})); ratio = div_(numerator, denominator); seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(cToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } cToken.isCToken(); // Sanity check to make sure its really a CToken markets[address(cToken)] = Market({isListed: true, onlyTrustedSuppliers: true, onlyTrustedBorrowers: true, collateralFactorMantissa: 0}); _addMarketInternal(address(cToken)); emit MarketListed(cToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address cToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != CToken(cToken), "market already added"); } allMarkets.push(CToken(cToken)); } /** * @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. * @param cTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(CToken[] calldata cTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps"); uint numMarkets = cTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[address(cTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(cTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Borrow Cap Guardian * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian */ function _setBorrowCapGuardian(address newBorrowCapGuardian) external { require(msg.sender == admin, "only admin can set borrow cap guardian"); // Save current value for inclusion in log address oldBorrowCapGuardian = borrowCapGuardian; // Store borrowCapGuardian with value newBorrowCapGuardian borrowCapGuardian = newBorrowCapGuardian; // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian) emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Mint", state); return state; } function _setBorrowPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); require(unitroller._acceptImplementation() == 0, "change not authorized"); } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == comptrollerImplementation; } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (CToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /*** Trusted Accounts ***/ /** * @notice Determine what the trusted account liquidity would be if the given amount borrowed * @param cToken The market to borrow from * @param account The account to determine liquidity for * @param borrowAmount The amount of underlying token to borrow * @dev Note that liquidity and shortfall are returned as an amount of undelying token * @return (possible error code, account liquidity in excess of allowance, * account shortfall below allowance) */ function getTrustedBorrowerLiquidity(address account, address cToken, uint borrowAmount) external view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getTrustedBorrowerLiquidityInternal(account, CToken(cToken), borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the trusted account liquidity would be if the given amount borrowed * @param cToken The market to borrow from * @param account The account to determine liquidity for * @param borrowAmount The amount of underlying token to borrow * @dev Note that liquidity and shortfall are returned as an amount of undelying token * @return (possible error code, account liquidity in excess of allowance, * account shortfall below allowance) */ function getTrustedBorrowerLiquidityInternal(address account, CToken cToken, uint borrowAmount) internal view returns (Error, uint, uint) { uint oErr; uint borrowBalance; // Read trusted borrower data (bool exists, uint borrowAllowance) = cToken.getTrustedBorrower(account); if (!exists) { return (Error.UNTRUSTED_BORROWER_ACCOUNT, 0, 0); } // Read borrow balance (oErr, , borrowBalance, ) = cToken.getAccountSnapshot(account); if (oErr != 0) { return (Error.SNAPSHOT_ERROR, 0, 0); } borrowBalance = add_(borrowBalance, borrowAmount); // These are safe, as the underflow condition is checked first if (borrowAllowance > borrowBalance) { return (Error.NO_ERROR, borrowAllowance - borrowBalance, 0); } else { return (Error.NO_ERROR, 0, borrowBalance - borrowAllowance); } } /** * @notice Determine what the trusted account liquidity would be if the given amount supplied * @param cToken The market to supply in * @param account The account to determine liquidity for * @param supplyAmount The amount of underlying token to supply * @dev Note that liquidity and shortfall are returned as an amount of undelying token * @return (possible error code, account liquidity in excess of allowance, * account shortfall below allowance) */ function getTrustedSupplierLiquidity(address account, address cToken, uint supplyAmount) external view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getTrustedSupplierLiquidityInternal(account, CToken(cToken), supplyAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amount borrowed * @param cToken The market to borrow from * @param account The account to determine liquidity for * @param supplyAmount The amount of underlying to supply * @dev Note that liquidity and shortfall are returned as an amount of undelying token * @return (possible error code, account liquidity in excess of allowance, * account shortfall below allowance) */ function getTrustedSupplierLiquidityInternal(address account, CToken cToken, uint supplyAmount) internal view returns (Error, uint, uint) { uint oErr; uint supplyBalance; uint exchangeRateMantissa; // Read trusted supplier data (bool exists, uint supplyAllowance) = cToken.getTrustedSupplier(account); if (!exists) { return (Error.UNTRUSTED_SUPPLIER_ACCOUNT, 0, 0); } // Read cToken balance (oErr, supplyBalance, , exchangeRateMantissa) = cToken.getAccountSnapshot(account); if (oErr != 0) { return (Error.SNAPSHOT_ERROR, 0, 0); } supplyBalance = mul_ScalarTruncateAddUInt(Exp({mantissa: exchangeRateMantissa}), supplyBalance, supplyAmount); // These are safe, as the underflow condition is checked first if (supplyAllowance > supplyBalance) { return (Error.NO_ERROR, supplyAllowance - supplyBalance, 0); } else { return (Error.NO_ERROR, 0, supplyBalance - supplyAllowance); } } function _setOnlyTrustedSuppliers(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "market is not listed"); require(msg.sender == admin, "caller is not admin"); markets[address(cToken)].onlyTrustedSuppliers = state; emit OnlyTrustedSuppliers(cToken, state); return state; } function _setOnlyTrustedBorrowers(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "market is not listed"); require(msg.sender == admin, "caller is not admin"); markets[address(cToken)].onlyTrustedBorrowers = state; emit OnlyTrustedBorrowers(cToken, state); return state; } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./InterestRateModel.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the comptroller uint err = _setComptroller(comptroller_); require(err == uint(Error.NO_ERROR), "setting comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint srcTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); // unused function // comptroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "balance could not be calculated"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { uint cTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calculate block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr)); } (mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED"); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ // unused function // comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ // unused function // comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0); } /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ // unused function // comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = cTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount); require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens); /* We call the defense hook */ // unused function // comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ // unused function // comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "add reserves unexpected overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } /*** Trsuted Accounts ***/ function getTrustedSupplier(address account) external view returns (bool, uint) { TrustedAccount memory supplier = trustedSuppliers[account]; return (supplier.exists, supplier.allowance); } function getTrustedBorrower(address account) external view returns (bool, uint) { TrustedAccount memory borrower = trustedBorrowers[account]; return (borrower.exists, borrower.allowance); } function getTrustedAdmin(address account) external view returns (bool) { return trustedAdmins[account]; } function _setTrustedSupplier(address account, bool exists, uint supplyAllowance) external returns (uint) { if (msg.sender != admin && !trustedAdmins[msg.sender]) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_TRUSTED_SUPPLIER_ADMIN_CHECK); } TrustedAccount storage supplier = trustedSuppliers[account]; emit TrustedSupplier(account, supplier.exists, supplier.allowance, exists, supplyAllowance); supplier.allowance = supplyAllowance; supplier.exists = exists; return uint(Error.NO_ERROR); } function _setTrustedBorrower(address account, bool exists, uint borrowAllowance) external returns (uint) { if (msg.sender != admin && !trustedAdmins[msg.sender]) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_TRUSTED_BORROWER_ADMIN_CHECK); } TrustedAccount storage borrower = trustedBorrowers[account]; emit TrustedBorrower(account, borrower.exists, borrower.allowance, exists, borrowAllowance); borrower.allowance = borrowAllowance; borrower.exists = exists; return uint(Error.NO_ERROR); } function _setTrustedAdmin(address account, bool enabled) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_TRUSTED_ADMIN_ACCOUNT_ADMIN_CHECK); } trustedAdmins[account] = enabled; emit TrustedAdmin(account, enabled); return uint(Error.NO_ERROR); } } pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY, UNTRUSTED_SUPPLIER_ACCOUNT, UNTRUSTED_BORROWER_ACCOUNT, TRUSTED_SUPPLY_ALLOWANCE_OVERFLOW, TRUSTED_BORROW_ALLOWANCE_OVERFLOW } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE, SET_TRUSTED_SUPPLIER_ADMIN_CHECK, SET_TRUSTED_BORROWER_ADMIN_CHECK, TRUSTED_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, SET_TRUSTED_ADMIN_ACCOUNT_ADMIN_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } pragma solidity ^0.5.16; import "./CToken.sol"; contract PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CToken cToken) external view returns (uint); } pragma solidity ^0.5.16; contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function exitMarket(address cToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint); function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint); function borrowVerify(address cToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify( address cToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address cToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint repayAmount) external view returns (uint, uint); } pragma solidity ^0.5.16; import "./ErrorReporter.sol"; import "./ComptrollerStorage.sol"; /** * @title ComptrollerCore * @dev Storage for the comptroller is at this address, while execution is delegated to the `comptrollerImplementation`. * CTokens should reference this contract as their comptroller. */ contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter { /** * @notice Emitted when pendingComptrollerImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); constructor() public { // Set admin to caller admin = msg.sender; } /*** Admin Functions ***/ function _setPendingImplementation(address newPendingImplementation) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK); } address oldPendingImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint(Error.NO_ERROR); } /** * @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptImplementation() public returns (uint) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = comptrollerImplementation; address oldPendingImplementation = pendingComptrollerImplementation; comptrollerImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = address(0); emit NewImplementation(oldImplementation, comptrollerImplementation); emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint(Error.NO_ERROR); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ function () payable external { // delegate all other functions to current implementation (bool success, ) = comptrollerImplementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } } pragma solidity ^0.5.16; import "../CToken.sol"; import "../ComptrollerStorage.sol"; contract CWComptrollerV2Storage is ComptrollerV1Storage { struct Market { /// @notice Whether or not this market is listed bool isListed; /// @notice Determines if only trusted suppliers allowed bool onlyTrustedSuppliers; /// @notice Determines if only trusted borrowers allowed bool onlyTrustedBorrowers; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract CWComptrollerV3Storage is CWComptrollerV2Storage { /// @notice A list of all markets CToken[] public allMarkets; } contract CWComptrollerV4Storage is CWComptrollerV3Storage { // @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; // @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint) public borrowCaps; } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; import "./EIP20NonStandardInterface.sol"; contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.005% / block) */ uint internal constant borrowRateMaxMantissa = 0.005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; /** * @notice Container for trusted account information */ struct TrustedAccount { uint allowance; bool exists; } /** * @notice Trusted suppliers mapping */ mapping(address => TrustedAccount) internal trustedSuppliers; /** * @notice Trusted borrowers mapping */ mapping(address => TrustedAccount) internal trustedBorrowers; /** * @notice Trusted admins mapping */ mapping(address => bool) internal trustedAdmins; } contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /** * @notice Event emitted when trusted supplier is configured */ event TrustedSupplier(address indexed account, bool oldExists, uint oldAllowance, bool newExists, uint newAllowance); /** * @notice Event emitted when trusted borrower is configured */ event TrustedBorrower(address indexed account, bool oldExists, uint oldAllowance, bool newExists, uint newAllowance); /** * @notice Event emitted when trusted admin is configured */ event TrustedAdmin(address indexed account, bool enabled); /*** User Interface ***/ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setComptroller(ComptrollerInterface newComptroller) public returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); /*** Trusted Functions ***/ function getTrustedAdmin(address account) external view returns (bool); function getTrustedSupplier(address account) external view returns (bool, uint); function getTrustedBorrower(address account) external view returns (bool, uint); function _setTrustedAdmin(address account, bool enabled) external returns (uint); function _setTrustedSupplier(address account, bool exists, uint supplyAllowance) external returns (uint); function _setTrustedBorrower(address account, bool exists, uint borrowAllowance) external returns (uint); } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; } contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); function sweepToken(EIP20NonStandardInterface token) external; /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); } contract CDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract CDelegatorInterface is CDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } contract CDelegateInterface is CDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } pragma solidity ^0.5.16; import "./CarefulMath.sol"; import "./ExponentialNoError.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @dev Legacy contract for compatibility reasons with existing contracts that still use MathError * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath, ExponentialNoError { /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } } pragma solidity ^0.5.16; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title Compound's InterestRateModel Interface * @author Compound */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } pragma solidity ^0.5.16; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.5.16; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract ExponentialNoError { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./PriceOracle.sol"; contract UnitrollerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of Unitroller */ address public comptrollerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingComptrollerImplementation; } contract ComptrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint public liquidationIncentiveMantissa; /** * @notice Max number of assets a single account can participate in (borrow or use as collateral) */ uint public maxAssets; /** * @notice Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => CToken[]) public accountAssets; } contract ComptrollerV2Storage is ComptrollerV1Storage { struct Market { /// @notice Whether or not this market is listed bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; /// @notice Whether or not this market receives COMP bool isComped; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract ComptrollerV3Storage is ComptrollerV2Storage { struct CompMarketState { /// @notice The market's last updated compBorrowIndex or compSupplyIndex uint224 index; /// @notice The block number the index was last updated at uint32 block; } /// @notice A list of all markets CToken[] public allMarkets; /// @notice The rate at which the flywheel distributes COMP, per block uint public compRate; /// @notice The portion of compRate that each market currently receives mapping(address => uint) public compSpeeds; /// @notice The COMP market supply state for each market mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP market borrow state for each market mapping(address => CompMarketState) public compBorrowState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compSupplierIndex; /// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compBorrowerIndex; /// @notice The COMP accrued but not yet transferred to each user mapping(address => uint) public compAccrued; } contract ComptrollerV4Storage is ComptrollerV3Storage { // @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; // @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint) public borrowCaps; } contract ComptrollerV5Storage is ComptrollerV4Storage { /// @notice The portion of COMP that each contributor receives per block mapping(address => uint) public compContributorSpeeds; /// @notice Last block at which a contributor's COMP rewards have been allocated mapping(address => uint) public lastContributorBlock; }
Checks if the account should be allowed to borrow the underlying asset of the given market cToken The market to verify the borrow against borrower The account which would borrow the asset borrowAmount The amount of underlying the account would borrow return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)/ Pausing is a very serious situation - we revert to sound the alarms only cTokens may call borrowAllowed if borrower not in market attempt to add borrower to the market Borrow cap of 0 corresponds to unlimited borrowing
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) { require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { require(msg.sender == cToken, "sender must be cToken"); Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint(Error.PRICE_ERROR); } uint borrowCap = borrowCaps[cToken]; if (borrowCap != 0) { uint totalBorrows = CToken(cToken).totalBorrows(); uint nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (bool exists, ) = CToken(cToken).getTrustedBorrower(borrower); if (exists) { (Error err, , uint shortfall) = getTrustedBorrowerLiquidityInternal(borrower, CToken(cToken), borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.TRUSTED_BORROW_ALLOWANCE_OVERFLOW); } return uint(Error.UNTRUSTED_BORROWER_ACCOUNT); (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } } return uint(Error.NO_ERROR); }
14,523,832
pragma solidity 0.4.25; import "./SafeMath.sol"; import "./IToken.sol"; import "./ISettings.sol"; import "./ITBoxManager.sol"; import "./IOracle.sol"; /// @title BondService contract BondService { using SafeMath for uint256; /// @notice The address of the admin account. address public admin; // The amount of Ether received from the commissions of the system. uint256 private systemETH; // Commission percentage charged from the issuer uint256 public issuerFee; // Commission percentage charged from the holder uint256 public holderFee; // The percentage divider uint256 public divider = 100000; // The minimum deposit amount uint256 public minEther; // The settings contract address ISettings public settings; /// @dev An array containing the Bond struct for all Bonds in existence. The ID /// of each Bond is actually an index into this array. Bond[] public bonds; /// @dev The main Bond struct. Every Bond is represented by a copy /// of this structure. struct Bond { // The address of the issuer of the Bond address issuer; // The address of the holder of the Bond address holder; // The Ether amount packed in the Bond uint256 deposit; // The collateral percentage uint256 percent; // The number of TMV tokens withdrawn to holder uint256 tmv; // The expiration time in seconds uint256 expiration; // The percentage of the holder commission fee uint256 yearFee; // The percentage of the system commission fee uint256 sysFee; // The TBox ID created inside the Bond uint256 tBoxId; // The timestamp of the Bond creation // Sets at the matching moment uint256 createdAt; } /// @dev The BondCreated event is fired whenever a new Bond comes into existence. event BondCreated(uint256 id, address who, uint256 deposit, uint256 percent, uint256 expiration, uint256 yearFee); /// @dev The BondChanged event is fired whenever a Bond changing. event BondChanged(uint256 id, uint256 deposit, uint256 percent, uint256 expiration, uint256 yearFee, address who); /// @dev The BondClosed event is fired whenever a Bond is closed. event BondClosed(uint256 id, address who); /// @dev The BondMatched event is fired whenever a Bond is matched. event BondMatched(uint256 id, address who, uint256 tBox, uint256 tmv, uint256 sysFee, address counteragent); /// @dev The BondFinished event is fired whenever a Bond is finished. event BondFinished(uint256 id, address issuer, address holder); /// @dev The BondExpired event is fired whenever a Bond is expired. event BondExpired(uint256 id, address issuer, address holder); event BondHolderFeeUpdated(uint256 _value); event BondIssuerFeeUpdated(uint256 _value); event BondMinEtherUpdated(uint256 _value); event IssuerRightsTransferred(address indexed from, address indexed to, uint indexed id); event HolderRightsTransferred(address indexed from, address indexed to, uint indexed id); /// @dev Defends against front-running attacks. modifier validTx() { require(tx.gasprice <= settings.gasPriceLimit(), "Gas price is greater than allowed"); _; } /// @dev Access modifier for admin-only functionality. modifier onlyAdmin() { require(admin == msg.sender, "You have no access"); _; } /// @dev Access modifier for issuer-only functionality. /// @param _id A Bond ID. modifier onlyIssuer(uint256 _id) { require(bonds[_id].issuer == msg.sender, "You are not the issuer"); _; } /// @dev Access modifier for holder-only functionality. /// @param _id A Bond ID. modifier onlyHolder(uint256 _id) { require(bonds[_id].holder == msg.sender, "You are not the holder"); _; } /// @dev Access modifier for single-owner-only functionality. /// @param _id A Bond ID. modifier singleOwner(uint256 _id) { bool _a = bonds[_id].issuer == msg.sender && bonds[_id].holder == address(0); bool _b = bonds[_id].holder == msg.sender && bonds[_id].issuer == address(0); require(_a || _b, "You are not the single owner"); _; } /// @dev Modifier to allow actions only when the bond is issuer's request /// @param _id A Bond ID. modifier issueRequest(uint256 _id) { require(bonds[_id].issuer != address(0) && bonds[_id].holder == address(0), "The bond isn't an emit request"); _; } /// @dev Modifier to allow actions only when the bond is holder's request /// @param _id A Bond ID. modifier buyRequest(uint256 _id) { require(bonds[_id].holder != address(0) && bonds[_id].issuer == address(0), "The bond isn't a buy request"); _; } /// @dev Modifier to allow actions only when the bond is matched /// @param _id A Bond ID. modifier matched(uint256 _id) { require(bonds[_id].issuer != address(0) && bonds[_id].holder != address(0), "Bond isn't matched"); _; } /// @notice Settings address can't be changed later. /// @dev The contract constructor sets the original `admin` of the contract to the sender // account and sets the settings contract with provided address. /// @param _settings The address of the settings contract. constructor(ISettings _settings) public { admin = msg.sender; settings = _settings; issuerFee = 500; // 0.5% emit BondIssuerFeeUpdated(issuerFee); holderFee = 10000; // 10% emit BondHolderFeeUpdated(holderFee); minEther = 0.1 ether; emit BondMinEtherUpdated(minEther); } /// @dev Creates issuer request. /// @param _percent The collateral percentage. /// @param _expiration The expiration in seconds. /// @param _yearFee The percentage of the commission. /// @return New Bond ID. function leverage(uint256 _percent, uint256 _expiration, uint256 _yearFee) public payable returns (uint256) { require(msg.value >= minEther, "Too small funds"); require(_percent >= ITBoxManager(settings.tBoxManager()).withdrawPercent(msg.value), "Collateralization is not enough"); require(_expiration >= 1 days && _expiration <= 365 days, "Expiration out of range"); require(_yearFee <= 25000, "Fee out of range"); return createBond(msg.sender, address(0), _percent, _expiration, _yearFee); } /// @dev Creates holder request. /// @param _expiration The expiration in seconds. /// @param _yearFee The percentage of the commission. /// @return New Bond ID. function exchange(uint256 _expiration, uint256 _yearFee) public payable returns (uint256) { require(msg.value >= minEther, "Too small funds"); require(_expiration >= 1 days && _expiration <= 365 days, "Expiration out of range"); require(_yearFee <= 25000, "Fee out of range"); return createBond(address(0), msg.sender, 0, _expiration, _yearFee); } /// @dev Creates Bond request. /// @param _issuer The address of the issuer. /// @param _holder The address of the holder. /// @param _percent The collateral percentage. /// @param _expiration The expiration in seconds. /// @param _yearFee The percentage of the commission. /// @return New Bond ID. function createBond( address _issuer, address _holder, uint256 _percent, uint256 _expiration, uint256 _yearFee ) internal returns(uint256) { Bond memory _bond = Bond( _issuer, _holder, msg.value, _percent, 0, _expiration, _yearFee, 0, 0, 0 ); uint256 _id = bonds.push(_bond).sub(1); emit BondCreated(_id, msg.sender, msg.value, _percent, _expiration, _yearFee); return _id; } /// @dev Closes the bond. /// @param _id A Bond ID. function close(uint256 _id) external singleOwner(_id) { uint256 _eth = bonds[_id].deposit; delete bonds[_id]; msg.sender.transfer(_eth); emit BondClosed(_id, msg.sender); } /// @dev Changes the issuer request. /// @param _id A Bond ID. /// @param _deposit The collateral amount. /// @param _percent The collateral percentage. /// @param _expiration The expiration in seconds. /// @param _yearFee The percentage of the commission. function issuerChange(uint256 _id, uint256 _deposit, uint256 _percent, uint256 _expiration, uint256 _yearFee) external payable singleOwner(_id) onlyIssuer(_id) { changeDeposit(_id, _deposit); changePercent(_id, _percent); changeExpiration(_id, _expiration); changeYearFee(_id, _yearFee); emit BondChanged(_id, _deposit, _percent, _expiration, _yearFee, msg.sender); } /// @dev Changes the holder request. /// @param _id A Bond ID. /// @param _deposit The collateral amount. /// @param _expiration The expiration in seconds. /// @param _yearFee The percentage of the commission. function holderChange(uint256 _id, uint256 _deposit, uint256 _expiration, uint256 _yearFee) external payable { require(bonds[_id].holder == msg.sender && bonds[_id].issuer == address(0), "You are not the holder or bond is matched"); changeDeposit(_id, _deposit); changeExpiration(_id, _expiration); changeYearFee(_id, _yearFee); emit BondChanged(_id, _deposit, 0, _expiration, _yearFee, msg.sender); } function changeDeposit(uint256 _id, uint256 _deposit) internal { uint256 _oldDeposit = bonds[_id].deposit; if (_deposit != 0 && _oldDeposit != _deposit) { require(_deposit >= minEther, "Too small funds"); bonds[_id].deposit = _deposit; if (_oldDeposit > _deposit) { msg.sender.transfer(_oldDeposit.sub(_deposit)); } else { require(msg.value == _deposit.sub(_oldDeposit), "Incorrect value"); } } } function changePercent(uint256 _id, uint256 _percent) internal { uint256 _oldPercent = bonds[_id].percent; if (_percent != 0 && _oldPercent != _percent) { require(_percent >= ITBoxManager(settings.tBoxManager()).withdrawPercent(bonds[_id].deposit), "Collateralization is not enough"); bonds[_id].percent = _percent; } } function changeExpiration(uint256 _id, uint256 _expiration) internal { uint256 _oldExpiration = bonds[_id].expiration; if (_oldExpiration != _expiration) { require(_expiration >= 1 days && _expiration <= 365 days, "Expiration out of range"); bonds[_id].expiration = _expiration; } } function changeYearFee(uint256 _id, uint256 _yearFee) internal { uint256 _oldYearFee = bonds[_id].yearFee; if (_oldYearFee != _yearFee) { require(_yearFee <= 25000, "Fee out of range"); bonds[_id].yearFee = _yearFee; } } /// @dev Uses to match the issuer request. /// @param _id A Bond ID. function takeIssueRequest(uint256 _id) external payable issueRequest(_id) validTx { address _issuer = bonds[_id].issuer; uint256 _eth = bonds[_id].deposit.mul(divider).div(bonds[_id].percent); require(msg.value == _eth, "Incorrect ETH value"); uint256 _sysEth = _eth.mul(issuerFee).div(divider); systemETH = systemETH.add(_sysEth); uint256 _tmv = _eth.mul(rate()).div(precision()); uint256 _box = ITBoxManager(settings.tBoxManager()).create.value(bonds[_id].deposit)(_tmv); bonds[_id].holder = msg.sender; bonds[_id].tmv = _tmv; bonds[_id].expiration = bonds[_id].expiration.add(now); bonds[_id].sysFee = holderFee; bonds[_id].tBoxId = _box; bonds[_id].createdAt = now; _issuer.transfer(_eth.sub(_sysEth)); IToken(settings.tmvAddress()).transfer(msg.sender, _tmv); emit BondMatched(_id, msg.sender, _box, _tmv, holderFee, _issuer); } /// @dev Uses to match the holder request. /// @param _id A Bond ID. function takeBuyRequest(uint256 _id) external payable buyRequest(_id) validTx { address _holder = bonds[_id].holder; uint256 _sysEth = bonds[_id].deposit.mul(issuerFee).div(divider); systemETH = systemETH.add(_sysEth); uint256 _tmv = bonds[_id].deposit.mul(rate()).div(precision()); uint256 _box = ITBoxManager(settings.tBoxManager()).create.value(msg.value)(_tmv); bonds[_id].issuer = msg.sender; bonds[_id].tmv = _tmv; bonds[_id].expiration = bonds[_id].expiration.add(now); bonds[_id].sysFee = holderFee; bonds[_id].tBoxId = _box; bonds[_id].createdAt = now; msg.sender.transfer(bonds[_id].deposit.sub(_sysEth)); IToken(settings.tmvAddress()).transfer(_holder, _tmv); emit BondMatched(_id, msg.sender, _box, _tmv, holderFee, _holder); } /// @dev Finishes the bond. /// @param _id A Bond ID. function finish(uint256 _id) external onlyIssuer(_id) validTx { Bond memory bond = bonds[_id]; // It's not necessary to check matching of the bond // since the expiration period cannot exceed 365 days. require(now < bond.expiration, "Bond expired"); uint256 _secondsPast = now.sub(bond.createdAt); (uint256 _eth, uint256 _debt) = getBox(bond.tBoxId); uint256 _commission = bond.tmv .mul(_secondsPast) .mul(bond.yearFee) .div(365 days) .div(divider); uint256 _sysTMV = _commission.mul(bond.sysFee).div(divider); address _holder = bond.holder; if (_sysTMV.add(_debt) > 0) { IToken(settings.tmvAddress()).transferFrom( msg.sender, address(this), _sysTMV.add(_debt) ); } if (_commission > 0) { IToken(settings.tmvAddress()).transferFrom( msg.sender, _holder, _commission.sub(_sysTMV) ); } if (_eth > 0) { ITBoxManager(settings.tBoxManager()).close(bond.tBoxId); delete bonds[_id]; msg.sender.transfer(_eth); } else { // when TBox no longer exists delete bonds[_id]; } emit BondFinished(_id, msg.sender, _holder); } /// @dev Executes expiration process of the bond. /// @param _id A Bond ID. function expire(uint256 _id) external matched(_id) validTx { require(now > bonds[_id].expiration, "Bond hasn't expired"); (uint256 _eth, uint256 _tmv) = getBox(bonds[_id].tBoxId); if (_eth == 0) { emit BondExpired(_id, bonds[_id].issuer, bonds[_id].holder); delete bonds[_id]; return; } uint256 _collateralPercent = ITBoxManager(settings.tBoxManager()).collateralPercent(bonds[_id].tBoxId); uint256 _targetCollateralPercent = settings.globalTargetCollateralization(); if (_collateralPercent > _targetCollateralPercent) { uint256 _ethTarget = _tmv.mul(_targetCollateralPercent).div(rate()); // mul and div by precision are omitted uint256 _issuerEth = _eth.sub(_ethTarget); uint256 _withdrawableEth = ITBoxManager(settings.tBoxManager()).withdrawableEth( bonds[_id].tBoxId ); if (_issuerEth > _withdrawableEth) { _issuerEth = _withdrawableEth; } ITBoxManager(settings.tBoxManager()).withdrawEth( bonds[_id].tBoxId, _issuerEth ); bonds[_id].issuer.transfer(_issuerEth); } _eth = ITBoxManager(settings.tBoxManager()).withdrawableEth( bonds[_id].tBoxId ); uint256 _commission = _eth.mul(bonds[_id].sysFee).div(divider); if (_commission > 0) { ITBoxManager(settings.tBoxManager()).withdrawEth( bonds[_id].tBoxId, _commission ); systemETH = systemETH.add(_commission); } ITBoxManager(settings.tBoxManager()).transferFrom( address(this), bonds[_id].holder, bonds[_id].tBoxId ); emit BondExpired(_id, bonds[_id].issuer, bonds[_id].holder); delete bonds[_id]; } /// @dev Returns TBox parameters. /// @param _id A Bond ID. function getBox(uint256 _id) public view returns(uint256, uint256) { return ITBoxManager(settings.tBoxManager()).boxes(_id); } /// @dev Needs to claim funds from the logic contract to execute finishing and expiration. function() external payable {} /// @dev Withdraws system fee. /// @param _beneficiary The address to forward funds to. function withdrawSystemETH(address _beneficiary) external onlyAdmin { require(_beneficiary != address(0), "Zero address, be careful"); require(systemETH > 0, "There is no available ETH"); uint256 _systemETH = systemETH; systemETH = 0; _beneficiary.transfer(_systemETH); } /// @dev Reclaims ERC20 tokens. /// @param _token The address of the ERC20 token. /// @param _beneficiary The address to forward funds to. function reclaimERC20(address _token, address _beneficiary) external onlyAdmin { require(_beneficiary != address(0), "Zero address, be careful"); uint256 _amount = IToken(_token).balanceOf(address(this)); require(_amount > 0, "There are no tokens"); IToken(_token).transfer(_beneficiary, _amount); } /// @dev Sets issuer fee. /// @param _value Commission percentage. function setIssuerFee(uint256 _value) external onlyAdmin { require(_value <= 10000, "Too much"); issuerFee = _value; emit BondIssuerFeeUpdated(_value); } /// @dev Sets holder fee. /// @param _value Commission percentage. function setHolderFee(uint256 _value) external onlyAdmin { require(_value <= 50000, "Too much"); holderFee = _value; emit BondHolderFeeUpdated(_value); } /// @dev Sets minimum deposit amount. /// @param _value The minimum deposit amount in wei. function setMinEther(uint256 _value) external onlyAdmin { require(_value <= 100 ether, "Too much"); minEther = _value; emit BondMinEtherUpdated(_value); } /// @dev Sets admin address. /// @param _newAdmin The address of the new admin. function changeAdmin(address _newAdmin) external onlyAdmin { require(_newAdmin != address(0), "Zero address, be careful"); admin = _newAdmin; } /// @dev Returns precision using for USD and commission calculation. function precision() public view returns(uint256) { return ITBoxManager(settings.tBoxManager()).precision(); } /// @dev Returns current oracle ETH/USD price with precision. function rate() public view returns(uint256) { return IOracle(settings.oracleAddress()).ethUsdPrice(); } /// @dev Transfers issuer's rights of an Order. function transferIssuerRights(address _to, uint256 _id) external onlyIssuer(_id) { require(_to != address(0), "Zero address, be careful"); bonds[_id].issuer = _to; emit IssuerRightsTransferred(msg.sender, _to, _id); } /// @dev Transfers holder's rights of an Order. function transferHolderRights(address _to, uint256 _id) external onlyHolder(_id) { require(_to != address(0), "Zero address, be careful"); bonds[_id].holder = _to; emit HolderRightsTransferred(msg.sender, _to, _id); } } pragma solidity 0.4.25; /// @title IOracle /// @dev Interface for getting the data from the oracle contract. interface IOracle { function ethUsdPrice() external view returns(uint256); } pragma solidity 0.4.25; /// @title ISettings /// @dev Interface for getting the data from settings contract. interface ISettings { function oracleAddress() external view returns(address); function minDeposit() external view returns(uint256); function sysFee() external view returns(uint256); function userFee() external view returns(uint256); function ratio() external view returns(uint256); function globalTargetCollateralization() external view returns(uint256); function tmvAddress() external view returns(uint256); function maxStability() external view returns(uint256); function minStability() external view returns(uint256); function gasPriceLimit() external view returns(uint256); function isFeeManager(address account) external view returns (bool); function tBoxManager() external view returns(address); } pragma solidity 0.4.25; /// @title ILogic /// @dev Interface for interaction with the TMV logic contract to manage Boxes. interface ITBoxManager { function create(uint256 withdraw) external payable returns (uint256); function precision() external view returns (uint256); function rate() external view returns (uint256); function transferFrom(address from, address to, uint256 tokenId) external; function close(uint256 id) external; function withdrawPercent(uint256 _collateral) external view returns(uint256); function boxes(uint256 id) external view returns(uint256, uint256); function withdrawEth(uint256 _id, uint256 _amount) external; function withdrawTmv(uint256 _id, uint256 _amount) external; function withdrawableEth(uint256 id) external view returns(uint256); function withdrawableTmv(uint256 collateral) external view returns(uint256); function maxCapAmount(uint256 _id) external view returns (uint256); function collateralPercent(uint256 _id) external view returns (uint256); function capitalize(uint256 _id, uint256 _tmv) external; function boxWithdrawableTmv(uint256 _id) external view returns(uint256); function addEth(uint256 _id) external payable; function capitalizeMax(uint256 _id) external payable; function withdrawTmvMax(uint256 _id) external payable; function addTmv(uint256 _id, uint256 _amount) external payable; } pragma solidity 0.4.25; /// @title IToken /// @dev Interface for interaction with the TMV token contract. interface IToken { function burnLogic(address from, uint256 value) external; function approve(address spender, uint256 value) external; function balanceOf(address who) external view returns (uint256); function mint(address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 tokenId) external; } pragma solidity 0.4.25; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'mul'); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, 'div'); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, 'sub'); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'add'); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } pragma solidity 0.4.25; import "./SafeMath.sol"; import "./IToken.sol"; import "./ISettings.sol"; import "./ITBoxManager.sol"; import "./IOracle.sol"; /// @title BondService contract BondService { using SafeMath for uint256; /// @notice The address of the admin account. address public admin; // The amount of Ether received from the commissions of the system. uint256 private systemETH; // Commission percentage charged from the issuer uint256 public issuerFee; // Commission percentage charged from the holder uint256 public holderFee; // The percentage divider uint256 public divider = 100000; // The minimum deposit amount uint256 public minEther; // The settings contract address ISettings public settings; /// @dev An array containing the Bond struct for all Bonds in existence. The ID /// of each Bond is actually an index into this array. Bond[] public bonds; /// @dev The main Bond struct. Every Bond is represented by a copy /// of this structure. struct Bond { // The address of the issuer of the Bond address issuer; // The address of the holder of the Bond address holder; // The Ether amount packed in the Bond uint256 deposit; // The collateral percentage uint256 percent; // The number of TMV tokens withdrawn to holder uint256 tmv; // The expiration time in seconds uint256 expiration; // The percentage of the holder commission fee uint256 yearFee; // The percentage of the system commission fee uint256 sysFee; // The TBox ID created inside the Bond uint256 tBoxId; // The timestamp of the Bond creation // Sets at the matching moment uint256 createdAt; } /// @dev The BondCreated event is fired whenever a new Bond comes into existence. event BondCreated(uint256 id, address who, uint256 deposit, uint256 percent, uint256 expiration, uint256 yearFee); /// @dev The BondChanged event is fired whenever a Bond changing. event BondChanged(uint256 id, uint256 deposit, uint256 percent, uint256 expiration, uint256 yearFee, address who); /// @dev The BondClosed event is fired whenever a Bond is closed. event BondClosed(uint256 id, address who); /// @dev The BondMatched event is fired whenever a Bond is matched. event BondMatched(uint256 id, address who, uint256 tBox, uint256 tmv, uint256 sysFee, address counteragent); /// @dev The BondFinished event is fired whenever a Bond is finished. event BondFinished(uint256 id, address issuer, address holder); /// @dev The BondExpired event is fired whenever a Bond is expired. event BondExpired(uint256 id, address issuer, address holder); event BondHolderFeeUpdated(uint256 _value); event BondIssuerFeeUpdated(uint256 _value); event BondMinEtherUpdated(uint256 _value); event IssuerRightsTransferred(address indexed from, address indexed to, uint indexed id); event HolderRightsTransferred(address indexed from, address indexed to, uint indexed id); /// @dev Defends against front-running attacks. modifier validTx() { require(tx.gasprice <= settings.gasPriceLimit(), "Gas price is greater than allowed"); _; } /// @dev Access modifier for admin-only functionality. modifier onlyAdmin() { require(admin == msg.sender, "You have no access"); _; } /// @dev Access modifier for issuer-only functionality. /// @param _id A Bond ID. modifier onlyIssuer(uint256 _id) { require(bonds[_id].issuer == msg.sender, "You are not the issuer"); _; } /// @dev Access modifier for holder-only functionality. /// @param _id A Bond ID. modifier onlyHolder(uint256 _id) { require(bonds[_id].holder == msg.sender, "You are not the holder"); _; } /// @dev Access modifier for single-owner-only functionality. /// @param _id A Bond ID. modifier singleOwner(uint256 _id) { bool _a = bonds[_id].issuer == msg.sender && bonds[_id].holder == address(0); bool _b = bonds[_id].holder == msg.sender && bonds[_id].issuer == address(0); require(_a || _b, "You are not the single owner"); _; } /// @dev Modifier to allow actions only when the bond is issuer's request /// @param _id A Bond ID. modifier issueRequest(uint256 _id) { require(bonds[_id].issuer != address(0) && bonds[_id].holder == address(0), "The bond isn't an emit request"); _; } /// @dev Modifier to allow actions only when the bond is holder's request /// @param _id A Bond ID. modifier buyRequest(uint256 _id) { require(bonds[_id].holder != address(0) && bonds[_id].issuer == address(0), "The bond isn't a buy request"); _; } /// @dev Modifier to allow actions only when the bond is matched /// @param _id A Bond ID. modifier matched(uint256 _id) { require(bonds[_id].issuer != address(0) && bonds[_id].holder != address(0), "Bond isn't matched"); _; } /// @notice Settings address can't be changed later. /// @dev The contract constructor sets the original `admin` of the contract to the sender // account and sets the settings contract with provided address. /// @param _settings The address of the settings contract. constructor(ISettings _settings) public { admin = msg.sender; settings = _settings; issuerFee = 500; // 0.5% emit BondIssuerFeeUpdated(issuerFee); holderFee = 10000; // 10% emit BondHolderFeeUpdated(holderFee); minEther = 0.1 ether; emit BondMinEtherUpdated(minEther); } /// @dev Creates issuer request. /// @param _percent The collateral percentage. /// @param _expiration The expiration in seconds. /// @param _yearFee The percentage of the commission. /// @return New Bond ID. function leverage(uint256 _percent, uint256 _expiration, uint256 _yearFee) public payable returns (uint256) { require(msg.value >= minEther, "Too small funds"); require(_percent >= ITBoxManager(settings.tBoxManager()).withdrawPercent(msg.value), "Collateralization is not enough"); require(_expiration >= 1 days && _expiration <= 365 days, "Expiration out of range"); require(_yearFee <= 25000, "Fee out of range"); return createBond(msg.sender, address(0), _percent, _expiration, _yearFee); } /// @dev Creates holder request. /// @param _expiration The expiration in seconds. /// @param _yearFee The percentage of the commission. /// @return New Bond ID. function exchange(uint256 _expiration, uint256 _yearFee) public payable returns (uint256) { require(msg.value >= minEther, "Too small funds"); require(_expiration >= 1 days && _expiration <= 365 days, "Expiration out of range"); require(_yearFee <= 25000, "Fee out of range"); return createBond(address(0), msg.sender, 0, _expiration, _yearFee); } /// @dev Creates Bond request. /// @param _issuer The address of the issuer. /// @param _holder The address of the holder. /// @param _percent The collateral percentage. /// @param _expiration The expiration in seconds. /// @param _yearFee The percentage of the commission. /// @return New Bond ID. function createBond( address _issuer, address _holder, uint256 _percent, uint256 _expiration, uint256 _yearFee ) internal returns(uint256) { Bond memory _bond = Bond( _issuer, _holder, msg.value, _percent, 0, _expiration, _yearFee, 0, 0, 0 ); uint256 _id = bonds.push(_bond).sub(1); emit BondCreated(_id, msg.sender, msg.value, _percent, _expiration, _yearFee); return _id; } /// @dev Closes the bond. /// @param _id A Bond ID. function close(uint256 _id) external singleOwner(_id) { uint256 _eth = bonds[_id].deposit; delete bonds[_id]; msg.sender.transfer(_eth); emit BondClosed(_id, msg.sender); } /// @dev Changes the issuer request. /// @param _id A Bond ID. /// @param _deposit The collateral amount. /// @param _percent The collateral percentage. /// @param _expiration The expiration in seconds. /// @param _yearFee The percentage of the commission. function issuerChange(uint256 _id, uint256 _deposit, uint256 _percent, uint256 _expiration, uint256 _yearFee) external payable singleOwner(_id) onlyIssuer(_id) { changeDeposit(_id, _deposit); changePercent(_id, _percent); changeExpiration(_id, _expiration); changeYearFee(_id, _yearFee); emit BondChanged(_id, _deposit, _percent, _expiration, _yearFee, msg.sender); } /// @dev Changes the holder request. /// @param _id A Bond ID. /// @param _deposit The collateral amount. /// @param _expiration The expiration in seconds. /// @param _yearFee The percentage of the commission. function holderChange(uint256 _id, uint256 _deposit, uint256 _expiration, uint256 _yearFee) external payable { require(bonds[_id].holder == msg.sender && bonds[_id].issuer == address(0), "You are not the holder or bond is matched"); changeDeposit(_id, _deposit); changeExpiration(_id, _expiration); changeYearFee(_id, _yearFee); emit BondChanged(_id, _deposit, 0, _expiration, _yearFee, msg.sender); } function changeDeposit(uint256 _id, uint256 _deposit) internal { uint256 _oldDeposit = bonds[_id].deposit; if (_deposit != 0 && _oldDeposit != _deposit) { require(_deposit >= minEther, "Too small funds"); bonds[_id].deposit = _deposit; if (_oldDeposit > _deposit) { msg.sender.transfer(_oldDeposit.sub(_deposit)); } else { require(msg.value == _deposit.sub(_oldDeposit), "Incorrect value"); } } } function changePercent(uint256 _id, uint256 _percent) internal { uint256 _oldPercent = bonds[_id].percent; if (_percent != 0 && _oldPercent != _percent) { require(_percent >= ITBoxManager(settings.tBoxManager()).withdrawPercent(bonds[_id].deposit), "Collateralization is not enough"); bonds[_id].percent = _percent; } } function changeExpiration(uint256 _id, uint256 _expiration) internal { uint256 _oldExpiration = bonds[_id].expiration; if (_oldExpiration != _expiration) { require(_expiration >= 1 days && _expiration <= 365 days, "Expiration out of range"); bonds[_id].expiration = _expiration; } } function changeYearFee(uint256 _id, uint256 _yearFee) internal { uint256 _oldYearFee = bonds[_id].yearFee; if (_oldYearFee != _yearFee) { require(_yearFee <= 25000, "Fee out of range"); bonds[_id].yearFee = _yearFee; } } /// @dev Uses to match the issuer request. /// @param _id A Bond ID. function takeIssueRequest(uint256 _id) external payable issueRequest(_id) validTx { address _issuer = bonds[_id].issuer; uint256 _eth = bonds[_id].deposit.mul(divider).div(bonds[_id].percent); require(msg.value == _eth, "Incorrect ETH value"); uint256 _sysEth = _eth.mul(issuerFee).div(divider); systemETH = systemETH.add(_sysEth); uint256 _tmv = _eth.mul(rate()).div(precision()); uint256 _box = ITBoxManager(settings.tBoxManager()).create.value(bonds[_id].deposit)(_tmv); bonds[_id].holder = msg.sender; bonds[_id].tmv = _tmv; bonds[_id].expiration = bonds[_id].expiration.add(now); bonds[_id].sysFee = holderFee; bonds[_id].tBoxId = _box; bonds[_id].createdAt = now; _issuer.transfer(_eth.sub(_sysEth)); IToken(settings.tmvAddress()).transfer(msg.sender, _tmv); emit BondMatched(_id, msg.sender, _box, _tmv, holderFee, _issuer); } /// @dev Uses to match the holder request. /// @param _id A Bond ID. function takeBuyRequest(uint256 _id) external payable buyRequest(_id) validTx { address _holder = bonds[_id].holder; uint256 _sysEth = bonds[_id].deposit.mul(issuerFee).div(divider); systemETH = systemETH.add(_sysEth); uint256 _tmv = bonds[_id].deposit.mul(rate()).div(precision()); uint256 _box = ITBoxManager(settings.tBoxManager()).create.value(msg.value)(_tmv); bonds[_id].issuer = msg.sender; bonds[_id].tmv = _tmv; bonds[_id].expiration = bonds[_id].expiration.add(now); bonds[_id].sysFee = holderFee; bonds[_id].tBoxId = _box; bonds[_id].createdAt = now; msg.sender.transfer(bonds[_id].deposit.sub(_sysEth)); IToken(settings.tmvAddress()).transfer(_holder, _tmv); emit BondMatched(_id, msg.sender, _box, _tmv, holderFee, _holder); } /// @dev Finishes the bond. /// @param _id A Bond ID. function finish(uint256 _id) external onlyIssuer(_id) validTx { Bond memory bond = bonds[_id]; // It's not necessary to check matching of the bond // since the expiration period cannot exceed 365 days. require(now < bond.expiration, "Bond expired"); uint256 _secondsPast = now.sub(bond.createdAt); (uint256 _eth, uint256 _debt) = getBox(bond.tBoxId); uint256 _commission = bond.tmv .mul(_secondsPast) .mul(bond.yearFee) .div(365 days) .div(divider); uint256 _sysTMV = _commission.mul(bond.sysFee).div(divider); address _holder = bond.holder; if (_sysTMV.add(_debt) > 0) { IToken(settings.tmvAddress()).transferFrom( msg.sender, address(this), _sysTMV.add(_debt) ); } if (_commission > 0) { IToken(settings.tmvAddress()).transferFrom( msg.sender, _holder, _commission.sub(_sysTMV) ); } if (_eth > 0) { ITBoxManager(settings.tBoxManager()).close(bond.tBoxId); delete bonds[_id]; msg.sender.transfer(_eth); } else { // when TBox no longer exists delete bonds[_id]; } emit BondFinished(_id, msg.sender, _holder); } /// @dev Executes expiration process of the bond. /// @param _id A Bond ID. function expire(uint256 _id) external matched(_id) validTx { require(now > bonds[_id].expiration, "Bond hasn't expired"); (uint256 _eth, uint256 _tmv) = getBox(bonds[_id].tBoxId); if (_eth == 0) { emit BondExpired(_id, bonds[_id].issuer, bonds[_id].holder); delete bonds[_id]; return; } uint256 _collateralPercent = ITBoxManager(settings.tBoxManager()).collateralPercent(bonds[_id].tBoxId); uint256 _targetCollateralPercent = settings.globalTargetCollateralization(); if (_collateralPercent > _targetCollateralPercent) { uint256 _ethTarget = _tmv.mul(_targetCollateralPercent).div(rate()); // mul and div by precision are omitted uint256 _issuerEth = _eth.sub(_ethTarget); uint256 _withdrawableEth = ITBoxManager(settings.tBoxManager()).withdrawableEth( bonds[_id].tBoxId ); if (_issuerEth > _withdrawableEth) { _issuerEth = _withdrawableEth; } ITBoxManager(settings.tBoxManager()).withdrawEth( bonds[_id].tBoxId, _issuerEth ); bonds[_id].issuer.transfer(_issuerEth); } _eth = ITBoxManager(settings.tBoxManager()).withdrawableEth( bonds[_id].tBoxId ); uint256 _commission = _eth.mul(bonds[_id].sysFee).div(divider); if (_commission > 0) { ITBoxManager(settings.tBoxManager()).withdrawEth( bonds[_id].tBoxId, _commission ); systemETH = systemETH.add(_commission); } ITBoxManager(settings.tBoxManager()).transferFrom( address(this), bonds[_id].holder, bonds[_id].tBoxId ); emit BondExpired(_id, bonds[_id].issuer, bonds[_id].holder); delete bonds[_id]; } /// @dev Returns TBox parameters. /// @param _id A Bond ID. function getBox(uint256 _id) public view returns(uint256, uint256) { return ITBoxManager(settings.tBoxManager()).boxes(_id); } /// @dev Needs to claim funds from the logic contract to execute finishing and expiration. function() external payable {} /// @dev Withdraws system fee. /// @param _beneficiary The address to forward funds to. function withdrawSystemETH(address _beneficiary) external onlyAdmin { require(_beneficiary != address(0), "Zero address, be careful"); require(systemETH > 0, "There is no available ETH"); uint256 _systemETH = systemETH; systemETH = 0; _beneficiary.transfer(_systemETH); } /// @dev Reclaims ERC20 tokens. /// @param _token The address of the ERC20 token. /// @param _beneficiary The address to forward funds to. function reclaimERC20(address _token, address _beneficiary) external onlyAdmin { require(_beneficiary != address(0), "Zero address, be careful"); uint256 _amount = IToken(_token).balanceOf(address(this)); require(_amount > 0, "There are no tokens"); IToken(_token).transfer(_beneficiary, _amount); } /// @dev Sets issuer fee. /// @param _value Commission percentage. function setIssuerFee(uint256 _value) external onlyAdmin { require(_value <= 10000, "Too much"); issuerFee = _value; emit BondIssuerFeeUpdated(_value); } /// @dev Sets holder fee. /// @param _value Commission percentage. function setHolderFee(uint256 _value) external onlyAdmin { require(_value <= 50000, "Too much"); holderFee = _value; emit BondHolderFeeUpdated(_value); } /// @dev Sets minimum deposit amount. /// @param _value The minimum deposit amount in wei. function setMinEther(uint256 _value) external onlyAdmin { require(_value <= 100 ether, "Too much"); minEther = _value; emit BondMinEtherUpdated(_value); } /// @dev Sets admin address. /// @param _newAdmin The address of the new admin. function changeAdmin(address _newAdmin) external onlyAdmin { require(_newAdmin != address(0), "Zero address, be careful"); admin = _newAdmin; } /// @dev Returns precision using for USD and commission calculation. function precision() public view returns(uint256) { return ITBoxManager(settings.tBoxManager()).precision(); } /// @dev Returns current oracle ETH/USD price with precision. function rate() public view returns(uint256) { return IOracle(settings.oracleAddress()).ethUsdPrice(); } /// @dev Transfers issuer's rights of an Order. function transferIssuerRights(address _to, uint256 _id) external onlyIssuer(_id) { require(_to != address(0), "Zero address, be careful"); bonds[_id].issuer = _to; emit IssuerRightsTransferred(msg.sender, _to, _id); } /// @dev Transfers holder's rights of an Order. function transferHolderRights(address _to, uint256 _id) external onlyHolder(_id) { require(_to != address(0), "Zero address, be careful"); bonds[_id].holder = _to; emit HolderRightsTransferred(msg.sender, _to, _id); } } pragma solidity 0.4.25; /// @title IOracle /// @dev Interface for getting the data from the oracle contract. interface IOracle { function ethUsdPrice() external view returns(uint256); } pragma solidity 0.4.25; /// @title ISettings /// @dev Interface for getting the data from settings contract. interface ISettings { function oracleAddress() external view returns(address); function minDeposit() external view returns(uint256); function sysFee() external view returns(uint256); function userFee() external view returns(uint256); function ratio() external view returns(uint256); function globalTargetCollateralization() external view returns(uint256); function tmvAddress() external view returns(uint256); function maxStability() external view returns(uint256); function minStability() external view returns(uint256); function gasPriceLimit() external view returns(uint256); function isFeeManager(address account) external view returns (bool); function tBoxManager() external view returns(address); } pragma solidity 0.4.25; /// @title ILogic /// @dev Interface for interaction with the TMV logic contract to manage Boxes. interface ITBoxManager { function create(uint256 withdraw) external payable returns (uint256); function precision() external view returns (uint256); function rate() external view returns (uint256); function transferFrom(address from, address to, uint256 tokenId) external; function close(uint256 id) external; function withdrawPercent(uint256 _collateral) external view returns(uint256); function boxes(uint256 id) external view returns(uint256, uint256); function withdrawEth(uint256 _id, uint256 _amount) external; function withdrawTmv(uint256 _id, uint256 _amount) external; function withdrawableEth(uint256 id) external view returns(uint256); function withdrawableTmv(uint256 collateral) external view returns(uint256); function maxCapAmount(uint256 _id) external view returns (uint256); function collateralPercent(uint256 _id) external view returns (uint256); function capitalize(uint256 _id, uint256 _tmv) external; function boxWithdrawableTmv(uint256 _id) external view returns(uint256); function addEth(uint256 _id) external payable; function capitalizeMax(uint256 _id) external payable; function withdrawTmvMax(uint256 _id) external payable; function addTmv(uint256 _id, uint256 _amount) external payable; } pragma solidity 0.4.25; /// @title IToken /// @dev Interface for interaction with the TMV token contract. interface IToken { function burnLogic(address from, uint256 value) external; function approve(address spender, uint256 value) external; function balanceOf(address who) external view returns (uint256); function mint(address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 tokenId) external; } pragma solidity 0.4.25; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'mul'); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, 'div'); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, 'sub'); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'add'); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } pragma solidity 0.4.25; import "./SafeMath.sol"; import "./IToken.sol"; import "./ISettings.sol"; import "./ITBoxManager.sol"; import "./IOracle.sol"; /// @title BondService contract BondService { using SafeMath for uint256; /// @notice The address of the admin account. address public admin; // The amount of Ether received from the commissions of the system. uint256 private systemETH; // Commission percentage charged from the issuer uint256 public issuerFee; // Commission percentage charged from the holder uint256 public holderFee; // The percentage divider uint256 public divider = 100000; // The minimum deposit amount uint256 public minEther; // The settings contract address ISettings public settings; /// @dev An array containing the Bond struct for all Bonds in existence. The ID /// of each Bond is actually an index into this array. Bond[] public bonds; /// @dev The main Bond struct. Every Bond is represented by a copy /// of this structure. struct Bond { // The address of the issuer of the Bond address issuer; // The address of the holder of the Bond address holder; // The Ether amount packed in the Bond uint256 deposit; // The collateral percentage uint256 percent; // The number of TMV tokens withdrawn to holder uint256 tmv; // The expiration time in seconds uint256 expiration; // The percentage of the holder commission fee uint256 yearFee; // The percentage of the system commission fee uint256 sysFee; // The TBox ID created inside the Bond uint256 tBoxId; // The timestamp of the Bond creation // Sets at the matching moment uint256 createdAt; } /// @dev The BondCreated event is fired whenever a new Bond comes into existence. event BondCreated(uint256 id, address who, uint256 deposit, uint256 percent, uint256 expiration, uint256 yearFee); /// @dev The BondChanged event is fired whenever a Bond changing. event BondChanged(uint256 id, uint256 deposit, uint256 percent, uint256 expiration, uint256 yearFee, address who); /// @dev The BondClosed event is fired whenever a Bond is closed. event BondClosed(uint256 id, address who); /// @dev The BondMatched event is fired whenever a Bond is matched. event BondMatched(uint256 id, address who, uint256 tBox, uint256 tmv, uint256 sysFee, address counteragent); /// @dev The BondFinished event is fired whenever a Bond is finished. event BondFinished(uint256 id, address issuer, address holder); /// @dev The BondExpired event is fired whenever a Bond is expired. event BondExpired(uint256 id, address issuer, address holder); event BondHolderFeeUpdated(uint256 _value); event BondIssuerFeeUpdated(uint256 _value); event BondMinEtherUpdated(uint256 _value); event IssuerRightsTransferred(address indexed from, address indexed to, uint indexed id); event HolderRightsTransferred(address indexed from, address indexed to, uint indexed id); /// @dev Defends against front-running attacks. modifier validTx() { require(tx.gasprice <= settings.gasPriceLimit(), "Gas price is greater than allowed"); _; } /// @dev Access modifier for admin-only functionality. modifier onlyAdmin() { require(admin == msg.sender, "You have no access"); _; } /// @dev Access modifier for issuer-only functionality. /// @param _id A Bond ID. modifier onlyIssuer(uint256 _id) { require(bonds[_id].issuer == msg.sender, "You are not the issuer"); _; } /// @dev Access modifier for holder-only functionality. /// @param _id A Bond ID. modifier onlyHolder(uint256 _id) { require(bonds[_id].holder == msg.sender, "You are not the holder"); _; } /// @dev Access modifier for single-owner-only functionality. /// @param _id A Bond ID. modifier singleOwner(uint256 _id) { bool _a = bonds[_id].issuer == msg.sender && bonds[_id].holder == address(0); bool _b = bonds[_id].holder == msg.sender && bonds[_id].issuer == address(0); require(_a || _b, "You are not the single owner"); _; } /// @dev Modifier to allow actions only when the bond is issuer's request /// @param _id A Bond ID. modifier issueRequest(uint256 _id) { require(bonds[_id].issuer != address(0) && bonds[_id].holder == address(0), "The bond isn't an emit request"); _; } /// @dev Modifier to allow actions only when the bond is holder's request /// @param _id A Bond ID. modifier buyRequest(uint256 _id) { require(bonds[_id].holder != address(0) && bonds[_id].issuer == address(0), "The bond isn't a buy request"); _; } /// @dev Modifier to allow actions only when the bond is matched /// @param _id A Bond ID. modifier matched(uint256 _id) { require(bonds[_id].issuer != address(0) && bonds[_id].holder != address(0), "Bond isn't matched"); _; } /// @notice Settings address can't be changed later. /// @dev The contract constructor sets the original `admin` of the contract to the sender // account and sets the settings contract with provided address. /// @param _settings The address of the settings contract. constructor(ISettings _settings) public { admin = msg.sender; settings = _settings; issuerFee = 500; // 0.5% emit BondIssuerFeeUpdated(issuerFee); holderFee = 10000; // 10% emit BondHolderFeeUpdated(holderFee); minEther = 0.1 ether; emit BondMinEtherUpdated(minEther); } /// @dev Creates issuer request. /// @param _percent The collateral percentage. /// @param _expiration The expiration in seconds. /// @param _yearFee The percentage of the commission. /// @return New Bond ID. function leverage(uint256 _percent, uint256 _expiration, uint256 _yearFee) public payable returns (uint256) { require(msg.value >= minEther, "Too small funds"); require(_percent >= ITBoxManager(settings.tBoxManager()).withdrawPercent(msg.value), "Collateralization is not enough"); require(_expiration >= 1 days && _expiration <= 365 days, "Expiration out of range"); require(_yearFee <= 25000, "Fee out of range"); return createBond(msg.sender, address(0), _percent, _expiration, _yearFee); } /// @dev Creates holder request. /// @param _expiration The expiration in seconds. /// @param _yearFee The percentage of the commission. /// @return New Bond ID. function exchange(uint256 _expiration, uint256 _yearFee) public payable returns (uint256) { require(msg.value >= minEther, "Too small funds"); require(_expiration >= 1 days && _expiration <= 365 days, "Expiration out of range"); require(_yearFee <= 25000, "Fee out of range"); return createBond(address(0), msg.sender, 0, _expiration, _yearFee); } /// @dev Creates Bond request. /// @param _issuer The address of the issuer. /// @param _holder The address of the holder. /// @param _percent The collateral percentage. /// @param _expiration The expiration in seconds. /// @param _yearFee The percentage of the commission. /// @return New Bond ID. function createBond( address _issuer, address _holder, uint256 _percent, uint256 _expiration, uint256 _yearFee ) internal returns(uint256) { Bond memory _bond = Bond( _issuer, _holder, msg.value, _percent, 0, _expiration, _yearFee, 0, 0, 0 ); uint256 _id = bonds.push(_bond).sub(1); emit BondCreated(_id, msg.sender, msg.value, _percent, _expiration, _yearFee); return _id; } /// @dev Closes the bond. /// @param _id A Bond ID. function close(uint256 _id) external singleOwner(_id) { uint256 _eth = bonds[_id].deposit; delete bonds[_id]; msg.sender.transfer(_eth); emit BondClosed(_id, msg.sender); } /// @dev Changes the issuer request. /// @param _id A Bond ID. /// @param _deposit The collateral amount. /// @param _percent The collateral percentage. /// @param _expiration The expiration in seconds. /// @param _yearFee The percentage of the commission. function issuerChange(uint256 _id, uint256 _deposit, uint256 _percent, uint256 _expiration, uint256 _yearFee) external payable singleOwner(_id) onlyIssuer(_id) { changeDeposit(_id, _deposit); changePercent(_id, _percent); changeExpiration(_id, _expiration); changeYearFee(_id, _yearFee); emit BondChanged(_id, _deposit, _percent, _expiration, _yearFee, msg.sender); } /// @dev Changes the holder request. /// @param _id A Bond ID. /// @param _deposit The collateral amount. /// @param _expiration The expiration in seconds. /// @param _yearFee The percentage of the commission. function holderChange(uint256 _id, uint256 _deposit, uint256 _expiration, uint256 _yearFee) external payable { require(bonds[_id].holder == msg.sender && bonds[_id].issuer == address(0), "You are not the holder or bond is matched"); changeDeposit(_id, _deposit); changeExpiration(_id, _expiration); changeYearFee(_id, _yearFee); emit BondChanged(_id, _deposit, 0, _expiration, _yearFee, msg.sender); } function changeDeposit(uint256 _id, uint256 _deposit) internal { uint256 _oldDeposit = bonds[_id].deposit; if (_deposit != 0 && _oldDeposit != _deposit) { require(_deposit >= minEther, "Too small funds"); bonds[_id].deposit = _deposit; if (_oldDeposit > _deposit) { msg.sender.transfer(_oldDeposit.sub(_deposit)); } else { require(msg.value == _deposit.sub(_oldDeposit), "Incorrect value"); } } } function changePercent(uint256 _id, uint256 _percent) internal { uint256 _oldPercent = bonds[_id].percent; if (_percent != 0 && _oldPercent != _percent) { require(_percent >= ITBoxManager(settings.tBoxManager()).withdrawPercent(bonds[_id].deposit), "Collateralization is not enough"); bonds[_id].percent = _percent; } } function changeExpiration(uint256 _id, uint256 _expiration) internal { uint256 _oldExpiration = bonds[_id].expiration; if (_oldExpiration != _expiration) { require(_expiration >= 1 days && _expiration <= 365 days, "Expiration out of range"); bonds[_id].expiration = _expiration; } } function changeYearFee(uint256 _id, uint256 _yearFee) internal { uint256 _oldYearFee = bonds[_id].yearFee; if (_oldYearFee != _yearFee) { require(_yearFee <= 25000, "Fee out of range"); bonds[_id].yearFee = _yearFee; } } /// @dev Uses to match the issuer request. /// @param _id A Bond ID. function takeIssueRequest(uint256 _id) external payable issueRequest(_id) validTx { address _issuer = bonds[_id].issuer; uint256 _eth = bonds[_id].deposit.mul(divider).div(bonds[_id].percent); require(msg.value == _eth, "Incorrect ETH value"); uint256 _sysEth = _eth.mul(issuerFee).div(divider); systemETH = systemETH.add(_sysEth); uint256 _tmv = _eth.mul(rate()).div(precision()); uint256 _box = ITBoxManager(settings.tBoxManager()).create.value(bonds[_id].deposit)(_tmv); bonds[_id].holder = msg.sender; bonds[_id].tmv = _tmv; bonds[_id].expiration = bonds[_id].expiration.add(now); bonds[_id].sysFee = holderFee; bonds[_id].tBoxId = _box; bonds[_id].createdAt = now; _issuer.transfer(_eth.sub(_sysEth)); IToken(settings.tmvAddress()).transfer(msg.sender, _tmv); emit BondMatched(_id, msg.sender, _box, _tmv, holderFee, _issuer); } /// @dev Uses to match the holder request. /// @param _id A Bond ID. function takeBuyRequest(uint256 _id) external payable buyRequest(_id) validTx { address _holder = bonds[_id].holder; uint256 _sysEth = bonds[_id].deposit.mul(issuerFee).div(divider); systemETH = systemETH.add(_sysEth); uint256 _tmv = bonds[_id].deposit.mul(rate()).div(precision()); uint256 _box = ITBoxManager(settings.tBoxManager()).create.value(msg.value)(_tmv); bonds[_id].issuer = msg.sender; bonds[_id].tmv = _tmv; bonds[_id].expiration = bonds[_id].expiration.add(now); bonds[_id].sysFee = holderFee; bonds[_id].tBoxId = _box; bonds[_id].createdAt = now; msg.sender.transfer(bonds[_id].deposit.sub(_sysEth)); IToken(settings.tmvAddress()).transfer(_holder, _tmv); emit BondMatched(_id, msg.sender, _box, _tmv, holderFee, _holder); } /// @dev Finishes the bond. /// @param _id A Bond ID. function finish(uint256 _id) external onlyIssuer(_id) validTx { Bond memory bond = bonds[_id]; // It's not necessary to check matching of the bond // since the expiration period cannot exceed 365 days. require(now < bond.expiration, "Bond expired"); uint256 _secondsPast = now.sub(bond.createdAt); (uint256 _eth, uint256 _debt) = getBox(bond.tBoxId); uint256 _commission = bond.tmv .mul(_secondsPast) .mul(bond.yearFee) .div(365 days) .div(divider); uint256 _sysTMV = _commission.mul(bond.sysFee).div(divider); address _holder = bond.holder; if (_sysTMV.add(_debt) > 0) { IToken(settings.tmvAddress()).transferFrom( msg.sender, address(this), _sysTMV.add(_debt) ); } if (_commission > 0) { IToken(settings.tmvAddress()).transferFrom( msg.sender, _holder, _commission.sub(_sysTMV) ); } if (_eth > 0) { ITBoxManager(settings.tBoxManager()).close(bond.tBoxId); delete bonds[_id]; msg.sender.transfer(_eth); } else { // when TBox no longer exists delete bonds[_id]; } emit BondFinished(_id, msg.sender, _holder); } /// @dev Executes expiration process of the bond. /// @param _id A Bond ID. function expire(uint256 _id) external matched(_id) validTx { require(now > bonds[_id].expiration, "Bond hasn't expired"); (uint256 _eth, uint256 _tmv) = getBox(bonds[_id].tBoxId); if (_eth == 0) { emit BondExpired(_id, bonds[_id].issuer, bonds[_id].holder); delete bonds[_id]; return; } uint256 _collateralPercent = ITBoxManager(settings.tBoxManager()).collateralPercent(bonds[_id].tBoxId); uint256 _targetCollateralPercent = settings.globalTargetCollateralization(); if (_collateralPercent > _targetCollateralPercent) { uint256 _ethTarget = _tmv.mul(_targetCollateralPercent).div(rate()); // mul and div by precision are omitted uint256 _issuerEth = _eth.sub(_ethTarget); uint256 _withdrawableEth = ITBoxManager(settings.tBoxManager()).withdrawableEth( bonds[_id].tBoxId ); if (_issuerEth > _withdrawableEth) { _issuerEth = _withdrawableEth; } ITBoxManager(settings.tBoxManager()).withdrawEth( bonds[_id].tBoxId, _issuerEth ); bonds[_id].issuer.transfer(_issuerEth); } _eth = ITBoxManager(settings.tBoxManager()).withdrawableEth( bonds[_id].tBoxId ); uint256 _commission = _eth.mul(bonds[_id].sysFee).div(divider); if (_commission > 0) { ITBoxManager(settings.tBoxManager()).withdrawEth( bonds[_id].tBoxId, _commission ); systemETH = systemETH.add(_commission); } ITBoxManager(settings.tBoxManager()).transferFrom( address(this), bonds[_id].holder, bonds[_id].tBoxId ); emit BondExpired(_id, bonds[_id].issuer, bonds[_id].holder); delete bonds[_id]; } /// @dev Returns TBox parameters. /// @param _id A Bond ID. function getBox(uint256 _id) public view returns(uint256, uint256) { return ITBoxManager(settings.tBoxManager()).boxes(_id); } /// @dev Needs to claim funds from the logic contract to execute finishing and expiration. function() external payable {} /// @dev Withdraws system fee. /// @param _beneficiary The address to forward funds to. function withdrawSystemETH(address _beneficiary) external onlyAdmin { require(_beneficiary != address(0), "Zero address, be careful"); require(systemETH > 0, "There is no available ETH"); uint256 _systemETH = systemETH; systemETH = 0; _beneficiary.transfer(_systemETH); } /// @dev Reclaims ERC20 tokens. /// @param _token The address of the ERC20 token. /// @param _beneficiary The address to forward funds to. function reclaimERC20(address _token, address _beneficiary) external onlyAdmin { require(_beneficiary != address(0), "Zero address, be careful"); uint256 _amount = IToken(_token).balanceOf(address(this)); require(_amount > 0, "There are no tokens"); IToken(_token).transfer(_beneficiary, _amount); } /// @dev Sets issuer fee. /// @param _value Commission percentage. function setIssuerFee(uint256 _value) external onlyAdmin { require(_value <= 10000, "Too much"); issuerFee = _value; emit BondIssuerFeeUpdated(_value); } /// @dev Sets holder fee. /// @param _value Commission percentage. function setHolderFee(uint256 _value) external onlyAdmin { require(_value <= 50000, "Too much"); holderFee = _value; emit BondHolderFeeUpdated(_value); } /// @dev Sets minimum deposit amount. /// @param _value The minimum deposit amount in wei. function setMinEther(uint256 _value) external onlyAdmin { require(_value <= 100 ether, "Too much"); minEther = _value; emit BondMinEtherUpdated(_value); } /// @dev Sets admin address. /// @param _newAdmin The address of the new admin. function changeAdmin(address _newAdmin) external onlyAdmin { require(_newAdmin != address(0), "Zero address, be careful"); admin = _newAdmin; } /// @dev Returns precision using for USD and commission calculation. function precision() public view returns(uint256) { return ITBoxManager(settings.tBoxManager()).precision(); } /// @dev Returns current oracle ETH/USD price with precision. function rate() public view returns(uint256) { return IOracle(settings.oracleAddress()).ethUsdPrice(); } /// @dev Transfers issuer's rights of an Order. function transferIssuerRights(address _to, uint256 _id) external onlyIssuer(_id) { require(_to != address(0), "Zero address, be careful"); bonds[_id].issuer = _to; emit IssuerRightsTransferred(msg.sender, _to, _id); } /// @dev Transfers holder's rights of an Order. function transferHolderRights(address _to, uint256 _id) external onlyHolder(_id) { require(_to != address(0), "Zero address, be careful"); bonds[_id].holder = _to; emit HolderRightsTransferred(msg.sender, _to, _id); } } pragma solidity 0.4.25; /// @title IOracle /// @dev Interface for getting the data from the oracle contract. interface IOracle { function ethUsdPrice() external view returns(uint256); } pragma solidity 0.4.25; /// @title ISettings /// @dev Interface for getting the data from settings contract. interface ISettings { function oracleAddress() external view returns(address); function minDeposit() external view returns(uint256); function sysFee() external view returns(uint256); function userFee() external view returns(uint256); function ratio() external view returns(uint256); function globalTargetCollateralization() external view returns(uint256); function tmvAddress() external view returns(uint256); function maxStability() external view returns(uint256); function minStability() external view returns(uint256); function gasPriceLimit() external view returns(uint256); function isFeeManager(address account) external view returns (bool); function tBoxManager() external view returns(address); } pragma solidity 0.4.25; /// @title ILogic /// @dev Interface for interaction with the TMV logic contract to manage Boxes. interface ITBoxManager { function create(uint256 withdraw) external payable returns (uint256); function precision() external view returns (uint256); function rate() external view returns (uint256); function transferFrom(address from, address to, uint256 tokenId) external; function close(uint256 id) external; function withdrawPercent(uint256 _collateral) external view returns(uint256); function boxes(uint256 id) external view returns(uint256, uint256); function withdrawEth(uint256 _id, uint256 _amount) external; function withdrawTmv(uint256 _id, uint256 _amount) external; function withdrawableEth(uint256 id) external view returns(uint256); function withdrawableTmv(uint256 collateral) external view returns(uint256); function maxCapAmount(uint256 _id) external view returns (uint256); function collateralPercent(uint256 _id) external view returns (uint256); function capitalize(uint256 _id, uint256 _tmv) external; function boxWithdrawableTmv(uint256 _id) external view returns(uint256); function addEth(uint256 _id) external payable; function capitalizeMax(uint256 _id) external payable; function withdrawTmvMax(uint256 _id) external payable; function addTmv(uint256 _id, uint256 _amount) external payable; } pragma solidity 0.4.25; /// @title IToken /// @dev Interface for interaction with the TMV token contract. interface IToken { function burnLogic(address from, uint256 value) external; function approve(address spender, uint256 value) external; function balanceOf(address who) external view returns (uint256); function mint(address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 tokenId) external; } pragma solidity 0.4.25; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'mul'); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, 'div'); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, 'sub'); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'add'); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
Uses to match the holder request. _id A Bond ID.
function takeBuyRequest(uint256 _id) external payable buyRequest(_id) validTx { address _holder = bonds[_id].holder; uint256 _sysEth = bonds[_id].deposit.mul(issuerFee).div(divider); systemETH = systemETH.add(_sysEth); uint256 _tmv = bonds[_id].deposit.mul(rate()).div(precision()); uint256 _box = ITBoxManager(settings.tBoxManager()).create.value(msg.value)(_tmv); bonds[_id].issuer = msg.sender; bonds[_id].tmv = _tmv; bonds[_id].expiration = bonds[_id].expiration.add(now); bonds[_id].sysFee = holderFee; bonds[_id].tBoxId = _box; bonds[_id].createdAt = now; msg.sender.transfer(bonds[_id].deposit.sub(_sysEth)); IToken(settings.tmvAddress()).transfer(_holder, _tmv); emit BondMatched(_id, msg.sender, _box, _tmv, holderFee, _holder); }
1,820,735
pragma solidity ^0.4.24; interface IDRCWalletMgrParams { function singleWithdrawMin() external returns (uint256); // min value of single withdraw function singleWithdrawMax() external returns (uint256); // Max value of single withdraw function dayWithdraw() external returns (uint256); // Max value of one day of withdraw function monthWithdraw() external returns (uint256); // Max value of one month of withdraw function dayWithdrawCount() external returns (uint256); // Max number of withdraw counting function chargeFee() external returns (uint256); // the charge fee for withdraw function chargeFeePool() external returns (address); // the address that will get the returned charge fees. } interface IDRCWalletStorage { // get the deposit address for this _wallet address function walletDeposits(address _wallet) external view returns (address); // get frozen status for the deposit address function frozenDeposits(address _deposit) external view returns (bool); // get a wallet address by the deposit address and the index function wallet(address _deposit, uint256 _ind) external view returns (address); // get a wallet name by the deposit address and the index function walletName(address _deposit, uint256 _ind) external view returns (bytes32); // get the wallets number of a deposit address function walletsNumber(address _deposit) external view returns (uint256); // get the frozen amount of the deposit address function frozenAmount(address _deposit) external view returns (uint256); // get the balance of the deposit address function balanceOf(address _deposit) external view returns (uint256); // get the deposit address by index function depositAddressByIndex(uint256 _ind) external view returns (address); // get the frozen amount of the deposit address function size() external view returns (uint256); // judge if the _deposit address exsisted. function isExisted(address _deposit) external view returns (bool); // add one deposit address for that wallet function addDeposit(address _wallet, address _depositAddr) external returns (bool); // change the default wallet address for the deposit address function changeDefaultWallet(address _oldWallet, address _newWallet) external returns (bool); // freeze or release the tokens that has been deposited in the deposit address. function freezeTokens(address _deposit, bool _freeze, uint256 _value) external returns (bool); // increase balance of this deposit address function increaseBalance(address _deposit, uint256 _value) external returns (bool); // decrease balance of this deposit address function decreaseBalance(address _deposit, uint256 _value) external returns (bool); // add withdraw address for one deposit addresss function addWithdraw(address _deposit, bytes32 _name, address _withdraw) external returns (bool); // change the withdraw wallet name function changeWalletName(address _deposit, bytes32 _newName, address _wallet) external returns (bool); // remove deposit contract address from storage function removeDeposit(address _depositAddr) external returns (bool); // withdraw tokens from this contract function withdrawToken(address _token, address _to, uint256 _value) external returns (bool); } 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; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract Withdrawable is Ownable { event ReceiveEther(address _from, uint256 _value); event WithdrawEther(address _to, uint256 _value); event WithdrawToken(address _token, address _to, uint256 _value); /** * @dev recording receiving ether from msn.sender */ function () payable public { emit ReceiveEther(msg.sender, msg.value); } /** * @dev withdraw,send ether to target * @param _to is where the ether will be sent to * _amount is the number of the ether */ function withdraw(address _to, uint _amount) public onlyOwner returns (bool) { require(_to != address(0)); _to.transfer(_amount); emit WithdrawEther(_to, _amount); return true; } /** * @dev withdraw tokens, send tokens to target * * @param _token the token address that will be withdraw * @param _to is where the tokens will be sent to * _value is the number of the token */ function withdrawToken(address _token, address _to, uint256 _value) public onlyOwner returns (bool) { require(_to != address(0)); require(_token != address(0)); ERC20 tk = ERC20(_token); tk.transfer(_to, _value); emit WithdrawToken(_token, _to, _value); return true; } /** * @dev receive approval from an ERC20 token contract, and then gain the tokens, * then take a record * * @param _from address The address which you want to send tokens from * @param _value uint256 the amounts of tokens to be sent * @param _token address the ERC20 token address * @param _extraData bytes the extra data for the record */ // function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public { // require(_token != address(0)); // require(_from != address(0)); // ERC20 tk = ERC20(_token); // require(tk.transferFrom(_from, this, _value)); // emit ReceiveDeposit(_from, _value, _token, _extraData); // } } contract TokenDestructible is Ownable { constructor() public payable { } /** * @notice Terminate contract and refund to owner * @param _tokens List of addresses of ERC20 or ERC20Basic token contracts to refund. * @notice The called token contracts could try to re-enter this contract. Only supply token contracts you trust. */ function destroy(address[] _tokens) public onlyOwner { // Transfer tokens to owner for (uint256 i = 0; i < _tokens.length; i++) { ERC20Basic token = ERC20Basic(_tokens[i]); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); } // Transfer Eth to owner and terminate contract selfdestruct(owner); } } contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } contract DepositWithdraw is Claimable, Withdrawable, TokenDestructible { using SafeMath for uint256; /** * transaction record */ struct TransferRecord { uint256 timeStamp; address account; uint256 value; } /** * accumulated transferring amount record */ struct accumulatedRecord { uint256 mul; uint256 count; uint256 value; } TransferRecord[] deposRecs; // record all the deposit tx data TransferRecord[] withdrRecs; // record all the withdraw tx data accumulatedRecord dayWithdrawRec; // accumulated amount record for one day accumulatedRecord monthWithdrawRec; // accumulated amount record for one month address wallet; // the binded withdraw address event ReceiveDeposit(address _from, uint256 _value, address _token, bytes _extraData); /** * @dev constructor of the DepositWithdraw contract * @param _wallet the binded wallet address to this depositwithdraw contract */ constructor(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; } /** * @dev set the default wallet address * @param _wallet the default wallet address binded to this deposit contract */ function setWithdrawWallet(address _wallet) onlyOwner public returns (bool) { require(_wallet != address(0)); wallet = _wallet; return true; } /** * @dev util function to change bytes data to bytes32 data * @param _data the bytes data to be converted */ function bytesToBytes32(bytes _data) public pure returns (bytes32 result) { assembly { result := mload(add(_data, 32)) } } /** * @dev receive approval from an ERC20 token contract, take a record * * @param _from address The address which you want to send tokens from * @param _value uint256 the amounts of tokens to be sent * @param _token address the ERC20 token address * @param _extraData bytes the extra data for the record */ function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) onlyOwner public { require(_token != address(0)); require(_from != address(0)); ERC20 tk = ERC20(_token); require(tk.transferFrom(_from, this, _value)); bytes32 timestamp = bytesToBytes32(_extraData); deposRecs.push(TransferRecord(uint256(timestamp), _from, _value)); emit ReceiveDeposit(_from, _value, _token, _extraData); } // function authorize(address _token, address _spender, uint256 _value) onlyOwner public returns (bool) { // ERC20 tk = ERC20(_token); // require(tk.approve(_spender, _value)); // return true; // } /** * @dev record withdraw into this contract * * @param _time the timstamp of the withdraw time * @param _to is where the tokens will be sent to * @param _value is the number of the token */ function recordWithdraw(uint256 _time, address _to, uint256 _value) onlyOwner public { withdrRecs.push(TransferRecord(_time, _to, _value)); } /** * @dev check if withdraw amount is not valid * * @param _params the limitation parameters for withdraw * @param _value is the number of the token * @param _time the timstamp of the withdraw time */ function checkWithdrawAmount(address _params, uint256 _value, uint256 _time) public returns (bool) { IDRCWalletMgrParams params = IDRCWalletMgrParams(_params); require(_value <= params.singleWithdrawMax()); require(_value >= params.singleWithdrawMin()); uint256 daysCount = _time.div(86400); // one day of seconds if (daysCount <= dayWithdrawRec.mul) { dayWithdrawRec.count = dayWithdrawRec.count.add(1); dayWithdrawRec.value = dayWithdrawRec.value.add(_value); require(dayWithdrawRec.count <= params.dayWithdrawCount()); require(dayWithdrawRec.value <= params.dayWithdraw()); } else { dayWithdrawRec.mul = daysCount; dayWithdrawRec.count = 1; dayWithdrawRec.value = _value; } uint256 monthsCount = _time.div(86400 * 30); if (monthsCount <= monthWithdrawRec.mul) { monthWithdrawRec.count = monthWithdrawRec.count.add(1); monthWithdrawRec.value = monthWithdrawRec.value.add(_value); require(monthWithdrawRec.value <= params.monthWithdraw()); } else { monthWithdrawRec.mul = monthsCount; monthWithdrawRec.count = 1; monthWithdrawRec.value = _value; } return true; } /** * @dev withdraw tokens, send tokens to target * * @param _token the token address that will be withdraw * @param _params the limitation parameters for withdraw * @param _time the timstamp of the withdraw time * @param _to is where the tokens will be sent to * _value is the number of the token * _fee is the amount of the transferring costs * _tokenReturn is the address that return back the tokens of the _fee */ function withdrawToken(address _token, address _params, uint256 _time, address _to, uint256 _value, uint256 _fee, address _tokenReturn) public onlyOwner returns (bool) { require(_to != address(0)); require(_token != address(0)); require(_value > _fee); // require(_tokenReturn != address(0)); require(checkWithdrawAmount(_params, _value, _time)); ERC20 tk = ERC20(_token); uint256 realAmount = _value.sub(_fee); require(tk.transfer(_to, realAmount)); if (_tokenReturn != address(0) && _fee > 0) { require(tk.transfer(_tokenReturn, _fee)); } recordWithdraw(_time, _to, realAmount); emit WithdrawToken(_token, _to, realAmount); return true; } /** * @dev withdraw tokens, send tokens to target default wallet * * @param _token the token address that will be withdraw * @param _params the limitation parameters for withdraw * @param _time the timestamp occur the withdraw record * @param _value is the number of the token * _fee is the amount of the transferring costs * —tokenReturn is the address that return back the tokens of the _fee */ function withdrawTokenToDefault(address _token, address _params, uint256 _time, uint256 _value, uint256 _fee, address _tokenReturn) public onlyOwner returns (bool) { return withdrawToken(_token, _params, _time, wallet, _value, _fee, _tokenReturn); } /** * @dev get the Deposit records number * */ function getDepositNum() public view returns (uint256) { return deposRecs.length; } /** * @dev get the one of the Deposit records * * @param _ind the deposit record index */ function getOneDepositRec(uint256 _ind) public view returns (uint256, address, uint256) { require(_ind < deposRecs.length); return (deposRecs[_ind].timeStamp, deposRecs[_ind].account, deposRecs[_ind].value); } /** * @dev get the withdraw records number * */ function getWithdrawNum() public view returns (uint256) { return withdrRecs.length; } /** * @dev get the one of the withdraw records * * @param _ind the withdraw record index */ function getOneWithdrawRec(uint256 _ind) public view returns (uint256, address, uint256) { require(_ind < withdrRecs.length); return (withdrRecs[_ind].timeStamp, withdrRecs[_ind].account, withdrRecs[_ind].value); } } contract DelayedClaimable is Claimable { uint256 public end; uint256 public start; /** * @dev Used to specify the time period during which a pending * owner can claim ownership. * @param _start The earliest time ownership can be claimed. * @param _end The latest time ownership can be claimed. */ function setLimits(uint256 _start, uint256 _end) public onlyOwner { require(_start <= _end); end = _end; start = _start; } /** * @dev Allows the pendingOwner address to finalize the transfer, as long as it is called within * the specified start and end time. */ function claimOwnership() public onlyPendingOwner { require((block.number <= end) && (block.number >= start)); emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); end = 0; } } contract OwnerContract is DelayedClaimable { Claimable public ownedContract; address public pendingOwnedOwner; // address internal origOwner; /** * @dev bind a contract as its owner * * @param _contract the contract address that will be binded by this Owner Contract */ function bindContract(address _contract) onlyOwner public returns (bool) { require(_contract != address(0)); ownedContract = Claimable(_contract); // origOwner = ownedContract.owner(); // take ownership of the owned contract if (ownedContract.owner() != address(this)) { ownedContract.claimOwnership(); } return true; } /** * @dev change the owner of the contract from this contract address to the original one. * */ // function transferOwnershipBack() onlyOwner public { // ownedContract.transferOwnership(origOwner); // ownedContract = Claimable(address(0)); // origOwner = address(0); // } /** * @dev change the owner of the contract from this contract address to another one. * * @param _nextOwner the contract address that will be next Owner of the original Contract */ function changeOwnershipto(address _nextOwner) onlyOwner public { require(ownedContract != address(0)); if (ownedContract.owner() != pendingOwnedOwner) { ownedContract.transferOwnership(_nextOwner); pendingOwnedOwner = _nextOwner; // ownedContract = Claimable(address(0)); // origOwner = address(0); } else { // the pending owner has already taken the ownership ownedContract = Claimable(address(0)); pendingOwnedOwner = address(0); } } /** * @dev to confirm the owner of the owned contract has already been transferred. * */ function ownedOwnershipTransferred() onlyOwner public returns (bool) { require(ownedContract != address(0)); if (ownedContract.owner() == pendingOwnedOwner) { // the pending owner has already taken the ownership ownedContract = Claimable(address(0)); pendingOwnedOwner = address(0); return true; } else { return false; } } } contract DRCWalletManager is OwnerContract, Withdrawable, TokenDestructible { using SafeMath for uint256; /** * withdraw wallet description */ // struct WithdrawWallet { // bytes32 name; // address walletAddr; // } /** * Deposit data storage */ // struct DepositRepository { // // uint256 balance; // uint256 frozen; // WithdrawWallet[] withdrawWallets; // // mapping (bytes32 => address) withdrawWallets; // } // mapping (address => DepositRepository) depositRepos; // mapping (address => address) public walletDeposits; // mapping (address => bool) public frozenDeposits; ERC20 public tk; // the token will be managed IDRCWalletMgrParams public params; // the parameters that the management needs IDRCWalletStorage public walletStorage; // the deposits and wallets data stored in a contract event CreateDepositAddress(address indexed _wallet, address _deposit); event FrozenTokens(address indexed _deposit, bool _freeze, uint256 _value); event ChangeDefaultWallet(address indexed _oldWallet, address _newWallet); /** * @dev initialize this contract with token, parameters and storage address * * @param _token the token address that will be withdraw * @param _walletParams the wallet management parameters */ function initialize(address _token, address _walletParams, address _walletStorage) onlyOwner public returns (bool) { require(_token != address(0)); require(_walletParams != address(0)); tk = ERC20(_token); params = IDRCWalletMgrParams(_walletParams); walletStorage = IDRCWalletStorage(_walletStorage); return true; } /** * @dev create deposit contract address for the default withdraw wallet * * @param _wallet the binded default withdraw wallet address */ function createDepositContract(address _wallet) onlyOwner public returns (address) { require(_wallet != address(0)); DepositWithdraw deposWithdr = new DepositWithdraw(_wallet); // new contract for deposit address _deposit = address(deposWithdr); // walletDeposits[_wallet] = _deposit; // WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; // withdrawWalletList.push(WithdrawWallet("default wallet", _wallet)); // // depositRepos[_deposit].balance = 0; // depositRepos[_deposit].frozen = 0; walletStorage.addDeposit(_wallet, _deposit); // deposWithdr.authorize(address(tk), this, 1e27); // give authorization to owner contract emit CreateDepositAddress(_wallet, _deposit); return _deposit; } /** * @dev deposit a value of funds to the deposit address * * @param _deposit the deposit address * @param _increase increase or decrease the value * @param _value the deposit funds value */ function doDeposit(address _deposit, bool _increase, uint256 _value) onlyOwner public returns (bool) { return (_increase ? walletStorage.increaseBalance(_deposit, _value) : walletStorage.decreaseBalance(_deposit, _value)); } /** * @dev get deposit contract address by using the default withdraw wallet * * @param _wallet the binded default withdraw wallet address */ function getDepositAddress(address _wallet) onlyOwner public view returns (address) { require(_wallet != address(0)); // address deposit = walletDeposits[_wallet]; // return deposit; return walletStorage.walletDeposits(_wallet); } /** * @dev get deposit balance and frozen amount by using the deposit address * * @param _deposit the deposit contract address */ function getDepositInfo(address _deposit) onlyOwner public view returns (uint256, uint256) { require(_deposit != address(0)); uint256 _balance = walletStorage.balanceOf(_deposit); // uint256 frozenAmount = depositRepos[_deposit].frozen; uint256 frozenAmount = walletStorage.frozenAmount(_deposit); // depositRepos[_deposit].balance = _balance; return (_balance, frozenAmount); } /** * @dev get the number of withdraw wallet addresses bindig to the deposit contract address * * @param _deposit the deposit contract address */ function getDepositWithdrawCount(address _deposit) onlyOwner public view returns (uint) { require(_deposit != address(0)); // WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; // uint len = withdrawWalletList.length; uint len = walletStorage.walletsNumber(_deposit); return len; } /** * @dev get the withdraw wallet addresses list binding to the deposit contract address * * @param _deposit the deposit contract address * @param _indices the array of indices of the withdraw wallets */ function getDepositWithdrawList(address _deposit, uint[] _indices) onlyOwner public view returns (bytes32[], address[]) { require(_indices.length != 0); bytes32[] memory names = new bytes32[](_indices.length); address[] memory wallets = new address[](_indices.length); for (uint i = 0; i < _indices.length; i = i.add(1)) { // WithdrawWallet storage wallet = depositRepos[_deposit].withdrawWallets[_indices[i]]; // names[i] = wallet.name; // wallets[i] = wallet.walletAddr; names[i] = walletStorage.walletName(_deposit, i); wallets[i] = walletStorage.wallet(_deposit, i); } return (names, wallets); } /** * @dev change the default withdraw wallet address binding to the deposit contract address * * @param _oldWallet the previous default withdraw wallet * @param _newWallet the new default withdraw wallet */ function changeDefaultWithdraw(address _oldWallet, address _newWallet) onlyOwner public returns (bool) { require(_oldWallet != address(0)); require(_newWallet != address(0)); address deposit = walletStorage.walletDeposits(_oldWallet); DepositWithdraw deposWithdr = DepositWithdraw(deposit); require(deposWithdr.setWithdrawWallet(_newWallet)); // WithdrawWallet[] storage withdrawWalletList = depositRepos[deposit].withdrawWallets; // withdrawWalletList[0].walletAddr = _newWallet; bool res = walletStorage.changeDefaultWallet(_oldWallet, _newWallet); emit ChangeDefaultWallet(_oldWallet, _newWallet); return res; } /** * @dev freeze the tokens in the deposit address * * @param _deposit the deposit address * @param _freeze to freeze or release * @param _value the amount of tokens need to be frozen */ function freezeTokens(address _deposit, bool _freeze, uint256 _value) onlyOwner public returns (bool) { // require(_deposit != address(0)); // frozenDeposits[_deposit] = _freeze; // if (_freeze) { // depositRepos[_deposit].frozen = depositRepos[_deposit].frozen.add(_value); // } else { // require(_value <= depositRepos[_deposit].frozen); // depositRepos[_deposit].frozen = depositRepos[_deposit].frozen.sub(_value); // } bool res = walletStorage.freezeTokens(_deposit, _freeze, _value); emit FrozenTokens(_deposit, _freeze, _value); return res; } /** * @dev withdraw the tokens from the deposit address to default wallet with charge fee * * @param _deposit the deposit address * @param _time the timestamp the withdraw occurs * @param _value the amount of tokens need to be frozen * @param _check if we will check the value is valid or meet the limit condition */ function withdrawWithFee(address _deposit, uint256 _time, uint256 _value, bool _check) onlyOwner public returns (bool) { // WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; // return withdrawWithFee(_deposit, _time, withdrawWalletList[0].name, withdrawWalletList[0].walletAddr, _value, _check); bytes32 defaultWalletName = walletStorage.walletName(_deposit, 0); address defaultWallet = walletStorage.wallet(_deposit, 0); return withdrawWithFee(_deposit, _time, defaultWalletName, defaultWallet, _value, _check); } /** * @dev check if the wallet name is not matching the expected wallet address * * @param _deposit the deposit address * @param _name the withdraw wallet name * @param _to the withdraw wallet address */ function checkWithdrawAddress(address _deposit, bytes32 _name, address _to) public view returns (bool, bool) { // uint len = depositRepos[_deposit].withdrawWallets.length; uint len = walletStorage.walletsNumber(_deposit); for (uint i = 0; i < len; i = i.add(1)) { // WithdrawWallet memory wallet = depositRepos[_deposit].withdrawWallets[i]; // if (_name == wallet.name) { // return(true, (_to == wallet.walletAddr)); // } // if (_to == wallet.walletAddr) { // return(true, true); // } bytes32 walletName = walletStorage.walletName(_deposit, i); address walletAddr = walletStorage.wallet(_deposit, i); if (_name == walletName) { return(true, (_to == walletAddr)); } if (_to == walletAddr) { return(false, true); } } return (false, false); } /** * @dev withdraw tokens from this contract, send tokens to target withdraw wallet * * @param _deposWithdr the deposit contract that will record withdrawing * @param _time the timestamp occur the withdraw record * @param _to the address the token will be transfer to * @param _value the token transferred value */ function withdrawFromThis(DepositWithdraw _deposWithdr, uint256 _time, address _to, uint256 _value) private returns (bool) { uint256 fee = params.chargeFee(); uint256 realAmount = _value.sub(fee); address tokenReturn = params.chargeFeePool(); if (tokenReturn != address(0) && fee > 0) { // require(tk.transfer(tokenReturn, fee)); require(walletStorage.withdrawToken(tk, tokenReturn, fee)); } // require (tk.transfer(_to, realAmount)); require(walletStorage.withdrawToken(tk, _to, realAmount)); _deposWithdr.recordWithdraw(_time, _to, realAmount); return true; } /** * @dev withdraw tokens, send tokens to target withdraw wallet * * @param _deposit the deposit address that will be withdraw from * @param _time the timestamp occur the withdraw record * @param _name the withdraw address alias name to verify * @param _to the address the token will be transfer to * @param _value the token transferred value * @param _check if we will check the value is valid or meet the limit condition */ function withdrawWithFee(address _deposit, uint256 _time, bytes32 _name, address _to, uint256 _value, bool _check) onlyOwner public returns (bool) { require(_deposit != address(0)); require(_to != address(0)); uint256 totalBalance = walletStorage.balanceOf(_deposit); uint256 frozen = walletStorage.frozenAmount(_deposit); // uint256 available = totalBalance.sub(frozen); // require(_value <= available); if (_check) { require(_value <= totalBalance.sub(frozen)); } uint256 _balance = tk.balanceOf(_deposit); bool exist; bool correct; // WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; (exist, correct) = checkWithdrawAddress(_deposit, _name, _to); if(!exist) { // withdrawWalletList.push(WithdrawWallet(_name, _to)); if (!correct) { walletStorage.addWithdraw(_deposit, _name, _to); } else { walletStorage.changeWalletName(_deposit, _name, _to); } } else { require(correct, "wallet address must be correct with wallet name!"); } DepositWithdraw deposWithdr = DepositWithdraw(_deposit); /** * if deposit address doesn't have enough tokens to withdraw, * then withdraw from this contract. Record this in the independent deposit contract. */ if (_value > _balance) { require(deposWithdr.checkWithdrawAmount(address(params), _value, _time)); if(_balance > 0) { require(deposWithdr.withdrawToken(address(tk), address(walletStorage), _balance)); } require(withdrawFromThis(deposWithdr, _time, _to, _value)); // return true; } else { require(deposWithdr.withdrawToken(address(tk), address(params), _time, _to, _value, params.chargeFee(), params.chargeFeePool())); } return walletStorage.decreaseBalance(_deposit, _value); } /** * @dev destory the old depoist contract and take back the tokens * * @param _deposit the deposit address */ function destroyDepositContract(address _deposit) onlyOwner public returns (bool) { require(_deposit != address(0)); DepositWithdraw deposWithdr = DepositWithdraw(_deposit); address[] memory tokens = new address[](1); tokens[0] = address(tk); deposWithdr.destroy(tokens); return walletStorage.removeDeposit(_deposit); } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); }
get the withdraw wallet addresses list binding to the deposit contract address _deposit the deposit contract address _indices the array of indices of the withdraw wallets/ WithdrawWallet storage wallet = depositRepos[_deposit].withdrawWallets[_indices[i]]; names[i] = wallet.name; wallets[i] = wallet.walletAddr;
function getDepositWithdrawList(address _deposit, uint[] _indices) onlyOwner public view returns (bytes32[], address[]) { require(_indices.length != 0); bytes32[] memory names = new bytes32[](_indices.length); address[] memory wallets = new address[](_indices.length); for (uint i = 0; i < _indices.length; i = i.add(1)) { names[i] = walletStorage.walletName(_deposit, i); wallets[i] = walletStorage.wallet(_deposit, i); } return (names, wallets); }
12,845,646
./partial_match/1/0xcAB2f2a8ab011ED7cD74fB77C49f057d9F90C2A7/sources/LoanToken.sol
Emitted when the loan is funded lender Address which funded the loan/ Emitted when transfer whitelist is updated account Account to whitelist for transfers status New whitelist status/ Emitted when borrower withdraws funds beneficiary Account which will receive funds/ Emitted when term is over status Final loan status returnedAmount Amount that was returned before expiry/ Emitted when a LoanToken is redeemed for underlying currencyTokens receiver Receiver of currencyTokens burnedAmount Amount of LoanTokens burned redeemedAmount Amount of currencyToken received/ Emitted when a LoanToken is repaid by the borrower in underlying currencyTokens repayer Sender of currencyTokens repaidAmount Amount of currencyToken repaid/ Emitted when borrower reclaims remaining currencyTokens borrower Receiver of remaining currencyTokens reclaimedAmount Amount of currencyTokens repaid/ Emitted when loan gets liquidated status Final loan status/ Create a Loan _currencyToken Token to lend _borrower Borrower address _amount Borrow amount of currency tokens _term Loan length _apy Loan APY/
function _beforeTokenTransfer( address from, address to, uint256 amount } } ) public ERC20("Loan Token", "LOAN") { require(_lender != address(0), "LoanToken: Lender is not set"); currencyToken = _currencyToken; borrower = _borrower; liquidator = _liquidator; amount = _amount; term = _term; apy = _apy; lender = _lender; debt = interest(amount); }
3,633,949
./partial_match/5/0xA109b34B1974C1f6BA554607F46E202926728E14/sources/src/InterestRateModel.sol
Returns the interest rate state of a position position Address of position (owner) return _ Interest rate state of the position
function getPositionIRS(address position) public view returns (PositionIRS memory) { return _checkPositionIRS(_positionIRS[position]); }
16,850,779
contract IERC20Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) 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) 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) 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) 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) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Owned { address public owner; address public newOwner; function Owned() public{ owner = msg.sender; } modifier onlyOwner { assert(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != owner); newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = 0x0; } event OwnerUpdate(address _prevOwner, address _newOwner); } contract SafeMath { uint256 constant MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; function safeAdd(uint256 x, uint256 y) pure internal returns (uint256 z) { require(x <= MAX_UINT256 - y); return x + y; } function safeSub(uint256 x, uint256 y) pure internal returns (uint256 z) { require(x >= y); return x - y; } function safeMul(uint256 x, uint256 y) pure internal returns (uint256 z) { if (y == 0) { return 0; } require(x <= (MAX_UINT256 / y)); return x * y; } } contract LinkedList { struct Element { uint previous; uint next; address data; } uint public size; uint public tail; uint public head; mapping(uint => Element) elements; mapping(address => uint) elementLocation; function addItem(address _newItem) public returns (bool) { Element memory elem = Element(0, 0, _newItem); if (size == 0) { head = 1; } else { elements[tail].next = tail + 1; elem.previous = tail; } elementLocation[_newItem] = tail + 1; elements[tail + 1] = elem; size++; tail++; return true; } function removeItem(address _item) public returns (bool) { uint key; if (elementLocation[_item] == 0) { return false; }else { key = elementLocation[_item]; } if (size == 1) { tail = 0; head = 0; }else if (key == head) { head = elements[head].next; }else if (key == tail) { tail = elements[tail].previous; elements[tail].next = 0; }else { elements[key - 1].next = elements[key].next; elements[key + 1].previous = elements[key].previous; } size--; delete elements[key]; elementLocation[_item] = 0; return true; } function getAllElements() constant public returns(address[]) { address[] memory tempElementArray = new address[](size); uint cnt = 0; uint currentElemId = head; while (cnt < size) { tempElementArray[cnt] = elements[currentElemId].data; currentElemId = elements[currentElemId].next; cnt += 1; } return tempElementArray; } function getElementAt(uint _index) constant public returns (address) { return elements[_index].data; } function getElementLocation(address _element) constant public returns (uint) { return elementLocation[_element]; } function getNextElement(uint _currElementId) constant public returns (uint) { return elements[_currElementId].next; } } contract ICreditBIT{ function claimGameReward(address _champion, uint _lockedTokenAmount, uint _lockTime) returns (uint error); } contract CreditGAME is Owned, SafeMath, LinkedList{ mapping(address => bool) approvedGames; mapping(address => GameLock) gameLocks; mapping(address => bool) public isGameLocked; mapping(uint => address) public concludedGames; uint public amountLocked = 0; uint public concludedGameIndex = 0; struct GameLock{ uint amount; uint lockDuration; } event LockParameters(address gameAddress, uint totalParticipationAmount, uint tokenLockDuration); event UnlockParameters(address gameAddress, uint totalParticipationAmount); event GameConcluded(address gameAddress); //SET TOKEN ADDRESS BEFORE DEPLOY address public tokenAddress = 0xAef38fBFBF932D1AeF3B808Bc8fBd8Cd8E1f8BC5; /** * Set CRB token address here * **/ function setTokenAddress(address _tokenAddress) onlyOwner public { tokenAddress = _tokenAddress; } /** * When new game is created it needs to be approved here before it starts. * **/ function addApprovedGame(address _gameAddress) onlyOwner public{ approvedGames[_gameAddress] = true; addItem(_gameAddress); } /** * Manually remove approved game. * **/ function removeApprovedGame(address _gameAddress) onlyOwner public{ approvedGames[_gameAddress] = false; removeItem(_gameAddress); } /** * Remove failed game. * **/ function removeFailedGame() public{ require(approvedGames[msg.sender] == true); removeItem(msg.sender); approvedGames[msg.sender] = false; concludedGames[concludedGameIndex] = msg.sender; concludedGameIndex++; emit GameConcluded(msg.sender); } /** * Verify if game is approved * **/ function isGameApproved(address _gameAddress) view public returns(bool){ if(approvedGames[_gameAddress] == true){ return true; }else{ return false; } } /** * Funds must be transfered by calling contract before calling this contract. * msg.sender is address of calling contract that must be approved. * **/ function createLock(address _winner, uint _totalParticipationAmount, uint _tokenLockDuration) public { require(approvedGames[msg.sender] == true); require(isGameLocked[msg.sender] == false); //Create gameLock GameLock memory gameLock = GameLock(_totalParticipationAmount, block.number + _tokenLockDuration); gameLocks[msg.sender] = gameLock; isGameLocked[msg.sender] = true; amountLocked = safeAdd(amountLocked, _totalParticipationAmount); //Transfer game credits to winner generateChampionTokens(_winner, _totalParticipationAmount, _tokenLockDuration); emit LockParameters(msg.sender, _totalParticipationAmount, block.number + _tokenLockDuration); } /** * Call CRB token to mint champion tokens * **/ function generateChampionTokens(address _winner, uint _totalParticipationAmount, uint _tokenLockDuration) internal{ ICreditBIT(tokenAddress).claimGameReward(_winner, _totalParticipationAmount, _tokenLockDuration); } /** * Check the CRB balance of this. * **/ function checkInternalBalance() public view returns(uint256 tokenBalance) { return IERC20Token(tokenAddress).balanceOf(address(this)); } /** * Method called by game contract * msg.sender is address of calling contract that must be approved. **/ function removeLock() public{ require(approvedGames[msg.sender] == true); require(isGameLocked[msg.sender] == true); require(checkIfLockCanBeRemoved(msg.sender) == true); GameLock memory gameLock = gameLocks[msg.sender]; //transfer tokens to game contract IERC20Token(tokenAddress).transfer(msg.sender, gameLock.amount); delete(gameLocks[msg.sender]); //clean up amountLocked = safeSub(amountLocked, gameLock.amount); isGameLocked[msg.sender] = false; emit UnlockParameters(msg.sender, gameLock.amount); } /** * Method called by game contract when last participant has withdrawn * msg.sender is address of calling contract that must be approved. **/ function cleanUp() public{ require(approvedGames[msg.sender] == true); require(isGameLocked[msg.sender] == false); removeItem(msg.sender); approvedGames[msg.sender] = false; concludedGames[concludedGameIndex] = msg.sender; concludedGameIndex++; emit GameConcluded(msg.sender); } /** * Failsafe if game needs to be removed. Tokens are transfered to _tokenHolder address * **/ function removeGameManually(address _gameAddress, address _tokenHolder) onlyOwner public{ GameLock memory gameLock = gameLocks[_gameAddress]; //transfer tokens to game contract IERC20Token(tokenAddress).transfer(_tokenHolder, gameLock.amount); //clean up amountLocked = safeSub(amountLocked, gameLock.amount); delete(gameLocks[_gameAddress]); isGameLocked[_gameAddress] = false; removeItem(_gameAddress); approvedGames[_gameAddress] = false; } /** * Get gamelock parameters: CRB amount locked, CRB lock duration * **/ function getGameLock(address _gameAddress) public view returns(uint, uint){ require(isGameLocked[_gameAddress] == true); GameLock memory gameLock = gameLocks[_gameAddress]; return(gameLock.amount, gameLock.lockDuration); } /** * Verify if game is locked * **/ function isGameLocked(address _gameAddress) public view returns(bool){ if(isGameLocked[_gameAddress] == true){ return true; }else{ return false; } } /** * Check if game lock can be removed * **/ function checkIfLockCanBeRemoved(address _gameAddress) public view returns(bool){ require(approvedGames[_gameAddress] == true); require(isGameLocked[_gameAddress] == true); GameLock memory gameLock = gameLocks[_gameAddress]; if(gameLock.lockDuration < block.number){ return true; }else{ return false; } } /** * Kill contract if needed * **/ function killContract() onlyOwner public { selfdestruct(owner); } }
Funds must be transfered by calling contract before calling this contract. msg.sender is address of calling contract that must be approved./Create gameLockTransfer game credits to winner
function createLock(address _winner, uint _totalParticipationAmount, uint _tokenLockDuration) public { require(approvedGames[msg.sender] == true); require(isGameLocked[msg.sender] == false); GameLock memory gameLock = GameLock(_totalParticipationAmount, block.number + _tokenLockDuration); gameLocks[msg.sender] = gameLock; isGameLocked[msg.sender] = true; amountLocked = safeAdd(amountLocked, _totalParticipationAmount); generateChampionTokens(_winner, _totalParticipationAmount, _tokenLockDuration); emit LockParameters(msg.sender, _totalParticipationAmount, block.number + _tokenLockDuration); }
4,807,301
./partial_match/42/0xB45F2e74d0fEc8E2aaa49bEc38F5178Bd880EcF7/sources/IdleStrategyUSDTTestnet.sol
Returns the current balance. Ignores COMP that was not liquidated and invested./ NOTE: The use of virtual price is okay for appreciating assets inside IDLE, but would be wrong and exploitable if funds were lost by IDLE, indicated by the virtualPrice being greater than the token price.
function investedUnderlyingBalance() public view returns (uint256) { if (protected) { require(virtualPrice <= idleTokenHelper.getRedeemPrice(idleUnderlying), "virtual price is higher than needed"); } uint256 invested = IERC20(idleUnderlying).balanceOf(address(this)).mul(virtualPrice).div(1e18); return invested.add(IERC20(underlying).balanceOf(address(this))); }
8,839,513
pragma solidity ^0.8.10; pragma abicoder v2; import "../DjinnBottleUSDC.sol"; import "../interfaces/CTokenInterfaces.sol"; import "../interfaces/ComptrollerInterface.sol"; import "../interfaces/IStdReference.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import "../interfaces/IMasterChef.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract DeltaNeutralFtmTomb is ERC20 { //Contract Specifics address public creator; uint private constant CREATOR_FEE = 100; //1% address public treasuryWallet; DjinnBottleUSDC public VAULT; //Balances For Withdraw mapping(address => uint) public tokenBorrowBalance; //18 decimals mapping(address => uint) public mintedETH; mapping(address => uint) public mintedUSDC; //Cream Finance Contracts (also just the Iron Bank Contracts) address public constant crUSDC = 0x328A7b4d538A2b3942653a9983fdA3C12c571141; address public constant crETH = 0xcc3E89fBc10e155F1164f8c9Cf0703aCDe53f6Fd; //Public Tokens address public constant USDC = 0x04068DA6C83AFCFA0e13ba15A6696662335D5B75; address public constant WETH = 0x74b23882a30290451A17c44f4F05243b6b58C76d; address public constant WFTM = 0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83; address public constant TOMB = 0x6c021Ae822BEa943b2E66552bDe1D2696a53fbB7; address public constant TSHARE = 0x4cdF39285D7Ca8eB3f090fDA0C069ba5F4145B37; //SpookySwap Router, LP, TSHAREPool address public constant spookyAddress = 0xF491e7B69E4244ad4002BC14e878a34207E38c29; address public constant spookyFtmTombLP = 0x2A651563C9d3Af67aE0388a5c8F89b867038089e; address public constant tShareRewardPool = 0xcc0a87F7e7c693042a9Cc703661F5060c80ACb43; //Contract Interfaces IUniswapV2Router02 public immutable spookyRouter; ComptrollerInterface public immutable comptroller; IStdReference public immutable priceOracle; constructor(DjinnBottleUSDC _djBottle, IUniswapV2Router02 _spookyRouter, ComptrollerInterface _comptroller, IStdReference _priceOracle, address wallet) ERC20("Djinn FTM Short Farm", "dFTMShort") { creator = msg.sender; VAULT = _djBottle; spookyRouter = _spookyRouter; comptroller = _comptroller; priceOracle = _priceOracle; treasuryWallet = wallet; } //designed for single user ie. user opens via vault contract function open(address user, uint amount) external { require(msg.sender == address(VAULT), "!vault"); split(user, amount); } //automate the harvest function harvest() external { require(msg.sender == address(VAULT), "!vault"); IMasterChef(tShareRewardPool).deposit(0, 0); //0 is poolId and we call a deposit of 0 to allocate the shares to this contract compoundLPTokens(); } //automate the closing of the position //designed for single use ie. user closes via vault contract //so we need to vault contract to determine how many tokens belong to the user from this contract function close(address user, uint amountShares) external { require(msg.sender == address(VAULT), "!vault"); withdrawLP(user, amountShares); } ////////////////// BEGIN DEPOSIT LOGIC ////////////////// function split(address user, uint amount) internal { uint swapAmount = (amount * 70) / 100; swap(USDC, WETH, swapAmount); uint usdcAmount = getTokenBalance(USDC); uint wethAmount = getTokenBalance(WETH); //next step borrow(user, usdcAmount, wethAmount); } //we are borrowing the same amount of deposited ETH to achieve a vault that does not get liquidated function borrow(address user, uint amountUSDC, uint amountWETH) internal { //first check for any leftovers in the contract uint cTokenETHBefore = getCrTokenBalance(crETH); uint cTokenUSDCBefore = getCrTokenBalance(crUSDC); //supply USDC && WETH IERC20(USDC).approve(crUSDC, amountUSDC); CERC20(crUSDC).mint(amountUSDC); IERC20(WETH).approve(crETH, amountWETH); CERC20(crETH).mint(amountWETH); uint cTokenETHAfter = getCrTokenBalance(crETH); uint cTokenUSDCAfter = getCrTokenBalance(crUSDC); uint cTokenUSDCAmount = cTokenUSDCAfter - cTokenUSDCBefore; uint cTokenETHAmount = cTokenETHAfter - cTokenETHBefore; //store cTokens user amounts separate due to different interest rates VAULT.storeCrTokens(user, cTokenUSDCAmount, cTokenETHAmount); mintedUSDC[user] += cTokenUSDCAmount; mintedETH[user] += cTokenETHAmount; //we enter the markets to use usdc && wftm as collateral address[] memory cTokenSupplied = new address[](2); cTokenSupplied[0] = crUSDC; //cToken address cTokenSupplied[1] = crETH; comptroller.enterMarkets(cTokenSupplied); uint borrowBalanceBefore = borrowBalance(); //get max borrow && borrow ( ,uint borrowAmount, ) = getBorrowAmount(); CERC20(crETH).borrow(borrowAmount); uint borrowBalanceAfter = borrowBalance(); tokenBorrowBalance[user] += (borrowBalanceAfter - borrowBalanceBefore); //next step swapForTokens(); } function swapForTokens() internal { uint half = (getTokenBalance(WETH) * 50) / 100; IERC20(WETH).approve(spookyAddress, getTokenBalance(WETH)); //execute the swap here swap(WETH, WFTM, half); uint rest = getTokenBalance(WETH); swap(WETH, TOMB, rest); //next step getLPTokens(); } function getLPTokens() internal { //we need to approve the router to spend our TOMB uint wftmAmount = getTokenBalance(WFTM); uint tombAmount = getTokenBalance(TOMB); //now we add liquidity //@params token, tokenAmount, minToken, minETH, to, deadline IERC20(TOMB).approve(spookyAddress, tombAmount); IERC20(WFTM).approve(spookyAddress, wftmAmount); uint lpTokenBalanceBefore = getTokenBalance(spookyFtmTombLP); spookyRouter.addLiquidity(TOMB, WFTM, tombAmount, wftmAmount, 1, 1, address(this), block.timestamp + 30); uint lpTokenBalanceAfter = getTokenBalance(spookyFtmTombLP); uint lpTokenToMint = lpTokenBalanceAfter - lpTokenBalanceBefore; //keep track of LP token amount in this contract using a 1:1 mint _mint(address(this), lpTokenToMint); depositLPGetTShare(lpTokenToMint); } function depositLPGetTShare(uint lpTokenAmount) internal { //after this deposit the contract should be earning tshares as a reward IERC20(spookyFtmTombLP).approve(tShareRewardPool, lpTokenAmount); IMasterChef(tShareRewardPool).deposit(0, lpTokenAmount); //FTM-TOMB pool ID is 0 on Tomb.finance } ////////////////// DEPOSIT LOGIC ENDS ////////////////// ////////////////// BEGIN WITHDRAW LOGIC ////////////////// //the shares are based on the dUSDC in the users wallet function withdrawLP(address user, uint amountShares) internal { uint strategyBalance = getTokenBalance(address(this)); //18 decimals uint totalShares = IERC20(address(VAULT)).totalSupply(); //8 decimals uint withdrawAmount = (strategyBalance / totalShares) * amountShares; //handle rounding error case on full vault withdraw if (withdrawAmount > strategyBalance) { withdrawAmount = strategyBalance; } //we first withdraw the LP tokens from TOMB ///we have to check the balances before and after the withdraw in case there are leftovers uint amountBefore = getTokenBalance(spookyFtmTombLP); IMasterChef(tShareRewardPool).withdraw(0, withdrawAmount); uint amountAfter = getTokenBalance(spookyFtmTombLP); uint lpTokenAmount = amountAfter - amountBefore; removeLiq(user, lpTokenAmount, amountShares); } function removeLiq(address user, uint lpTokenAmount, uint amountShares) internal { //we remove liquidity belonging to the user(amount) back for tomb + wftm uint wftmBefore = getTokenBalance(WFTM); uint tombBefore = getTokenBalance(TOMB); IERC20(spookyFtmTombLP).approve(spookyAddress, lpTokenAmount); spookyRouter.removeLiquidity( WFTM, TOMB, lpTokenAmount, 1, 1, address(this), block.timestamp + 30 ); _burn(address(this), lpTokenAmount); uint wftmAfter = getTokenBalance(WFTM); uint tombAfter = getTokenBalance(TOMB); uint wftmToSwap = wftmAfter - wftmBefore; uint tombToSwap = tombAfter - tombBefore; IERC20(WFTM).approve(spookyAddress, wftmToSwap); IERC20(TOMB).approve(spookyAddress, tombToSwap); uint ethBefore = getTokenBalance(WETH); //execute the swaps swap(WFTM, WETH, wftmToSwap); swap(TOMB, WETH, tombToSwap); uint ethAfter = getTokenBalance(WETH); uint ethAfterSwap = ethAfter - ethBefore; //next step repay(user, amountShares, ethAfterSwap); } function repay(address user, uint amountShares, uint ethAfterSwap) internal { //crToken shares (uint ethShares, uint usdcShares) = splitShares(amountShares); uint ethRedeem; uint usdcRedeem; //main logic uint profits; uint amountToRepay; if (ethAfterSwap > tokenBorrowBalance[user]) { profits = ethAfterSwap - tokenBorrowBalance[user]; amountToRepay = tokenBorrowBalance[user]; tokenBorrowBalance[user] = 0; //min fee ethRedeem = ethShares - (chargeFees(ethShares)); usdcRedeem = usdcShares - (chargeFees(usdcShares)); payCreator(chargeFees(ethShares), chargeFees(usdcShares)); } else { profits = 0; amountToRepay = ethAfterSwap; tokenBorrowBalance[user] -= ethAfterSwap; //max fee on insta withdraw to prevent rounding error profits //2% fee instead of 1% ethRedeem = ethShares - (chargeFees(ethShares) * 2); usdcRedeem = usdcShares - (chargeFees(usdcShares) * 2); payCreator(chargeFees(ethShares) * 2, chargeFees(usdcShares) * 2); } if (ethRedeem > mintedETH[user]) { ethRedeem = mintedETH[user]; } if (usdcRedeem > mintedUSDC[user]) { usdcRedeem = mintedUSDC[user]; } ass = ethRedeem; balls = usdcRedeem; cocks = CERC20(crETH).balanceOf(address(this)); tits = CERC20(crUSDC).balanceOf(address(this)); //account for rounding errors if last person in vault wants to withdraw if (amountToRepay > borrowBalance()) { amountToRepay = borrowBalance(); } //now we can repay our users borrow IERC20(WETH).approve(crETH, amountToRepay); CERC20(crETH).repayBorrow(amountToRepay); uint ethBefore = getTokenBalance(WETH); uint usdcBefore = getTokenBalance(USDC); //redeem initial deposit amount + interest CERC20(crETH).redeem(ethRedeem); CERC20(crUSDC).redeem(usdcRedeem); //one final check for dust if (profits > getTokenBalance(WETH)) { profits = getTokenBalance(WETH); } //recheck uint ethAfter = getTokenBalance(WETH); uint usdcAfter = getTokenBalance(USDC); uint ethAmount = (ethAfter - ethBefore) + profits; uint usdcAmount = usdcAfter - usdcBefore; //final step swapProfits(ethAmount, usdcAmount); } //swap eth for usdc and send back to vault function swapProfits(uint ethAmount, uint usdcAmount) internal { uint usdcBefore = getTokenBalance(USDC); swap(WETH, USDC, ethAmount); uint usdcAfter = getTokenBalance(USDC); uint totalToSend = (usdcAfter - usdcBefore) + usdcAmount; IERC20(USDC).transfer(address(VAULT), totalToSend); } ////////////////// END WITHDRAW LOGIC ////////////////// ////////////////// BEGIN HARVEST LOGIC ////////////////// //sells tshares for tomb and wftm tokens function compoundLPTokens() internal { uint tsharesInitial = getTokenBalance(TSHARE); uint harvestFee = chargeFees(tsharesInitial); IERC20(TSHARE).transfer(treasuryWallet, harvestFee); //goes to treasury and will be swapped for FTM to use for gas fees uint tshares = getTokenBalance(TSHARE); //update amount uint half = (tshares * 50) / 100; IERC20(TSHARE).approve(spookyAddress, tshares); //true for 3 route swap swap(TSHARE, TOMB, half); //swap rest to WFTM //call again to avoid rounding errors uint rest = getTokenBalance(TSHARE); swap(TSHARE, WFTM, rest); //reinvest getLPTokens(); } ////////////////// END HARVEST LOGIC ////////////////// ////////////////// BEGIN HELPER LOGIC ////////////////// function swap(address tokenIn, address tokenOut, uint amount) internal { IERC20(tokenIn).approve(spookyAddress, amount); address[] memory path; if (tokenIn == WFTM || tokenOut == WFTM) { path = new address[](2); path[0] = tokenIn; path[1] = tokenOut; } else { path = new address[](3); path[0] = tokenIn; path[1] = WFTM; path[2] = tokenOut; } IUniswapV2Router02(spookyAddress).swapExactTokensForTokens( amount, 0, //min amount out path, address(this), block.timestamp + 30 ); } //returuns USD value of deposited assets, how much can be borrowed, and the price of the borrowed asset function getBorrowAmount() internal returns(uint liquidity, uint borrowAmount, uint price) { (, liquidity,) = comptroller.getAccountLiquidity(address(this)); IStdReference.ReferenceData memory data = priceOracle.getReferenceData("ETH", "USDC"); price = data.rate; uint maxTokenBorrow = (liquidity * 1e18) / price; //ETH has 18 decimals borrowAmount = (maxTokenBorrow * 94) / 100; //this is token amount //rebalance check to keep vault delta neutral uint borrowCheck = borrowAmount + borrowBalance(); (uint underlying, ) = getUnderlying(); //might have to add current deposit to this? uint diff; if (borrowCheck < underlying) { diff = underlying - borrowCheck; borrowAmount += diff; } else if (borrowCheck > underlying) { diff = borrowCheck - underlying; borrowAmount -= diff; } return (liquidity, borrowAmount, price); } //returns the share per underlying crToken price function splitShares (uint amountShares) internal view returns(uint, uint) { uint cTokenEth = getCrTokenBalance(crETH) * 1e18; uint cTokenUsdc = getCrTokenBalance(crUSDC) * 1e18; uint pool = VAULT.totalSupply() * 1e18; uint ethShares = ((pool * 1e6) / cTokenEth) * amountShares; uint usdcShares = (pool / cTokenUsdc) * amountShares; return (ethShares / 1e6, usdcShares); } function payCreator(uint amountEth, uint amountUSDC) internal { CERC20(crETH).transfer(creator, amountEth); CERC20(crUSDC).transfer(creator, amountUSDC); } function chargeFees(uint amount) internal pure returns(uint feeAmount) { return feeAmount = (amount * CREATOR_FEE) / 1e4; //0.1 or 1% } function getTokenBalance(address token) internal view returns(uint amount) { return amount = IERC20(token).balanceOf(address(this)); } function getCrTokenBalance(address crToken) internal view returns(uint amount) { return amount = CERC20(crToken).balanceOf(address(this)); } function setTreasury(address wallet) external { require(msg.sender == address(VAULT), "!vault"); treasuryWallet = wallet; } //public for querying from frontend function getUnderlying() public returns(uint, uint) { uint underlyingETH = CERC20(crETH).balanceOfUnderlying(address(this)); uint underlyingUSDC = CERC20(crUSDC).balanceOfUnderlying(address(this)); return (underlyingETH, underlyingUSDC); } function borrowBalance() public returns(uint) { return CERC20(crETH).borrowBalanceCurrent(address(this)); } }
execute the swap herenext step
function swapForTokens() internal { uint half = (getTokenBalance(WETH) * 50) / 100; IERC20(WETH).approve(spookyAddress, getTokenBalance(WETH)); swap(WETH, WFTM, half); uint rest = getTokenBalance(WETH); swap(WETH, TOMB, rest); getLPTokens(); }
12,639,489
// Dependency file: as/interfaces/ISetToken.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ // pragma solidity 0.6.10; // pragma experimental "ABIEncoderV2"; // import { IERC20 } from "@openzeppelin/as/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); } // Dependency file: as/interfaces/ISetValuer.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ // pragma solidity 0.6.10; // import { ISetToken } from "../interfaces/ISetToken.sol"; interface ISetValuer { function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256); } // Dependency file: as/interfaces/IIntegrationRegistry.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ // pragma solidity 0.6.10; interface IIntegrationRegistry { function addIntegration(address _module, string memory _id, address _wrapper) external; function getIntegrationAdapter(address _module, string memory _id) external view returns(address); function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address); function isValidIntegration(address _module, string memory _id) external view returns(bool); } // Dependency file: @openzeppelin/as/math/SignedSafeMath.sol // SPDX-License-Identifier: MIT // pragma solidity ^0.6.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // Dependency file: @openzeppelin/as/utils/Address.sol // SPDX-License-Identifier: MIT // pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [// importANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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 as 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); } } } } // Dependency file: @openzeppelin/as/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT // pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * // importANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Dependency file: @openzeppelin/as/GSN/Context.sol // SPDX-License-Identifier: MIT // pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like as. */ 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: as/protocol/lib/ResourceIdentifier.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ // pragma solidity 0.6.10; // import { IController } from "../../interfaces/IController.sol"; // import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol"; // import { IPriceOracle } from "../../interfaces/IPriceOracle.sol"; // import { ISetValuer } from "../../interfaces/ISetValuer.sol"; /** * @title ResourceIdentifier * @author Set Protocol * * A collection of utility functions to fetch information related to Resource as in the system */ library ResourceIdentifier { // IntegrationRegistry will always be resource ID 0 in the system uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0; // PriceOracle will always be resource ID 1 in the system uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1; // SetValuer resource will always be resource ID 2 in the system uint256 constant internal SET_VALUER_RESOURCE_ID = 2; /* ============ Internal ============ */ /** * Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on * the Controller */ function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) { return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID)); } /** * Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller */ function getPriceOracle(IController _controller) internal view returns (IPriceOracle) { return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID)); } /** * Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller */ function getSetValuer(IController _controller) internal view returns (ISetValuer) { return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID)); } } // Dependency file: as/lib/PreciseUnitMath.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ // pragma solidity 0.6.10; // pragma experimental ABIEncoderV2; // import { SafeMath } from "@openzeppelin/as/math/SafeMath.sol"; // import { SignedSafeMath } from "@openzeppelin/as/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 constant internal PRECISE_UNIT = 10 ** 18; int256 constant internal PRECISE_UNIT_INT = 10 ** 18; // Max unsigned integer value uint256 constant internal MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 constant internal MAX_INT_256 = type(int256).max; int256 constant internal MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } } // Dependency file: external/as/uniswap/lib/UniswapV2Library.sol // pragma solidity 0.6.10; // import "../../../../as/interfaces/external/IUniswapV2Pair.sol"; // import { SafeMath } from "@openzeppelin/as/math/SafeMath.sol"; library UniswapV2Library { 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, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } } // Dependency file: as/interfaces/external/IUniswapV2Pair.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ // pragma solidity 0.6.10; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // Dependency file: as/interfaces/IPriceOracle.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ // pragma solidity 0.6.10; /** * @title IPriceOracle * @author Set Protocol * * Interface for interacting with PriceOracle */ interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function masterQuoteAsset() external view returns (address); } // Dependency file: as/interfaces/IController.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ // pragma solidity 0.6.10; interface IController { function addSet(address _setToken) external; function feeRecipient() external view returns(address); function getModuleFee(address _module, uint256 _feeType) external view returns(uint256); function isModule(address _module) external view returns(bool); function isSet(address _setToken) external view returns(bool); function isSystemContract(address _contractAddress) external view returns (bool); function resourceId(uint256 _id) external view returns(address); } // Dependency file: as/lib/AddressArrayUtils.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ // pragma solidity 0.6.10; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address 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; } } /** * 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]); } } // Dependency file: @openzeppelin/as/math/SafeMath.sol // SPDX-License-Identifier: MIT // pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Dependency file: @openzeppelin/as/access/Ownable.sol // SPDX-License-Identifier: MIT // pragma solidity ^0.6.0; // import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Dependency file: @openzeppelin/as/token/ERC20/ERC20.sol // SPDX-License-Identifier: MIT // pragma solidity ^0.6.0; // import "../../GSN/Context.sol"; // import "./IERC20.sol"; // import "../../math/SafeMath.sol"; // import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token as 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-as.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; // import { ERC20 } from "@openzeppelin/as/token/ERC20/ERC20.sol"; // import { Ownable } from "@openzeppelin/as/access/Ownable.sol"; // import { SafeMath } from "@openzeppelin/as/math/SafeMath.sol"; // import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol"; // import { IController } from "../../interfaces/IController.sol"; // import { IPriceOracle } from "../../interfaces/IPriceOracle.sol"; // import { IUniswapV2Pair } from "../../interfaces/external/IUniswapV2Pair.sol"; // import { UniswapV2Library } from "../../../external/as/uniswap/lib/UniswapV2Library.sol"; // import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; // import { ResourceIdentifier } from "../lib/ResourceIdentifier.sol"; contract UniswapPairPriceAdapter is Ownable { using AddressArrayUtils for address[]; using SafeMath for uint256; using PreciseUnitMath for uint256; using ResourceIdentifier for IController; /* ============ Structs ============ */ /** * Struct containing information for get price function */ struct PoolSettings { address tokenOne; // Address of first token in reserve address tokenTwo; // Address of second token in reserve uint256 tokenOneBaseUnit; // Token one base unit. E.g. ETH is 10e18, USDC is 10e6 uint256 tokenTwoBaseUnit; // Token two base unit. bool isValid; // Boolean that returns if Uniswap pool is allowed } /* ============ State Variables ============ */ // Instance of the Controller contract IController public controller; // Uniswap allowed pools to settings mapping mapping(address => PoolSettings) public uniswapPoolsToSettings; // Uniswap allowed pools address[] public allowedUniswapPools; // Address of Uniswap factory address public uniswapFactory; /* ============ Constructor ============ */ /** * Set state variables * * @param _controller Instance of controller contract * @param _uniswapFactory Address of Uniswap factory * @param _uniswapPools Array of allowed Uniswap pools */ constructor( IController _controller, address _uniswapFactory, IUniswapV2Pair[] memory _uniswapPools ) public { controller = _controller; uniswapFactory = _uniswapFactory; // Add each of initial addresses to state for (uint256 i = 0; i < _uniswapPools.length; i++) { IUniswapV2Pair uniswapPoolToAdd = _uniswapPools[i]; // Require pools are unique require( !uniswapPoolsToSettings[address(uniswapPoolToAdd)].isValid, "Uniswap pool address must be unique." ); // Initialize pool settings PoolSettings memory poolSettings; poolSettings.tokenOne = uniswapPoolToAdd.token0(); poolSettings.tokenTwo = uniswapPoolToAdd.token1(); uint256 tokenOneDecimals = ERC20(poolSettings.tokenOne).decimals(); poolSettings.tokenOneBaseUnit = 10 ** tokenOneDecimals; uint256 tokenTwoDecimals = ERC20(poolSettings.tokenTwo).decimals(); poolSettings.tokenTwoBaseUnit = 10 ** tokenTwoDecimals; poolSettings.isValid = true; // Add to storage allowedUniswapPools.push(address(uniswapPoolToAdd)); uniswapPoolsToSettings[address(uniswapPoolToAdd)] = poolSettings; } } /* ============ External Functions ============ */ /** * Calculate price from Uniswap. Note: must be system contract to be able to retrieve price. If both assets are * not Uniswap pool, return false. * * @param _assetOne Address of first asset in pair * @param _assetTwo Address of second asset in pair */ function getPrice(address _assetOne, address _assetTwo) external view returns (bool, uint256) { require(controller.isSystemContract(msg.sender), "Must be system contract"); bool isAllowedUniswapPoolOne = uniswapPoolsToSettings[_assetOne].isValid; bool isAllowedUniswapPoolTwo = uniswapPoolsToSettings[_assetTwo].isValid; // If assetOne and assetTwo are both not Uniswap pools, then return false if (!isAllowedUniswapPoolOne && !isAllowedUniswapPoolTwo) { return (false, 0); } IPriceOracle priceOracle = controller.getPriceOracle(); address masterQuoteAsset = priceOracle.masterQuoteAsset(); uint256 assetOnePriceToMaster; if(isAllowedUniswapPoolOne) { assetOnePriceToMaster = _getUniswapPrice(priceOracle, _assetOne, masterQuoteAsset); } else { assetOnePriceToMaster = priceOracle.getPrice(_assetOne, masterQuoteAsset); } uint256 assetTwoPriceToMaster; if(isAllowedUniswapPoolTwo) { assetTwoPriceToMaster = _getUniswapPrice(priceOracle, _assetTwo, masterQuoteAsset); } else { assetTwoPriceToMaster = priceOracle.getPrice(_assetTwo, masterQuoteAsset); } return (true, assetOnePriceToMaster.preciseDiv(assetTwoPriceToMaster)); } function addPool(address _poolAddress) external onlyOwner { require ( !uniswapPoolsToSettings[_poolAddress].isValid, "Uniswap pool address already added" ); IUniswapV2Pair poolToken = IUniswapV2Pair(_poolAddress); uniswapPoolsToSettings[_poolAddress].tokenOne = poolToken.token0(); uniswapPoolsToSettings[_poolAddress].tokenTwo = poolToken.token1(); uint256 tokenOneDecimals = ERC20(uniswapPoolsToSettings[_poolAddress].tokenOne).decimals(); uniswapPoolsToSettings[_poolAddress].tokenOneBaseUnit = 10 ** tokenOneDecimals; uint256 tokenTwoDecimals = ERC20(uniswapPoolsToSettings[_poolAddress].tokenTwo).decimals(); uniswapPoolsToSettings[_poolAddress].tokenTwoBaseUnit = 10 ** tokenTwoDecimals; uniswapPoolsToSettings[_poolAddress].isValid = true; allowedUniswapPools.push(_poolAddress); } function removePool(address _poolAddress) external onlyOwner { require ( uniswapPoolsToSettings[_poolAddress].isValid, "Uniswap pool address does not exist" ); allowedUniswapPools = allowedUniswapPools.remove(_poolAddress); delete uniswapPoolsToSettings[_poolAddress]; } function getAllowedUniswapPools() external view returns (address[] memory) { return allowedUniswapPools; } /* ============ Internal Functions ============ */ function _getUniswapPrice( IPriceOracle _priceOracle, address _poolAddress, address _masterQuoteAsset ) internal view returns (uint256) { PoolSettings memory poolInfo = uniswapPoolsToSettings[_poolAddress]; IUniswapV2Pair poolToken = IUniswapV2Pair(_poolAddress); // Get prices against master quote asset. Note: if prices do not exist, function will revert uint256 tokenOnePriceToMaster = _priceOracle.getPrice(poolInfo.tokenOne, _masterQuoteAsset); uint256 tokenTwoPriceToMaster = _priceOracle.getPrice(poolInfo.tokenTwo, _masterQuoteAsset); // Get reserve amounts ( uint256 tokenOneReserves, uint256 tokenTwoReserves ) = UniswapV2Library.getReserves(uniswapFactory, poolInfo.tokenOne, poolInfo.tokenTwo); uint256 normalizedTokenOneBaseUnit = tokenOneReserves.preciseDiv(poolInfo.tokenOneBaseUnit); uint256 normalizedTokenBaseTwoUnits = tokenTwoReserves.preciseDiv(poolInfo.tokenTwoBaseUnit); uint256 totalNotionalToMaster = normalizedTokenOneBaseUnit.preciseMul(tokenOnePriceToMaster).add(normalizedTokenBaseTwoUnits.preciseMul(tokenTwoPriceToMaster)); uint256 totalSupply = poolToken.totalSupply(); return totalNotionalToMaster.preciseDiv(totalSupply); } }
Dependency file: as/interfaces/IIntegrationRegistry.sol/ pragma solidity 0.6.10;
interface IIntegrationRegistry { function addIntegration(address _module, string memory _id, address _wrapper) external; function getIntegrationAdapter(address _module, string memory _id) external view returns(address); function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address); function isValidIntegration(address _module, string memory _id) external view returns(bool); }
1,794,542
./full_match/5/0x64A0ED7f89d9F6de790F7d77022017be9Dcb405A/sources/browser/veth2-5.sol
Approve `spender` to transfer up to `amount` from `src` This will overwrite the approval amount for `spender` spender The address of the account which may transfer tokens rawAmount The number of tokens that are approved (2^256-1 means infinite) return Whether or not the approval succeeded/
function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); amount = safe96(rawAmount, "vETH2::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; }
11,628,909
// Sources flattened with hardhat v2.4.1 https://hardhat.org // File contracts/interfaces/IERC721.sol pragma solidity 0.5.7; /// @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 { /// @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, uint 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, uint 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 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, uint _tokenId) external payable; /// @notice Set or reaffirm the approved address for an NFT /// @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. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint _tokenId) external payable; /// @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,uint,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, uint _tokenId, bytes calldata data) external payable; /// @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, uint _tokenId) external payable; /// @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 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 (uint); /// @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(uint _tokenId) external view returns (address); /// @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(uint _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); /// @notice A descriptive name for a collection of NFTs in this contract function name() external view returns (string memory _name); } // File contracts/interfaces/ILockCore.sol pragma solidity 0.5.7; /** * @title The Lock interface core methods for a Lock * @author HardlyDifficult (unlock-protocol.com) */ interface ILockCore { /** * @dev Purchase function, public version, with no referrer. * @param _recipient address of the recipient of the purchased key */ function purchaseFor( address _recipient ) external payable; /** * @dev Purchase function, public version, with referrer. * @param _recipient address of the recipient of the purchased key * @param _referrer address of the user making the referral */ function purchaseForFrom( address _recipient, address _referrer ) external payable; /** * @dev Destroys the user's key and sends a refund based on the amount of time remaining. */ function cancelAndRefund() external; /** * @dev Called by owner to withdraw all funds from the lock. */ function withdraw( ) external; /** * @dev Called by owner to partially withdraw funds from the lock. */ function partialWithdraw( uint _amount ) external; /** * A function which lets the owner of the lock expire a users' key. */ function expireKeyFor( address _owner ) external; /** * A function which lets the owner of the lock to change the price for future purchases. */ function updateKeyPrice( uint _keyPrice ) external; /** * @dev Used to disable lock before migrating keys and/or destroying contract. * @dev Reverts if called by anyone but the owner. * @dev Reverts if isAlive == false * @dev Should emit Disable event. */ function disableLock( ) external; /** * @dev Used to clean up old lock contracts from the blockchain by using selfdestruct. * @dev Reverts if called by anyone but the owner. * @dev Reverts if isAlive == true * @dev Should emit Destroy event. */ function destroyLock( ) external; /** * @dev Determines how much of a refund a key owner would receive if they issued * a cancelAndRefund now. * @param _owner The owner of the key check the refund value for. * 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 _owner ) external view returns (uint refund); /** * Checks if the user has a non-expired key. */ function getHasValidKey( address _owner ) external view returns (bool); /** * 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); /** * Public function which returns the total number of keys (both expired and valid) * * This function signature is from the ERC-721 enumerable extension. * https://eips.ethereum.org/EIPS/eip-721 * @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 */ function totalSupply() external view returns (uint); /** * @dev Returns the key's ExpirationTimestamp field for a given owner. * @param _owner address of the user for whom we search the key */ function keyExpirationTimestampFor( address _owner ) external view returns (uint timestamp); /** * @param _page the page of key owners requested when faceted by page size * @param _pageSize the number of Key Owners requested per page */ function getOwnersByPage( uint _page, uint _pageSize ) external view returns (address[] memory); } // File zos-lib/contracts/Initializable.sol@v2.2.2 pragma solidity >=0.4.24 <0.6.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool wasInitializing = initializing; initializing = true; initialized = true; _; initializing = wasInitializing; } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File openzeppelin-eth/contracts/ownership/Ownable.sol@v2.1.3 pragma solidity ^0.5.0; /** * @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 is Initializable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } // File openzeppelin-solidity/contracts/introspection/IERC165.sol@v2.1.3 pragma solidity ^0.5.0; /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ 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. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File openzeppelin-solidity/contracts/introspection/ERC165.sol@v2.1.3 pragma solidity ^0.5.0; /** * @title ERC165 * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract ERC165 is IERC165 { bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor () internal { _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } // File openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol@v2.1.3 pragma solidity ^0.5.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } // File openzeppelin-solidity/contracts/token/ERC721/ERC721Holder.sol@v2.1.3 pragma solidity ^0.5.0; contract ERC721Holder is IERC721Receiver { function onERC721Received(address, address, uint256, bytes memory) public returns (bytes4) { return this.onERC721Received.selector; } } // File contracts/mixins/MixinDisableAndDestroy.sol pragma solidity 0.5.7; /** * @title Mixin allowing the Lock owner to disable a Lock (preventing new purchases) * and then destroy it. * @author HardlyDifficult * @dev `Mixins` are a design pattern seen in the 0x contracts. It simply * separates logically groupings of code to ease readability. */ contract MixinDisableAndDestroy is IERC721, Ownable { // Used to disable payable functions when deprecating an old lock bool public isAlive; event Destroy( uint balance, address indexed owner ); event Disable(); constructor( ) internal { isAlive = true; } // Only allow usage when contract is Alive modifier onlyIfAlive() { require(isAlive, 'LOCK_DEPRECATED'); _; } /** * @dev Used to disable lock before migrating keys and/or destroying contract */ function disableLock() external onlyOwner onlyIfAlive { emit Disable(); isAlive = false; } /** * @dev Used to clean up old lock contracts from the blockchain * TODO: add a check to ensure all keys are INVALID! */ function destroyLock() external onlyOwner { require(isAlive == false, 'DISABLE_FIRST'); emit Destroy(address(this).balance, msg.sender); selfdestruct(msg.sender); // Note we don't clean up the `locks` data in Unlock.sol as it should not be necessary // and leaves some data behind ('Unlock.LockBalances') which may be helpful. } } // File contracts/interfaces/IUnlock.sol pragma solidity 0.5.7; /** * @title The Unlock Interface * @author Nick Furfaro (unlock-protocol.com) **/ interface IUnlock { // Events event NewLock( address indexed lockOwner, address indexed newLockAddress ); // Use initialize instead of a constructor to support proxies (for upgradeability via zos). function initialize(address _owner) 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. * Return type `ILockCore` is the most specific interface from which all lock types inherit. */ function createLock( uint _expirationDuration, address _tokenAddress, uint _keyPrice, uint _maxNumberOfKeys ) external returns (ILockCore lock); /** * 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); } // File openzeppelin-solidity/contracts/token/ERC20/IERC20.sol@v2.1.3 pragma solidity ^0.5.0; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/mixins/MixinFunds.sol pragma solidity 0.5.7; /** * @title An implementation of the money related functions. * @author HardlyDifficult (unlock-protocol.com) */ contract MixinFunds { /** * The token-type that this Lock is priced in. If 0, then use ETH, else this is * a ERC20 token address. */ address public tokenAddress; constructor( address _tokenAddress ) public { require( _tokenAddress == address(0) || IERC20(_tokenAddress).totalSupply() > 0, 'INVALID_TOKEN' ); tokenAddress = _tokenAddress; } /** * Ensures that the msg.sender has paid at least the price stated. * * With ETH, this means the function originally called was `payable` and the * transaction included at least the amount requested. * * Security: be wary of re-entrancy when calling this function. */ function _chargeAtLeast( uint _price ) internal { if(tokenAddress == address(0)) { require(msg.value >= _price, 'NOT_ENOUGH_FUNDS'); } else { IERC20 token = IERC20(tokenAddress); uint balanceBefore = token.balanceOf(address(this)); token.transferFrom(msg.sender, address(this), _price); // There are known bugs in popular ERC20 implements which means we cannot // trust the return value of `transferFrom`. This require statement ensures // that a transfer occurred. require(token.balanceOf(address(this)) > balanceBefore, 'TRANSFER_FAILED'); } } /** * Transfers funds from the contract to the account provided. * * Security: be wary of re-entrancy when calling this function. */ function _transfer( address _to, uint _amount ) internal { if(tokenAddress == address(0)) { address(uint160(_to)).transfer(_amount); } else { IERC20 token = IERC20(tokenAddress); uint balanceBefore = token.balanceOf(_to); token.transfer(_to, _amount); // There are known bugs in popular ERC20 implements which means we cannot // trust the return value of `transferFrom`. This require statement ensures // that a transfer occurred. require(token.balanceOf(_to) > balanceBefore, 'TRANSFER_FAILED'); } } /** * Gets the current balance of the account provided. */ function _getBalance( address _account ) internal view returns (uint) { if(tokenAddress == address(0)) { return _account.balance; } else { return IERC20(tokenAddress).balanceOf(_account); } } } // File contracts/mixins/MixinLockCore.sol pragma solidity 0.5.7; /** * @title Mixin for core lock data and functions. * @author HardlyDifficult * @dev `Mixins` are a design pattern seen in the 0x contracts. It simply * separates logically groupings of code to ease readability. */ contract MixinLockCore is Ownable, MixinFunds, MixinDisableAndDestroy { event PriceChanged( uint oldKeyPrice, uint keyPrice ); event Withdrawal( address indexed _sender, uint _amount ); // Unlock Protocol address // TODO: should we make that private/internal? IUnlock public unlockProtocol; // Duration in seconds for which the keys are valid, after creation // should we take a smaller type use less gas? // TODO: add support for a timestamp instead of duration uint public expirationDuration; // price in wei of the next key // TODO: allow support for a keyPriceCalculator which could set prices dynamically uint public keyPrice; // Max number of keys sold if the keyReleaseMechanism is public uint public maxNumberOfKeys; // A count of how many new key purchases there have been uint public numberOfKeysSold; // The version number for this lock contract, uint public publicLockVersion; // Ensure that the Lock has not sold all of its keys. modifier notSoldOut() { require(maxNumberOfKeys > numberOfKeysSold, 'LOCK_SOLD_OUT'); _; } constructor( uint _expirationDuration, uint _keyPrice, uint _maxNumberOfKeys, uint _version ) internal { require(_expirationDuration <= 100 * 365 * 24 * 60 * 60, 'MAX_EXPIRATION_100_YEARS'); unlockProtocol = IUnlock(msg.sender); // Make sure we link back to Unlock's smart contract. expirationDuration = _expirationDuration; keyPrice = _keyPrice; maxNumberOfKeys = _maxNumberOfKeys; publicLockVersion = _version; } /** * @dev Called by owner to withdraw all funds from the lock. * TODO: consider allowing anybody to trigger this as long as it goes to owner anyway? */ function withdraw() external onlyOwner { uint balance = _getBalance(address(this)); require(balance > 0, 'NOT_ENOUGH_FUNDS'); // Security: re-entrancy not a risk as this is the last line of an external function _withdraw(balance); } /** * @dev Called by owner to partially withdraw funds from the lock. * TODO: consider allowing anybody to trigger this as long as it goes to owner anyway? */ function partialWithdraw(uint _amount) external onlyOwner { require(_amount > 0, 'GREATER_THAN_ZERO'); uint balance = _getBalance(address(this)); require(balance >= _amount, 'NOT_ENOUGH_FUNDS'); // Security: re-entrancy not a risk as this is the last line of an external function _withdraw(_amount); } /** * A function which lets the owner of the lock to change the price for future purchases. */ function updateKeyPrice( uint _keyPrice ) external onlyOwner onlyIfAlive { uint oldKeyPrice = keyPrice; keyPrice = _keyPrice; emit PriceChanged(oldKeyPrice, keyPrice); } /** * Public function which returns the total number of unique keys sold (both * expired and valid) */ function totalSupply() public view returns (uint) { return numberOfKeysSold; } /** * @dev private version of the withdraw function which handles all withdrawals from the lock. * * Security: Be wary of re-entrancy when calling this. */ function _withdraw(uint _amount) private { _transfer(Ownable.owner(), _amount); emit Withdrawal(msg.sender, _amount); } } // File contracts/mixins/MixinKeys.sol pragma solidity 0.5.7; /** * @title Mixin for managing `Key` data. * @author HardlyDifficult * @dev `Mixins` are a design pattern seen in the 0x contracts. It simply * separates logically groupings of code to ease readability. */ contract MixinKeys is Ownable, MixinLockCore { // The struct for a key struct Key { uint tokenId; uint expirationTimestamp; } // Called when the Lock owner expires a user's Key event ExpireKey(uint tokenId); // Keys // Each owner can have at most exactly one key // TODO: could we use public here? (this could be confusing though because it getter will // return 0 values when missing a key) mapping (address => Key) private keyByOwner; // Each tokenId can have at most exactly one owner at a time. // Returns 0 if the token does not exist // TODO: once we decouple tokenId from owner address (incl in js), then we can consider // merging this with numberOfKeysSold into an array instead. mapping (uint => address) private ownerByTokenId; // Addresses of owners are also stored in an array. // Addresses are never removed by design to avoid abuses around referals address[] public owners; // Ensures that an owner has a key modifier hasKey( address _owner ) { Key storage key = keyByOwner[_owner]; require( key.expirationTimestamp > 0, 'NO_SUCH_KEY' ); _; } // Ensures that an owner has a valid key modifier hasValidKey( address _owner ) { require( getHasValidKey(_owner), 'KEY_NOT_VALID' ); _; } // Ensures that a key has an owner modifier isKey( uint _tokenId ) { require( ownerByTokenId[_tokenId] != address(0), 'NO_SUCH_KEY' ); _; } // Ensure that the caller owns the key modifier onlyKeyOwner( uint _tokenId ) { require( isKeyOwner(_tokenId, msg.sender), 'ONLY_KEY_OWNER' ); _; } /** * A function which lets the owner of the lock expire a users' key. */ function expireKeyFor( address _owner ) public onlyOwner hasValidKey(_owner) { Key storage key = keyByOwner[_owner]; key.expirationTimestamp = block.timestamp; // Effectively expiring the key emit ExpireKey(key.tokenId); } /** * In the specific case of a Lock, each owner can own only at most 1 key. * @return The number of NFTs owned by `_owner`, either 0 or 1. */ function balanceOf( address _owner ) external view returns (uint) { require(_owner != address(0), 'INVALID_ADDRESS'); return keyByOwner[_owner].expirationTimestamp > 0 ? 1 : 0; } /** * Checks if the user has a non-expired key. */ function getHasValidKey( address _owner ) public view returns (bool) { return keyByOwner[_owner].expirationTimestamp > block.timestamp; } /** * @notice Find the tokenId for a given user * @return The tokenId of the NFT, else revert */ function getTokenIdFor( address _account ) external view hasKey(_account) returns (uint) { return keyByOwner[_account].tokenId; } /** * 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 */ function getOwnersByPage(uint _page, uint _pageSize) public view returns (address[] memory) { require(owners.length > 0, 'NO_OUTSTANDING_KEYS'); uint pageSize = _pageSize; uint _startIndex = _page * pageSize; uint endOfPageIndex; if (_startIndex + pageSize > owners.length) { endOfPageIndex = owners.length; pageSize = owners.length - _startIndex; } else { endOfPageIndex = (_startIndex + pageSize); } // new temp in-memory array to hold pageSize number of requested owners: address[] memory ownersByPage = new address[](pageSize); uint pageIndex = 0; // Build the requested set of owners into a new temporary array: for (uint i = _startIndex; i < endOfPageIndex; i++) { ownersByPage[pageIndex] = owners[i]; pageIndex++; } return ownersByPage; } /** * Checks if the given address owns the given tokenId. */ function isKeyOwner( uint _tokenId, address _owner ) public view returns (bool) { return ownerByTokenId[_tokenId] == _owner; } /** * @dev Returns the key's ExpirationTimestamp field for a given owner. * @param _owner address of the user for whom we search the key */ function keyExpirationTimestampFor( address _owner ) public view hasKey(_owner) returns (uint timestamp) { return keyByOwner[_owner].expirationTimestamp; } /** * Public function which returns the total number of unique owners (both expired * and valid). This may be larger than totalSupply. */ function numberOfOwners() public view returns (uint) { return owners.length; } /** * @notice ERC721: Find the owner of an NFT * @return The address of the owner of the NFT, if applicable */ function ownerOf( uint _tokenId ) public view isKey(_tokenId) returns (address) { return ownerByTokenId[_tokenId]; } /** * Assigns the key a new tokenId (from numberOfKeysSold) if it does not already have * one assigned. */ function _assignNewTokenId( Key storage _key ) internal { if (_key.tokenId == 0) { // This is a brand new owner, else an owner of an expired key buying an extension. // We increment the tokenId counter numberOfKeysSold++; // we assign the incremented `numberOfKeysSold` as the tokenId for the new key _key.tokenId = numberOfKeysSold; } } /** * Records the owner of a given tokenId */ function _recordOwner( address _owner, uint _tokenId ) internal { if (ownerByTokenId[_tokenId] != _owner) { // TODO: this may include duplicate entries owners.push(_owner); // We register the owner of the tokenID ownerByTokenId[_tokenId] = _owner; } } /** * Returns the Key struct for the given owner. */ function _getKeyFor( address _owner ) internal view returns (Key storage) { return keyByOwner[_owner]; } } // File contracts/mixins/MixinApproval.sol pragma solidity 0.5.7; /** * @title Mixin for the Approval related functions needed to meet the ERC721 * standard. * @author HardlyDifficult * @dev `Mixins` are a design pattern seen in the 0x contracts. It simply * separates logically groupings of code to ease readability. */ contract MixinApproval is IERC721, MixinDisableAndDestroy, MixinKeys { // Keeping track of approved transfers // This is a mapping of addresses which have approved // the transfer of a key to another address where their key can be transfered // Note: the approver may actually NOT have a key... and there can only // be a single approved beneficiary // Note 2: for transfer, both addresses will be different // Note 3: for sales (new keys on restricted locks), both addresses will be the same mapping (uint => address) private approved; // Keeping track of approved operators for a Key owner. // Since an owner can have up to 1 Key, this is similiar to above // but the approval does not reset when a transfer occurs. mapping (address => mapping (address => bool)) private ownerToOperatorApproved; // Ensure that the caller has a key // or that the caller has been approved // for ownership of that key modifier onlyKeyOwnerOrApproved( uint _tokenId ) { require( isKeyOwner(_tokenId, msg.sender) || _isApproved(_tokenId, msg.sender) || isApprovedForAll(ownerOf(_tokenId), msg.sender), 'ONLY_KEY_OWNER_OR_APPROVED'); _; } /** * This approves _approved to get ownership of _tokenId. * Note: that since this is used for both purchase and transfer approvals * the approved token may not exist. */ function approve( address _approved, uint _tokenId ) external payable onlyIfAlive onlyKeyOwnerOrApproved(_tokenId) { require(msg.sender != _approved, 'APPROVE_SELF'); approved[_tokenId] = _approved; emit Approval(ownerOf(_tokenId), _approved, _tokenId); } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll( address _to, bool _approved ) external onlyIfAlive { require(_to != msg.sender, 'APPROVE_SELF'); ownerToOperatorApproved[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * external version * Will return the approved recipient for a key, if any. */ function getApproved( uint _tokenId ) external view returns (address) { return _getApproved(_tokenId); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return ownerToOperatorApproved[_owner][_operator]; } /** * @dev Checks if the given user is approved to transfer the tokenId. */ function _isApproved( uint _tokenId, address _user ) internal view returns (bool) { return approved[_tokenId] == _user; } /** * Will return the approved recipient for a key transfer or ownership. * Note: this does not check that a corresponding key * actually exists. */ function _getApproved( uint _tokenId ) internal view returns (address) { address approvedRecipient = approved[_tokenId]; require(approvedRecipient != address(0), 'NONE_APPROVED'); return approvedRecipient; } /** * @dev Function to clear current approval of a given token ID * @param _tokenId uint256 ID of the token to be transferred */ function _clearApproval( uint256 _tokenId ) internal { if (approved[_tokenId] != address(0)) { approved[_tokenId] = address(0); } } } // File contracts/mixins/MixinGrantKeys.sol pragma solidity 0.5.7; /** * @title Mixin allowing the Lock owner to grant / gift keys to users. * @author HardlyDifficult * @dev `Mixins` are a design pattern seen in the 0x contracts. It simply * separates logically groupings of code to ease readability. */ contract MixinGrantKeys is IERC721, Ownable, MixinKeys { /** * Allows the Lock owner to give a user a key with no charge. */ function grantKey( address _recipient, uint _expirationTimestamp ) external onlyOwner { _grantKey(_recipient, _expirationTimestamp); } /** * Allows the Lock owner to give a collection of users a key with no charge. * All keys granted have the same expiration date. */ function grantKeys( address[] calldata _recipients, uint _expirationTimestamp ) external onlyOwner { for(uint i = 0; i < _recipients.length; i++) { _grantKey(_recipients[i], _expirationTimestamp); } } /** * Allows the Lock owner to give a collection of users a key with no charge. * Each key may be assigned a different expiration date. */ function grantKeys( address[] calldata _recipients, uint[] calldata _expirationTimestamps ) external onlyOwner { for(uint i = 0; i < _recipients.length; i++) { _grantKey(_recipients[i], _expirationTimestamps[i]); } } /** * Give a key to the given user */ function _grantKey( address _recipient, uint _expirationTimestamp ) private { require(_recipient != address(0), 'INVALID_ADDRESS'); Key storage toKey = _getKeyFor(_recipient); require(_expirationTimestamp > toKey.expirationTimestamp, 'ALREADY_OWNS_KEY'); _assignNewTokenId(toKey); _recordOwner(_recipient, toKey.tokenId); toKey.expirationTimestamp = _expirationTimestamp; // trigger event emit Transfer( address(0), // This is a creation. _recipient, toKey.tokenId ); } } // File contracts/mixins/MixinLockMetadata.sol pragma solidity 0.5.7; /** * @title Mixin for metadata about the Lock. * @author HardlyDifficult * @dev `Mixins` are a design pattern seen in the 0x contracts. It simply * separates logically groupings of code to ease readability. */ contract MixinLockMetadata is IERC721, Ownable { /// A descriptive name for a collection of NFTs in this contract string private lockName; /** * Allows the Lock owner to assign a descriptive name for this Lock. */ function updateLockName( string calldata _lockName ) external onlyOwner { lockName = _lockName; } /** * @dev Gets the token name * @return string representing the token name */ function name( ) external view returns (string memory) { return lockName; } } // File contracts/mixins/MixinNoFallback.sol pragma solidity 0.5.7; /** * @title Mixin for the fallback function implementation, which simply reverts. * @author HardlyDifficult * @dev `Mixins` are a design pattern seen in the 0x contracts. It simply * separates logically groupings of code to ease readability. */ contract MixinNoFallback { /** * @dev the fallback function should not be used. This explicitly reverts * to ensure it's never used. */ function() external { revert('NO_FALLBACK'); } } // File openzeppelin-solidity/contracts/math/SafeMath.sol@v2.1.3 pragma solidity ^0.5.0; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File contracts/mixins/MixinPurchase.sol pragma solidity 0.5.7; /** * @title Mixin for the purchase-related functions. * @author HardlyDifficult * @dev `Mixins` are a design pattern seen in the 0x contracts. It simply * separates logically groupings of code to ease readability. */ contract MixinPurchase is MixinFunds, MixinDisableAndDestroy, MixinLockCore, MixinKeys { using SafeMath for uint; /** * @dev Purchase function, public version, with no referrer. * @param _recipient address of the recipient of the purchased key */ function purchaseFor( address _recipient ) external payable onlyIfAlive { return _purchaseFor(_recipient, address(0)); } /** * @dev Purchase function, public version, with referrer. * @param _recipient address of the recipient of the purchased key * @param _referrer address of the user making the referral */ function purchaseForFrom( address _recipient, address _referrer ) external payable onlyIfAlive hasValidKey(_referrer) { return _purchaseFor(_recipient, _referrer); } /** * @dev Purchase function: this lets a user purchase a key from the lock for another user * @param _recipient address of the recipient of the purchased key * This will fail if * - the keyReleaseMechanism is private * - the keyReleaseMechanism is Approved and the recipient has not been previously approved * - the amount value is smaller than the price * - the recipient already owns a key * TODO: next version of solidity will allow for message to be added to require. */ function _purchaseFor( address _recipient, address _referrer ) private notSoldOut() { // solhint-disable-line function-max-lines require(_recipient != address(0), 'INVALID_ADDRESS'); // Let's get the actual price for the key from the Unlock smart contract uint discount; uint tokens; uint inMemoryKeyPrice = keyPrice; (discount, tokens) = unlockProtocol.computeAvailableDiscountFor(_recipient, inMemoryKeyPrice); uint netPrice = inMemoryKeyPrice; if (discount > inMemoryKeyPrice) { netPrice = 0; } else { // SafeSub not required as the if statement already confirmed `inMemoryKeyPrice - discount` cannot underflow netPrice = inMemoryKeyPrice - discount; } // We explicitly allow for greater amounts of ETH to allow 'donations' _chargeAtLeast(netPrice); // Assign the key Key storage toKey = _getKeyFor(_recipient); uint previousExpiration = toKey.expirationTimestamp; if (previousExpiration < block.timestamp) { _assignNewTokenId(toKey); _recordOwner(_recipient, toKey.tokenId); // SafeAdd is not required here since expirationDuration is capped to a tiny value // (relative to the size of a uint) toKey.expirationTimestamp = block.timestamp + expirationDuration; } else { // This is an existing owner trying to extend their key toKey.expirationTimestamp = previousExpiration.add(expirationDuration); } if (discount > 0) { unlockProtocol.recordConsumedDiscount(discount, tokens); } unlockProtocol.recordKeyPurchase(netPrice, _referrer); // trigger event emit Transfer( address(0), // This is a creation. _recipient, numberOfKeysSold ); } } // File contracts/mixins/MixinRefunds.sol pragma solidity 0.5.7; contract MixinRefunds is Ownable, MixinFunds, MixinLockCore, MixinKeys { using SafeMath for uint; // CancelAndRefund will return funds based on time remaining minus this penalty. // This is calculated as `proRatedRefund * refundPenaltyNumerator / refundPenaltyDenominator`. uint public refundPenaltyNumerator = 1; uint public refundPenaltyDenominator = 10; event CancelKey( uint indexed tokenId, address indexed owner, uint refund ); event RefundPenaltyChanged( uint oldRefundPenaltyNumerator, uint oldRefundPenaltyDenominator, uint refundPenaltyNumerator, uint refundPenaltyDenominator ); /** * @dev Destroys the user's key and sends a refund based on the amount of time remaining. */ function cancelAndRefund() external { Key storage key = _getKeyFor(msg.sender); uint refund = _getCancelAndRefundValue(msg.sender); emit CancelKey(key.tokenId, msg.sender, refund); // expirationTimestamp is a proxy for hasKey, setting this to `block.timestamp` instead // of 0 so that we can still differentiate hasKey from hasValidKey. key.expirationTimestamp = block.timestamp; if (refund > 0) { // Security: doing this last to avoid re-entrancy concerns _transfer(msg.sender, refund); } } /** * Allow the owner to change the refund penalty. */ function updateRefundPenalty( uint _refundPenaltyNumerator, uint _refundPenaltyDenominator ) external onlyOwner { require(_refundPenaltyDenominator != 0, 'INVALID_RATE'); emit RefundPenaltyChanged( refundPenaltyNumerator, refundPenaltyDenominator, _refundPenaltyNumerator, _refundPenaltyDenominator ); refundPenaltyNumerator = _refundPenaltyNumerator; refundPenaltyDenominator = _refundPenaltyDenominator; } /** * @dev Determines how much of a refund a key owner would receive if they issued * 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 _owner ) external view returns (uint refund) { return _getCancelAndRefundValue(_owner); } /** * @dev Determines how much of a refund a key owner would receive if they issued * a cancelAndRefund now. * @param _owner The owner of the key check the refund value for. */ function _getCancelAndRefundValue( address _owner ) private view hasValidKey(_owner) returns (uint refund) { Key storage key = _getKeyFor(_owner); // Math: safeSub is not required since `hasValidKey` confirms timeRemaining is positive uint timeRemaining = key.expirationTimestamp - block.timestamp; if(timeRemaining >= expirationDuration) { refund = keyPrice; } else { // Math: using safeMul in case keyPrice or timeRemaining is very large refund = keyPrice.mul(timeRemaining) / expirationDuration; } uint penalty = keyPrice.mul(refundPenaltyNumerator) / refundPenaltyDenominator; if (refund > penalty) { // Math: safeSub is not required since the if confirms this won't underflow refund -= penalty; } else { refund = 0; } } } // File openzeppelin-solidity/contracts/utils/Address.sol@v2.1.3 pragma solidity ^0.5.0; /** * Utility library of inline functions on addresses */ library Address { /** * 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 account address of the account to check * @return whether the target address is a contract */ function isContract(address account) 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. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File contracts/mixins/MixinTransfer.sol pragma solidity 0.5.7; /** * @title Mixin for the transfer-related functions needed to meet the ERC721 * standard. * @author Nick Furfaro * @dev `Mixins` are a design pattern seen in the 0x contracts. It simply * separates logically groupings of code to ease readability. */ contract MixinTransfer is MixinLockCore, MixinKeys, MixinApproval { using SafeMath for uint; using Address for address; event TransferFeeChanged( uint oldTransferFeeNumerator, uint oldTransferFeeDenominator, uint transferFeeNumerator, uint transferFeeDenominator ); // 0x150b7a02 == bytes4(keccak256('onERC721Received(address,address,uint256,bytes)')) bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // The fee relative to keyPrice to charge when transfering a Key to another account // (potentially on a 0x marketplace). // This is calculated as `keyPrice * transferFeeNumerator / transferFeeDenominator`. // TODO: this value is currently ignored and no fee is charged yet! uint public transferFeeNumerator = 5; uint public transferFeeDenominator = 100; /** * This is payable because at some point we want to allow the LOCK to capture a fee on 2ndary * market transactions... */ function transferFrom( address _from, address _recipient, uint _tokenId ) public payable onlyIfAlive hasValidKey(_from) onlyKeyOwnerOrApproved(_tokenId) { require(_recipient != address(0), 'INVALID_ADDRESS'); Key storage fromKey = _getKeyFor(_from); Key storage toKey = _getKeyFor(_recipient); uint previousExpiration = toKey.expirationTimestamp; if (toKey.tokenId == 0) { toKey.tokenId = fromKey.tokenId; } _recordOwner(_recipient, toKey.tokenId); if (previousExpiration <= block.timestamp) { // The recipient did not have a key, or had a key but it expired. The new expiration is the // sender's key expiration toKey.expirationTimestamp = fromKey.expirationTimestamp; } else { // The recipient has a non expired key. We just add them the corresponding remaining time // SafeSub is not required since the if confirms `previousExpiration - block.timestamp` cannot underflow toKey.expirationTimestamp = fromKey .expirationTimestamp.add(previousExpiration - block.timestamp); } // Effectively expiring the key for the previous owner fromKey.expirationTimestamp = block.timestamp; // Clear any previous approvals _clearApproval(_tokenId); // trigger event emit Transfer( _from, _recipient, _tokenId ); } /** * @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, uint _tokenId ) external payable { safeTransferFrom(_from, _to, _tokenId, ''); } /** * @notice Transfers the ownership of an NFT from one address to another address. * When transfer is complete, this functions * 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)'))`. * @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, uint _tokenId, bytes memory _data ) public payable onlyIfAlive onlyKeyOwnerOrApproved(_tokenId) hasValidKey(ownerOf(_tokenId)) { transferFrom(_from, _to, _tokenId); require(_checkOnERC721Received(_from, _to, _tokenId, _data), 'NON_COMPLIANT_ERC721_RECEIVER'); } /** * Allow the Lock owner to change the transfer fee. */ function updateTransferFee( uint _transferFeeNumerator, uint _transferFeeDenominator ) external onlyOwner { require(_transferFeeDenominator != 0, 'INVALID_RATE'); emit TransferFeeChanged( transferFeeNumerator, transferFeeDenominator, _transferFeeNumerator, _transferFeeDenominator ); transferFeeNumerator = _transferFeeNumerator; transferFeeDenominator = _transferFeeDenominator; } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } } // File contracts/PublicLock.sol pragma solidity 0.5.7; /** * @title The Lock contract * @author Julien Genestoux (unlock-protocol.com) * Eventually: implement ERC721. * @dev ERC165 allows our contract to be queried to determine whether it implements a given interface. * Every ERC-721 compliant contract must implement the ERC165 interface. * https://eips.ethereum.org/EIPS/eip-721 */ contract PublicLock is MixinNoFallback, ERC721Holder, IERC721, ILockCore, ERC165, Ownable, MixinFunds, MixinDisableAndDestroy, MixinLockCore, MixinKeys, MixinGrantKeys, MixinApproval, MixinLockMetadata, MixinRefunds, MixinPurchase, MixinTransfer { constructor( address _owner, uint _expirationDuration, address _tokenAddress, uint _keyPrice, uint _maxNumberOfKeys ) public MixinFunds(_tokenAddress) MixinLockCore(_expirationDuration, _keyPrice, _maxNumberOfKeys, 1) { // registering the interface for erc721 with ERC165.sol using // the ID specified in the standard: https://eips.ethereum.org/EIPS/eip-721 _registerInterface(0x80ac58cd); // We must manually initialize Ownable.sol Ownable.initialize(_owner); } }
Called by owner to withdraw all funds from the lock. TODO: consider allowing anybody to trigger this as long as it goes to owner anyway?/ Security: re-entrancy not a risk as this is the last line of an external function
function withdraw() external onlyOwner { uint balance = _getBalance(address(this)); require(balance > 0, 'NOT_ENOUGH_FUNDS'); _withdraw(balance); }
949,471
./full_match/7700/0x6F16b6661F91e666946F8621896C4060Cd7fb196/sources/contracts/cedar/drop/CedarERC721Drop.sol
Expose the current active claim condition including claim limits
function getActiveClaimConditions() external view override returns ( ClaimCondition memory condition, uint256 conditionId, uint256 walletMaxClaimCount, uint256 maxTotalSupply, uint256 tokenSupply, bool isClaimPaused ) { (condition, conditionId, walletMaxClaimCount, maxTotalSupply) = claimData.getActiveClaimConditions(); isClaimPaused = claimIsPaused; tokenSupply = totalSupply(); }
4,655,233
./full_match/4/0x95774833307E2F54583644F52be0c238c62D5122/sources/GunPool.sol
得到 这个 BridgePair 的实时资产
function getTokenAmount() public view returns (address _token0, uint _amount0, address _token1, uint _amount1) { _token0 = Token0; _token1 = Token1; address UniPair = UniswapV2Library.pairFor(factory, Token0, Token1); _amount0 = IERC20(_token0).balanceOf(address(this)) + IERC20(_token0).balanceOf(UniPair) * IUniswapV2Pair(UniPair).balanceOf(address(this)) / IUniswapV2Pair(UniPair).totalSupply(); _amount1 = IERC20(_token1).balanceOf(address(this)) + IERC20(_token1).balanceOf(UniPair) * IUniswapV2Pair(UniPair).balanceOf(address(this)) / IUniswapV2Pair(UniPair).totalSupply(); }
764,391
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/ONEPOOL.sol // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.12; // File: @openzeppelin/contracts/token/ERC20/ERC20.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 ERC20Basic is Context, IERC20 , Ownable{ using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; // A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @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; } 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); _moveDelegates(_delegates[sender], _delegates[recipient], amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _moveDelegates(address(0), _delegates[account], amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } /** * @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 { } } // Token with Governance. contract ONEPOOL is ERC20Basic { //Initialize Token name, symbol, decimal and totalsupply constructor () public ERC20Basic ("oneToken", "op") { } /** * @dev Burns a specific amount of tokens. Can be executed by contract Operator only. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public onlyOwner { _burn(msg.sender,_value); } function mint(address _account, uint256 _value) public onlyOwner returns(bool) { _mint(_account, _value); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "delegateBySig: invalid nonce"); require(now <= expiry, "delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } } // File: contracts/RewardPool.sol // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity 0.6.12; interface IMaster{ function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function updatePool(uint256 _pid) external ; function poolInfo(uint256 _pid) external view returns(address, uint256, uint256 , uint256); function userInfo(uint256 _pid,address _user) external view returns(uint256, uint256); function getMultiplier(uint256 _from, uint256 _to) external view returns (uint256); function sushiPerBlock() external view returns(uint256); function pendingSushi(uint256 _pid, address _user) external view returns(uint256); function totalAllocPoint() external view returns(uint256); function emergencyWithdraw(uint256 _pid) external ; } /** * @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 FactoryOwnable 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 owner) internal { _owner = owner; 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(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/RewardPool.sol contract RewardPoolFactory is FactoryOwnable { 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. uint256 debt; //Yield reward } uint256 public poolId; uint256 public lpId; address public masterChef; address public token; uint256 public totalSupply; bool public vaultStatus; // Info of each user that stakes LP tokens. mapping(address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event SetVaultStatus(address sender, bool newStatus); RewardPool public rewardPool; ONEPOOL public onePool; constructor(RewardPool _rewardPool,ONEPOOL _onePool, uint256 _poolId,uint256 _lpId,address _masterChef, address _token, bool _status, address _owner) public FactoryOwnable(_owner) { rewardPool = _rewardPool; onePool = _onePool; poolId = _poolId; lpId = _lpId; masterChef = _masterChef; token = _token; vaultStatus = _status; } // Deposit LP tokens to MasterChef for onePool allocation. function deposit( uint256 _amount) public { rewardPool.updatePool(poolId); (IERC20 lpToken, , , uint256 acconePoolPerShare,) = rewardPool.poolInfo(poolId); UserInfo storage user = userInfo[msg.sender]; if (user.amount > 0) { uint256 pending = user.amount.mul(acconePoolPerShare).div(1e12).sub( user.rewardDebt ); if(pending > 0){ user.rewardDebt = user.amount.mul(acconePoolPerShare).div(1e12); safeonePoolTransfer(msg.sender, pending); } } if(_amount>0){ lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); } if(vaultStatus == true){ yieldDeposit(lpToken.balanceOf(address(this)), user, lpToken); } if(_amount > 0){ user.amount = user.amount.add(_amount); totalSupply = totalSupply.add(_amount); } user.rewardDebt = user.amount.mul(acconePoolPerShare).div(1e12); emit Deposit(msg.sender, poolId, _amount); } function yieldDeposit(uint256 _amount, UserInfo memory user, IERC20 lpToken) internal { lpToken.approve(masterChef, _amount); IMaster(masterChef).deposit(lpId,_amount); // move lptoken to masterchef uint256 accYieldPerShare = poolDetails(lpId); if (user.amount > 0) { uint256 pendinglp = user.amount.mul(accYieldPerShare).div(1e12).sub(user.debt); if(pendinglp > 0){ user.debt = user.amount.mul(accYieldPerShare).div(1e12); safeYieldTransfer(msg.sender, pendinglp); } } user.debt = user.amount.mul(accYieldPerShare).div(1e12); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _amount) public { UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount && _amount > 0, "withdraw: not good"); rewardPool.updatePool(poolId); (IERC20 lpToken, , , uint256 acconePoolPerShare,) = rewardPool.poolInfo(poolId); uint256 pending = user.amount.mul(acconePoolPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0){ safeonePoolTransfer(msg.sender, pending); } if(vaultStatus == true){ yieldWithdraw(_amount, user); } user.amount = user.amount.sub(_amount); totalSupply = totalSupply.sub(_amount); user.rewardDebt = user.amount.mul(acconePoolPerShare).div(1e12); lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, poolId, _amount); } function yieldWithdraw(uint256 _amount, UserInfo memory user) internal { (IERC20 lpToken, , , ,) = rewardPool.poolInfo(poolId); if(lpToken.balanceOf(address(this)) < _amount){ IMaster(masterChef).withdraw(lpId,_amount); } uint accYieldPerShare = poolDetails(lpId); uint256 pendinglp = user.amount.mul(accYieldPerShare).div(1e12).sub(user.debt); if(pendinglp > 0){ safeYieldTransfer(msg.sender, pendinglp); } user.debt = user.amount.mul(accYieldPerShare).div(1e12); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() public { (IERC20 lpToken, , , ,) = rewardPool.poolInfo(poolId); UserInfo storage user = userInfo[msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; user.debt = 0; totalSupply = totalSupply.sub(amount); if( (vaultStatus == true) && (lpToken.balanceOf(address(this)) < amount) ){ IMaster(masterChef).withdraw(lpId,amount); } lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, poolId, amount); } // Safe onePool transfer function, just in case if rounding error causes pool to not have enough 1Pool. function safeonePoolTransfer(address _to, uint256 _amount) internal { uint256 onePoolBal = onePool.balanceOf(address(this)); if (_amount > onePoolBal) { onePool.transfer(_to, onePoolBal); } else { onePool.transfer(_to, _amount); } } function safeYieldTransfer(address _to, uint256 _amount) internal { uint256 bal = IERC20(token).balanceOf(address(this)); if(bal < _amount){ _amount = bal; } if(_amount > 0) { uint256 treasuryFund = _amount.mul(rewardPool.treasuryPcent()).div(100); uint256 stakerFund = _amount.mul(rewardPool.stakePcent()).div(100); _amount = _amount.mul(rewardPool.yieldPcent()).div(100); IERC20(token).safeTransfer(_to, _amount); // user reward if( (rewardPool.stake() != address(0)) && (stakerFund > 0 ) ){ IERC20(token).safeTransfer(rewardPool.stake(), stakerFund); // stakingHolder reward } if( (rewardPool.treasury() != address(0)) && (treasuryFund > 0) ){ IERC20(token).safeTransfer(rewardPool.treasury(),treasuryFund); // treasury reward } } } function emergencyWithReward() external onlyOwner { if(vaultStatus){ (IERC20 lpToken, , , ,) = rewardPool.poolInfo(poolId); IMaster(masterChef).withdraw(lpId, totalSupply); vaultStatus = false; emit EmergencyWithdraw(address(this), poolId, totalSupply); } } function emergency() external onlyOwner { if(vaultStatus){ IMaster(masterChef).emergencyWithdraw(lpId); vaultStatus = false; } } function setVaultStatus(bool _status) external onlyOwner { require(vaultStatus != _status , "invalid status"); (IERC20 lpToken, , , ,) = rewardPool.poolInfo(poolId); if(vaultStatus){ IMaster(masterChef).emergencyWithdraw(lpId); } vaultStatus = _status; emit SetVaultStatus(msg.sender, _status); } // View function to see pending 1Pool on frontend. function pendingonePool(address _user) public view returns (uint256) { ( , uint256 allocPoint, uint256 lastRewardBlock, uint256 acconePoolPerShare, ) = rewardPool.poolInfo(poolId); UserInfo storage user = userInfo[_user]; uint256 _acconePoolPerShare = acconePoolPerShare; uint256 lpSupply = totalSupply; if (block.number > lastRewardBlock && lpSupply != 0) { uint256 multiplier = rewardPool.getMultiplier(lastRewardBlock, block.number); uint256 onePoolReward = multiplier.mul(rewardPool.onePoolPerBlock()).mul(allocPoint).div( rewardPool.totalAllocPoint() ); onePoolReward = onePoolReward.sub(onePoolReward.div(10)); _acconePoolPerShare = _acconePoolPerShare.add( onePoolReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(_acconePoolPerShare).div(1e12).sub(user.rewardDebt); } function rewardpool()external view returns(address){ return address(rewardPool); } function poolDetails(uint _poolId) public view returns(uint poolAccPerShare){ ( , , , poolAccPerShare) = IMaster(masterChef).poolInfo(_poolId); } function getyieldReward(address _user) external view returns(uint pendinglp){ if (vaultStatus == true){ UserInfo storage user = userInfo[_user]; ( address lpToken, uint256 allocPoint, uint256 lastRewardBlock, uint256 yieldPerShare) = getPoolDetails(lpId); uint256 lpSupply = IERC20(lpToken).balanceOf(masterChef); uint256 multiplier = IMaster(masterChef).getMultiplier(lastRewardBlock, block.number); uint256 sushiReward = multiplier.mul(IMaster(masterChef).sushiPerBlock()).mul(allocPoint).div(IMaster(masterChef).totalAllocPoint()); uint accSushiPerShare = yieldPerShare.add(sushiReward.mul(1e12).div(lpSupply)); pendinglp = user.amount.mul(accSushiPerShare).div(1e12).sub(user.debt); return pendinglp.mul(rewardPool.yieldPcent()).div(100); } } function getRewardonePool(address _user) external view returns(uint _totalReward) { _totalReward = pendingonePool(_user); (, , , uint256 acconePoolPerShare,) = rewardPool.poolInfo(poolId); UserInfo storage user = userInfo[_user]; uint256 pending = user.amount.mul(acconePoolPerShare).div(1e12).sub(user.rewardDebt); _totalReward = _totalReward + pending; } function getPoolDetails(uint _poolId) public view returns(address lpToken, uint256 allocPoint, uint256 lastRewardBlock, uint256 poolAccPerShare){ (lpToken ,allocPoint , lastRewardBlock, poolAccPerShare) = IMaster(masterChef).poolInfo(_poolId); } } contract RewardPool is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. 1Pool to distribute per block. uint256 lastRewardBlock; // Last block number that 1Pool distribution occurs. uint256 acconePoolPerShare; // Accumulated 1Pool per share, times 1e12. See below. address reawardFactory; // lp staking contract address } // The onePool TOKEN! ONEPOOL public onePool; // onePool tokens created per block. uint256 public onePoolPerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when onePool mining starts. uint256 public startBlock; // The Masterchef address address public masterChef; // The yield reawrd token address public token; // One pool converter address address public stake; // The treasury address address public treasury; address public devaddr; uint256 public treasuryPcent = 5; // 5% uint256 public stakePcent = 20; // 25% uint256 public yieldPcent = 75; mapping(address => bool) public lpPoolStatus; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event OnePoolPerBlock(uint256 value); event SetTreasury(address newTreasury); event SetStake(address stake); event SetDev(address sender, address newdev); event SetFeePcent(address sender, uint256 newTreasuryPcent, uint256 newStakingPcent, uint256 newYieldPcent); modifier lpPool(address _lpToken) { require(lpPoolStatus[_lpToken] == false, "invalid"); _; } constructor(ONEPOOL _onePool, uint256 _onePoolPerBlock, uint256 _startBlock, address _masterChef, address _token, address _tresary, address _convert, address _dev) public { onePool = _onePool; onePoolPerBlock = _onePoolPerBlock; startBlock = _startBlock; masterChef = _masterChef; token = _token; stake = _convert; treasury = _tresary; devaddr = _dev; } function poolLength() public view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. function add( uint256 _allocPoint,IERC20 _lpToken, bool _withUpdate, uint256 _lpId, bool _status) public onlyOwner { require(lpPoolStatus[address(_lpToken)] == false, "duplicated"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); address _reawardFactory = address(new RewardPoolFactory(RewardPool(address(this)), onePool, poolLength(), _lpId, masterChef, token,_status, msg.sender)); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, acconePoolPerShare: 0, reawardFactory: _reawardFactory }) ); lpPoolStatus[address(_lpToken)] = true; } // Update the given pool's onePool allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { require( _pid < poolLength(), "pool not exist"); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); require(lpPoolStatus[address(poolInfo[_pid].lpToken)] == true, "invalid"); poolInfo[_pid].allocPoint = _allocPoint; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { return _to.sub(_from); } // 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 { require(lpPoolStatus[address(poolInfo[_pid].lpToken)] == true, "invalid"); PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = RewardPoolFactory(pool.reawardFactory).totalSupply(); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 onePoolReward = multiplier.mul(onePoolPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); onePool.mint(devaddr, onePoolReward.div(10)); onePoolReward = onePoolReward.sub(onePoolReward.div(10)); require(onePool.mint(pool.reawardFactory, onePoolReward)); pool.acconePoolPerShare = pool.acconePoolPerShare.add( onePoolReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } // Safe onePool transfer function, just in case if rounding error causes pool to not have enough 1Pool. function safeonePoolTransfer(address _to, uint256 _amount) internal { uint256 onePoolBal = onePool.balanceOf(address(this)); if (_amount > onePoolBal) { onePool.transfer(_to, onePoolBal); } else { onePool.transfer(_to, _amount); } } function setONEPoolBlock(uint256 _amount) public onlyOwner { massUpdatePools(); onePoolPerBlock =_amount; emit OnePoolPerBlock(_amount); } function setTreasury(address _treasury) public onlyOwner { treasury =_treasury; emit SetTreasury(_treasury); } function setStake(address _stake) public onlyOwner { stake =_stake; emit SetStake(_stake); } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; SetDev(msg.sender, _devaddr); } function setFeePcent(uint256 _treasury, uint256 _stake) external onlyOwner { require(_treasury.add(_stake) < 100 , "invalid fee"); treasuryPcent = _treasury; stakePcent = _stake; yieldPcent = uint256(100).sub(treasuryPcent.add(_stake)); emit SetFeePcent(msg.sender, treasuryPcent, stakePcent, yieldPcent); } }
Withdraw LP tokens from MasterChef.
function withdraw(uint256 _amount) public { UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount && _amount > 0, "withdraw: not good"); rewardPool.updatePool(poolId); (IERC20 lpToken, , , uint256 acconePoolPerShare,) = rewardPool.poolInfo(poolId); uint256 pending = user.amount.mul(acconePoolPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0){ safeonePoolTransfer(msg.sender, pending); } if(vaultStatus == true){ yieldWithdraw(_amount, user); } user.amount = user.amount.sub(_amount); totalSupply = totalSupply.sub(_amount); user.rewardDebt = user.amount.mul(acconePoolPerShare).div(1e12); lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, poolId, _amount); }
12,135,166
pragma solidity ^0.8.4; import "remix_tests.sol"; // injected by remix-tests import "./Company.sol"; contract MyTest { // Deploy our ERC721 contract to the ethereum blockchain allowing ‘Company’ tokens to be minted. Company company; function beforeAll() public { // deploy share contract Share share; // mint erc721 token company = new Company(0x72656d6978000000000000000000000000000000000000000000000000000000, 'testcompany', 'testURI', 1000, 2); // point erc20 token to erc721 token share.setCompanyContractLocation(0x72656d6978000000000000000000000000000000000000000000000000000000); } function initialNameTest() public returns (bool) { // make a share shares.mintShares() return Assert.equal(share.name(), 'testcompany', "initial value is not correct"); } function initialValueShouldNotBe200() public returns (bool) { return Assert.notEqual(foo.get(), 200, "initial value is not correct"); } function shouldTriggerOneFail() public { Assert.equal(uint(1), uint(2), "uint test 1 fails"); Assert.notEqual(uint(1), uint(2), "uint test 2 passes"); } function shouldTriggerOnePass() public { Assert.equal(uint(1), uint(1), "uint test 3 passes"); } }
deploy share contract mint erc721 token point erc20 token to erc721 token
function beforeAll() public { Share share; company = new Company(0x72656d6978000000000000000000000000000000000000000000000000000000, 'testcompany', 'testURI', 1000, 2); share.setCompanyContractLocation(0x72656d6978000000000000000000000000000000000000000000000000000000); }
12,725,307
./partial_match/1/0x14cC8DfaF2258E1B8B2869300dBa1B734dc0fE43/sources/KtuneTokenBlocks.sol
return the address of the owner./
function owner() public view returns (address) { return _owner; }
2,737,018
./full_match/1/0x0bC24E61DAAd6293A1b3b53a7D01086BfF0Ea6e5/sources/contracts/FeeManager/FeeManagerHelper.sol
Internal function updating bad debt amount of a position and global one (in USD). Compares totalBorrow and totalCollateral of the postion in USD anadjustes bad debt variables. Pseudo pool amounts needed to be updated before this function is called./
function _updateUserBadDebt( uint256 _nftId ) internal { uint256 currentBorrowUSD = WISE_SECURITY.overallUSDBorrowHeartbeat( _nftId ); uint256 currentCollateralBareUSD = WISE_SECURITY.overallUSDCollateralsBare( _nftId ); uint256 currentBadDebt = badDebtPosition[ _nftId ]; if (currentBorrowUSD < currentCollateralBareUSD) { _eraseBadDebtUser( _nftId ); _decreaseTotalBadDebt( currentBadDebt ); emit UpdateBadDebtPosition( _nftId, 0, block.timestamp ); return; } uint256 newBadDebt = currentBorrowUSD - currentCollateralBareUSD; _setBadDebtPosition( _nftId, newBadDebt ); newBadDebt > currentBadDebt ? _increaseTotalBadDebt(newBadDebt - currentBadDebt) : _decreaseTotalBadDebt(currentBadDebt - newBadDebt); emit UpdateBadDebtPosition( _nftId, newBadDebt, block.timestamp ); }
4,818,629
/** *Submitted for verification at Etherscan.io on 2021-05-30 */ /* * Fire Inu (FINU) * * Anon fork with adjusted tokenomics. * * Locking Liquidity. * * Total Supply: 100,000,000,000,000 * Max Buy: 690,000,000,000 (0.69% of Total Supply) * Max Hold: 2,100,000,000,000 (2.1% of Total Supply) * * READ THIS CAREFULLY: * The starting taxes will be as follows and may change based on the community vote * Sell within 1 day : 32% tax (0% burn, 32% Liquidity, 0% Holders) * Sell within 3 days : 30% tax (4% burn, 20% Liquidity, 6% Holders) * Sell within 3 weeks : 20% tax (6% burn, 10% Liquidity, 4% Holders) * Standard : 8% tax (6% burn, 0% Liquidity, 2% Holders) * * https://fireinu.com * https://t.me/FireInuToken * */ pragma solidity ^0.6.12; // SPDX-License-Identifier: The MIT License interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. (extra from BEP20) */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. (extra from BEP20) */ function name() external view returns (string memory); /** * @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}. * * Owner Validation: * VsLbhPbclGuvfYvarBsS!E3!AHLbherNFuvgQriJubQbrfagPurpxBirePbqr * * 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; } } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, 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); } // File: contracts\interfaces\IUniswapV2Router02.sol pragma solidity >=0.6.2; 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; } pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function 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; function INIT_CODE_PAIR_HASH() external view returns (bytes32); } pragma solidity >=0.5.0; interface IUniswapPair { 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; } contract FireInu is Context, IERC20, Ownable { // Interfaces are from sister chain ^^. Kept it the same for simplicity using SafeMath for uint256; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant HOUR = 60 * 60; uint256 private constant MAX = ~uint256(0); bool inSwapAndLiquify; uint256 private _tTotal = 100 * 10**12 * 10**18; // 100 Trillion uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 public _maxTxAmount = 690 * 10**9 * 10**18; // Max Transaction: 690 Billion (0.69%) uint256 public _numTokensSellToAddToLiquidity = 300 * 10**9 * 10**18; // 300 Billion uint256 public _maxWalletToken = 2.1 * 10**12 * 10**18; // Max Wallet: 2.1 Trillion (2.1%) // Fees uint256 public _burnFee = 2 * 10**2; // 200 = 2.00% uint256 public _liquidityFee = 2 * 10**2; // 200 = 2.00% uint256 public _holderFee = 2 * 10**2; // 200 = 2.00% uint256 public _previousBurnFee = _burnFee; uint256 public _previousLiquidityFee = _liquidityFee; uint256 public _previousHolderFee = _holderFee; uint256[] public _taxTiers = [24, 72, 504]; // 24 = 1 day, 72 = 3 days, 504 = 3 weeks IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; string private _name = "FireInu"; string private _symbol = "FINU"; uint8 private _decimals = 18; uint256 private _start_timestamp = block.timestamp; event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity, uint256 contractTokenBalance ); constructor() public { _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; IUniswapV2Router02 _uniswapswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapswapV2Router.factory()) .createPair(address(this), _uniswapswapV2Router.WETH()); uniswapV2Router = _uniswapswapV2Router; emit Transfer(address(0), _msgSender(), _tTotal); } modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } // This section allows for adjust tokenomics /* * newStartTimestamp: in seconds */ function resetStartTimestamp(uint256 newStartTimestamp) public onlyOwner { _start_timestamp = newStartTimestamp; } /* * newBurnFee: 200 = 2.00% */ function setBurnFee(uint256 newBurnFee) public onlyOwner { require(newBurnFee <= _burnFee); _burnFee = newBurnFee; } /* * newLiquidityFee: 200 = 2.00% */ function setLiquidityFee(uint256 newLiquidityFee) public onlyOwner { require(newLiquidityFee <= _liquidityFee); _liquidityFee = newLiquidityFee; } /* * newHolderFee: 200 = 2.00% */ function setHolderFee(uint256 newHolderFee) public onlyOwner { require(newHolderFee <= _holderFee); _holderFee = newHolderFee; } /* * newHours: in hours */ function setTier(uint256 count, uint256 newHours) public onlyOwner { require(count < _taxTiers.length); _taxTiers[count] = newHours; } /* * newNum: 300 * 10**9 * 10**18 = 300 Billion */ function setNumTokensSellToAddToLiquidity(uint256 newNum) public onlyOwner { require(newNum <= _numTokensSellToAddToLiquidity); _numTokensSellToAddToLiquidity = newNum; } function toggleExcludedFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = !_isExcludedFromFee[account]; } // Getters function name() public view override returns (string memory) { return _name; } function symbol() public view override returns (string memory) { return _symbol; } function decimals() public view override returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function startTimestampForTax() public view returns (uint256) { return _start_timestamp; } function burnPercent() public view returns (uint256) { return _getCurrentBurnFee(); } function liquidityPercent() public view returns (uint256) { return _getCurrentLiqFee(); } function holderPercent() public view returns (uint256) { return _getCurrentHolderFee(); } function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFromFee[account]; } /* * Wen tier end in seconds from epoc */ function wenTierEnd(uint256 count) public view returns (uint256) { require(count < _taxTiers.length); return _start_timestamp + (_taxTiers[count] * HOUR); } function numTokensSellToAddToLiquidity() public view returns (uint256) { return _numTokensSellToAddToLiquidity; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function pSolHoldAME() public pure returns (string memory) { return "LbherNFuvgQriJubQbrfagPurpxBirePbqrVsAbgS!ER!Ah"; } // Getters function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function reflect(uint256 tAmount) public { address sender = _msgSender(); (uint256 rAmount, , , , , , ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , , ) = _getValues(tAmount); return rAmount; } else { (, uint256 rTransferAmount, , , , , ) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function removeAllFee() private { if (_burnFee == 0 && _holderFee == 0 && _liquidityFee == 0) return; _previousBurnFee = _burnFee; _previousHolderFee = _holderFee; _previousLiquidityFee = _liquidityFee; _burnFee = 0; _holderFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _burnFee = _previousBurnFee; _holderFee = _previousHolderFee; _liquidityFee = _previousLiquidityFee; } function _transfer( address sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if ( sender != owner() && recipient != owner() && recipient != address(1) && recipient != address(0xdead) && recipient != uniswapV2Pair ) { require( amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount." ); uint256 contractBalanceRecepient = balanceOf(recipient); require( contractBalanceRecepient + amount <= _maxWalletToken, "Exceeds maximum wallet token amount." ); } // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && sender != uniswapV2Pair ) { contractTokenBalance = _numTokensSellToAddToLiquidity; swapAndLiquify(contractTokenBalance); } bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if ( _isExcludedFromFee[sender] || _isExcludedFromFee[recipient] || sender == uniswapV2Pair ) { takeFee = false; } if (!takeFee) removeAllFee(); _transferStandard(sender, recipient, amount); if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tBurn ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); if (tBurn > 0) _reflectBurn(sender, tBurn); emit Transfer(sender, recipient, tTransferAmount); } function _reflectBurn(address sender, uint256 tBurn) private { _rOwned[address(0xdead)] = _rOwned[address(0xdead)].add(tBurn); _tTotal = _tTotal.sub(tBurn); _rTotal = _rTotal.sub(tBurn); emit Transfer(sender, address(0xdead), tBurn); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256, uint256 ) { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tBurn ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, tBurn, _getRate()); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity, tBurn ); } function _getCurrentBurnFee() private view returns (uint256) { uint256 time_since_start = block.timestamp - _start_timestamp; if (time_since_start < _taxTiers[0] * HOUR) { return _burnFee.mul(0); } else if (time_since_start < _taxTiers[1] * HOUR) { return _burnFee.mul(2); } else if (time_since_start < _taxTiers[2] * HOUR) { return _burnFee.mul(3); } else { return _burnFee.mul(3); } } function _getCurrentLiqFee() private view returns (uint256) { uint256 time_since_start = block.timestamp - _start_timestamp; if (time_since_start < _taxTiers[0] * HOUR) { return _liquidityFee.mul(16); } else if (time_since_start < _taxTiers[1] * HOUR) { return _liquidityFee.mul(10); } else if (time_since_start < _taxTiers[2] * HOUR) { return _burnFee.mul(5); } else { return _liquidityFee.mul(0); } } function _getCurrentHolderFee() private view returns (uint256) { uint256 time_since_start = block.timestamp - _start_timestamp; if (time_since_start < _taxTiers[0] * HOUR) { return _holderFee.mul(0); } else if (time_since_start < _taxTiers[1] * HOUR) { return _holderFee.mul(3); } else if (time_since_start < _taxTiers[2] * HOUR) { return _burnFee.mul(2); } else { return _holderFee.mul(1); } } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256 ) { // uint256 currentBurnFee = _getCurrentBurnFee(); // uint256 currentLiqFee = _getCurrentLiqFee(); // uint256 currentHolderFee = _getCurrentHolderFee(); // 10**2 for percentage. Another 10**2 to allow fees with decimals in the future uint256 tBurn = tAmount.div(10**2).mul(_getCurrentBurnFee()).div(10**2); uint256 tLiquidity = tAmount.div(10**2).mul(_getCurrentLiqFee()).div(10**2); uint256 tFee = tAmount.div(10**2).mul(_getCurrentHolderFee()).div(10**2); uint256 tTransferAmount = tAmount.sub(tBurn).sub(tLiquidity).sub(tFee); return (tTransferAmount, tFee, tLiquidity, tBurn); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 tBurn, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rBurn = tBurn.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity).sub(rBurn); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // If you copy this line of F!R3!NU you're a shit dev who doesn't check over code // 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 swapTokensForBNB(half); // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf, contractTokenBalance); } function swapTokensForBNB(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 owner(), block.timestamp ); } receive() external payable {} }
Wen tier end in seconds from epoc/
function wenTierEnd(uint256 count) public view returns (uint256) { require(count < _taxTiers.length); return _start_timestamp + (_taxTiers[count] * HOUR); }
2,213,222
pragma solidity ^0.5.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex); event Approval(address indexed owner, address indexed approved, uint256 indexed nftIndex); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /// NEW EVENTS - ADDED BY KASPER event txMint(address indexed from, address indexed to, uint256 indexed nftIndex); event txPrimary(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex); event txSecondary(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex); event txCollect(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex); /** * @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 `nftIndex`. */ function ownerOf(uint256 nftIndex) public view returns (address owner); /** * @dev Transfers a specific NFT (`nftIndex`) from one account (`originAddress `) to * another (`to`). * Requirements: * - `originAddress `, `to` cannot be zero. * - `nftIndex` must be owned by `originAddress `. * - If the caller is not `originAddress `, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex) public; /** * @dev Transfers a specific NFT (`nftIndex`) from one account (`originAddress `) to * another (`to`). * Requirements: * - If the caller is not `originAddress `, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address originAddress, address destinationAddress, uint256 nftIndex) public; function approve(address destinationAddress, uint256 nftIndex) public; function getApproved(uint256 nftIndex) 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 originAddress, address destinationAddress, uint256 nftIndex, bytes memory data) public; } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param originAddress The address which previously owned the token * @param nftIndex The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address originAddress, uint256 nftIndex, bytes memory data) public returns (bytes4); } /** * @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; } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param nftIndex uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 nftIndex) public view returns (address) { address owner = _tokenOwner[nftIndex]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param destinationAddress address to be approved for the given token ID * @param nftIndex uint256 ID of the token to be approved */ function approve(address destinationAddress, uint256 nftIndex) public { address owner = ownerOf(nftIndex); require(destinationAddress != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[nftIndex] = destinationAddress; emit Approval(owner, destinationAddress, nftIndex); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param nftIndex uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 nftIndex) public view returns (address) { require(_exists(nftIndex), "ERC721: approved query for nonexistent token"); return _tokenApprovals[nftIndex]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param destinationAddress operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address destinationAddress, bool approved) public { require(destinationAddress != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][destinationAddress] = approved; emit ApprovalForAll(_msgSender(), destinationAddress, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param originAddress current owner of the token * @param destinationAddress address to receive the ownership of the given token ID * @param nftIndex uint256 ID of the token to be transferred */ function transferFrom(address originAddress, address destinationAddress, uint256 nftIndex) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), nftIndex), "ERC721: transfer caller is not owner nor approved"); _transferFrom(originAddress, destinationAddress, nftIndex); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param originAddress current owner of the token * @param destinationAddress address to receive the ownership of the given token ID * @param nftIndex uint256 ID of the token to be transferred */ function safeTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex) public { safeTransferFrom(originAddress, destinationAddress, nftIndex, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param originAddress current owner of the token * @param destinationAddress address to receive the ownership of the given token ID * @param nftIndex uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), nftIndex), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(originAddress, destinationAddress, nftIndex, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param originAddress current owner of the token * @param destinationAddress address to receive the ownership of the given token ID * @param nftIndex uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex, bytes memory _data) internal { _transferFrom(originAddress, destinationAddress, nftIndex); require(_checkOnERC721Received(originAddress, destinationAddress, nftIndex, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param nftIndex uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 nftIndex) internal view returns (bool) { address owner = _tokenOwner[nftIndex]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param nftIndex uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 nftIndex) internal view returns (bool) { require(_exists(nftIndex), "ERC721: operator query for nonexistent token"); address owner = ownerOf(nftIndex); return (spender == owner || getApproved(nftIndex) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param destinationAddress The address that will own the minted token * @param nftIndex uint256 ID of the token to be minted */ function _safeMint(address destinationAddress, uint256 nftIndex) internal { _safeMint(destinationAddress, nftIndex, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param destinationAddress The address that will own the minted token * @param nftIndex uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address destinationAddress, uint256 nftIndex, bytes memory _data) internal { _mint(destinationAddress, nftIndex); require(_checkOnERC721Received(address(0), destinationAddress, nftIndex, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param destinationAddress The address that will own the minted token * @param nftIndex uint256 ID of the token to be minted */ function _mint(address destinationAddress, uint256 nftIndex) internal { require(destinationAddress != address(0), "ERC721: mint to the zero address"); require(!_exists(nftIndex), "ERC721: token already minted"); _tokenOwner[nftIndex] = destinationAddress; _ownedTokensCount[destinationAddress].increment(); emit Transfer(address(0), destinationAddress, nftIndex); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param nftIndex uint256 ID of the token being burned */ function _burn(address owner, uint256 nftIndex) internal { require(ownerOf(nftIndex) == owner, "ERC721: burn of token that is not own"); _clearApproval(nftIndex); _ownedTokensCount[owner].decrement(); _tokenOwner[nftIndex] = address(0); emit Transfer(owner, address(0), nftIndex); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param nftIndex uint256 ID of the token being burned */ function _burn(uint256 nftIndex) internal { _burn(ownerOf(nftIndex), nftIndex); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param originAddress current owner of the token * @param destinationAddress address to receive the ownership of the given token ID * @param nftIndex uint256 ID of the token to be transferred */ function _transferFrom(address originAddress, address destinationAddress, uint256 nftIndex) internal { require(ownerOf(nftIndex) == originAddress, "ERC721: transfer of token that is not own"); require(destinationAddress != address(0), "ERC721: transfer to the zero address"); _clearApproval(nftIndex); _ownedTokensCount[originAddress].decrement(); _ownedTokensCount[destinationAddress].increment(); _tokenOwner[nftIndex] = destinationAddress; emit Transfer(originAddress, destinationAddress, nftIndex); } /** * @dev Only used/called by GET Protocol relayer - ADDED / NEW * @notice The function assumes that the originAddress has signed the tx. * @param originAddress the address the NFT will be extracted from * @param destinationAddress the address of the ticketeer that will receive the NFT * @param nftIndex the index of the NFT that will be returned to the tickeer */ function _relayerTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex) internal { _clearApproval(nftIndex); _ownedTokensCount[originAddress].decrement(); _ownedTokensCount[destinationAddress].increment(); _tokenOwner[nftIndex] = destinationAddress; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * This function is deprecated. * @param originAddress address representing the previous owner of the given token ID * @param destinationAddress target address that will receive the tokens * @param nftIndex 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 originAddress, address destinationAddress, uint256 nftIndex, bytes memory _data) internal returns (bool) { if (!destinationAddress.isContract()) { return true; } bytes4 retval = IERC721Receiver(destinationAddress).onERC721Received(_msgSender(), originAddress, nftIndex, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param nftIndex uint256 ID of the token to be transferred */ function _clearApproval(uint256 nftIndex) private { if (_tokenApprovals[nftIndex] != address(0)) { _tokenApprovals[nftIndex] = address(0); } } } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 nftIndex); function tokenByIndex(uint256 index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => 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; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferoriginAddress, this imposes no restrictions on msg.sender. * @param originAddress current owner of the token * @param destinationAddress address to receive the ownership of the given token ID * @param nftIndex uint256 ID of the token to be transferred */ function _transferFrom(address originAddress, address destinationAddress, uint256 nftIndex) internal { super._transferFrom(originAddress, destinationAddress, nftIndex); _removeTokenFromOwnerEnumeration(originAddress, nftIndex); _addTokenToOwnerEnumeration(destinationAddress, nftIndex); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferoriginAddress, this imposes no restrictions on msg.sender. * @param originAddress current owner of the token * @param destinationAddress address to receive the ownership of the given token ID * @param nftIndex uint256 ID of the token to be transferred */ function _relayerTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex) internal { super._relayerTransferFrom(originAddress, destinationAddress, nftIndex); _removeTokenFromOwnerEnumeration(originAddress, nftIndex); _addTokenToOwnerEnumeration(destinationAddress, nftIndex); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param destinationAddress address the beneficiary that will own the minted token * @param nftIndex uint256 ID of the token to be minted */ function _mint(address destinationAddress, uint256 nftIndex) internal { super._mint(destinationAddress, nftIndex); _addTokenToOwnerEnumeration(destinationAddress, nftIndex); _addTokenToAllTokensEnumeration(nftIndex); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param nftIndex uint256 ID of the token being burned */ function _burn(address owner, uint256 nftIndex) internal { super._burn(owner, nftIndex); _removeTokenFromOwnerEnumeration(owner, nftIndex); // Since nftIndex will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[nftIndex] = 0; _removeTokenFromAllTokensEnumeration(nftIndex); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param destinationAddress address representing the new owner of the given token ID * @param nftIndex uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address destinationAddress, uint256 nftIndex) private { _ownedTokensIndex[nftIndex] = _ownedTokens[destinationAddress].length; _ownedTokens[destinationAddress].push(nftIndex); } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param nftIndex uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 nftIndex) private { _allTokensIndex[nftIndex] = _allTokens.length; _allTokens.push(nftIndex); } /** * @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 originAddress address representing the previous owner of the given token ID * @param nftIndex uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address originAddress, uint256 nftIndex) 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 = _ownedTokens[originAddress ].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[nftIndex]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastnftIndex = _ownedTokens[originAddress ][lastTokenIndex]; _ownedTokens[originAddress ][tokenIndex] = lastnftIndex; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastnftIndex] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array _ownedTokens[originAddress ].length--; // Note that _ownedTokensIndex[nftIndex] hasn't been cleared: it still points to the old slot (now occupied by // lastnftIndex, or just over the end of the array if the token was the last one). } /** * @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 nftIndex uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 nftIndex) 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.sub(1); uint256 tokenIndex = _allTokensIndex[nftIndex]; /** 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 lastnftIndex = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastnftIndex; // Move the last token to the slot of the to-delete token _allTokensIndex[lastnftIndex] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array _allTokens.length--; _allTokensIndex[nftIndex] = 0; } } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function nftMetadata(uint256 nftIndex) external view returns (string memory); } contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _nftMetadatas; // // Optional mapping for tickeer_ids (underwriter) mapping (uint256 => address) private _ticketeerAddresss; // Base URI string private _baseURI; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('nftMetadata(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param nftIndex uint256 ID of the token to query */ function nftMetadata(uint256 nftIndex) external view returns (string memory) { require(_exists(nftIndex), "ERC721Metadata: URI query for nonexistent token"); return _nftMetadatas[nftIndex]; } /// NEW function getTicketeerOwner(uint256 nftIndex) public view returns (address) { require(_exists(nftIndex), "ERC721Metadata: Tickeer owner query for nonexistent token"); return _ticketeerAddresss[nftIndex]; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param nftIndex uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setnftMetadata (uint256 nftIndex, string memory uri) internal { require(_exists(nftIndex), "ERC721Metadata: URI set of nonexistent token"); _nftMetadatas[nftIndex] = uri; } /** NEW FUNCTION - ADDED BY KASPER * @dev Sets `_nftMetadata ` as the nftMetadata of `nftIndex`. */ function _addTicketeerIndex(uint256 nftIndex, address _ticketeerAddress) internal { require(_exists(nftIndex), "ERC721Metadata: URI set of nonexistent token"); _ticketeerAddresss[nftIndex] = _ticketeerAddress; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param nftIndex uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 nftIndex) internal { super._burn(owner, nftIndex); // Clear metadata (if any) if (bytes(_nftMetadatas[nftIndex]).length != 0) { delete _nftMetadatas[nftIndex]; } } } /** NEW ADDED * @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 { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title Full ERC721 Token * @dev This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology. * * See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { // solhint-disable-previous-line no-empty-blocks } } /** * @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]; } } contract MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(_msgSender()); } 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 onlyMinter { _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); } } contract RelayerRole is Context { using Roles for Roles.Role; event RelayerAdded(address indexed account); event RelayerRemoved(address indexed account); Roles.Role private _relayers; constructor () internal { _addRelayer(_msgSender()); } modifier onlyRelayer() { require(isRelayer(_msgSender()), "RelayerRole: caller does not have the Relayer role"); _; } function isRelayer(address account) public view returns (bool) { return _relayers.has(account); } function addRelayer(address account) public onlyRelayer { _addRelayer(account); } function renounceRelayer() public { _removeRelayer(_msgSender()); } function _addRelayer(address account) internal { _relayers.add(account); emit RelayerAdded(account); } function _removeRelayer(address account) internal { _relayers.remove(account); emit RelayerRemoved(account); } } /** * @title ERC721Mintable * @dev ERC721 minting logic. */ contract ERC721Mintable is ERC721, MinterRole, RelayerRole { /** * @dev Function to mint tokens. * @param destinationAddress The address that will receive the minted token. * @param nftIndex The token id to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address destinationAddress, uint256 nftIndex) private onlyMinter returns (bool) { _mint(destinationAddress, nftIndex); return true; } /** * @dev Function to safely mint tokens. * @param destinationAddress The address that will receive the minted token. * @param nftIndex The token id to mint. * @return A boolean that indicates if the operation was successful. */ function safeMint(address destinationAddress, uint256 nftIndex) private onlyMinter returns (bool) { _safeMint(destinationAddress, nftIndex); return true; } /** * @dev Function to safely mint tokens. * @param destinationAddress The address that will receive the minted token. * @param nftIndex The token id to mint. * @param _data bytes data to send along with a safe transfer check. * @return A boolean that indicates if the operation was successful. */ function safeMint(address destinationAddress, uint256 nftIndex, bytes memory _data) private onlyMinter returns (bool) { _safeMint(destinationAddress, nftIndex, _data); return true; } } /** * @title ERC721MetadataMintable * @dev ERC721 minting logic with metadata. */ contract ERC721MetadataMintable is ERC721, ERC721Metadata, MinterRole { /** * @dev Function to mint tokens. * @param destinationAddress The address that will receive the minted tokens. * @param nftIndex The token id to mint. * @param nftMetadata The token URI of the minted token. * @return A boolean that indicates if the operation was successful. */ function mintWithNftMetadata(address destinationAddress, uint256 nftIndex, string memory nftMetadata) private onlyMinter returns (bool) { _mint(destinationAddress, nftIndex); _setnftMetadata(nftIndex, nftMetadata); return true; } } /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ contract ERC721Burnable is Context, ERC721 { /** * @dev Burns a specific ERC721 token. * TODO This needs to be made onlyOwner as destroying NFTs is a form of control. * @param nftIndex uint256 id of the ERC721 token to be burned. */ function burn(uint256 nftIndex) private { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), nftIndex), "ERC721Burnable: caller is not owner nor approved"); _burn(nftIndex); } } /** * @title GET_NFTV02 * TODO Add Description * checking token existence, removal of a token from an address */ contract SmartTicketingERC721 is ERC721Full, ERC721Mintable, ERC721MetadataMintable, ERC721Burnable, Ownable { constructor (string memory _nftName, string memory _nftSymbol) public ERC721Mintable() ERC721Full(_nftName, _nftSymbol) { // solhint-disable-previous-line no-empty-blocks } using Counters for Counters.Counter; Counters.Counter private _nftIndexs; /** @notice This function mints a new NFT * @dev the nftIndex (NFT_index is auto incremented) * @param destinationAddress addres of the underwriter of the NFT */ function mintNFTIncrement(address destinationAddress) public onlyMinter returns (uint256) { _nftIndexs.increment(); uint256 newNFTIndex = _nftIndexs.current(); _mint(destinationAddress, newNFTIndex); _addTicketeerIndex(newNFTIndex, destinationAddress); return newNFTIndex; } /** @notice This function mints a new NFT -> * @dev the nftIndex needs to be provided in the call * @dev ensure that the provided newNFTIndex is unique and stored/cached. * @param newNFTIndex uint of the nftIndex that will be minted * @param destinationAddress addres of the underwriter of the NFT */ function mintNFT(address destinationAddress, uint256 newNFTIndex) public onlyMinter returns (uint256) { _mint(destinationAddress, newNFTIndex); _addTicketeerIndex(newNFTIndex, destinationAddress); return newNFTIndex; } /** @param originAddress addres of the underwriter of the NFT * @param destinationAddress addres of the to-be owner of the NFT * @param ticket_execution_data string containing the metadata about the ticket the NFT is representing */ function primaryTransfer(address originAddress, address destinationAddress, uint256 nftIndex, string memory ticket_execution_data) public { /// Check if originAddress currently owners the NFT require(ownerOf(nftIndex) == originAddress, "ERC721: transfer of token that is not own"); require(destinationAddress != address(0), "ERC721: transfer to the zero address"); /// Store the ticket_execution metadata in the NFT _setnftMetadata(nftIndex, ticket_execution_data); /// Transfer the NFT to the new owner safeTransferFrom(originAddress, destinationAddress, nftIndex); emit txPrimary(originAddress, destinationAddress, nftIndex); } /** * @notice This function can only be called by a whitelisted relayer address (onlyRelayer). * @notice As tx is relayed msg.sender is assumed to be signed by originAddress. * @dev Tx will fail/throw if originAddress is not owner of nftIndex * @dev Tx will fail/throw if destinationAddress is genensis address. * @dev TODO Tx should fail if destinationAddress is smart contract * @param originAddress address the NFT is asserted * @param destinationAddress addres of the to-be owner of the NFT * @param nftIndex uint256 ID of the token to be transferred */ function secondaryTransfer(address originAddress, address destinationAddress, uint256 nftIndex) public { /// Verify if originAddress is owner of nftIndex require(ownerOf(nftIndex) == originAddress, "ERC721: transfer of token that is not owned by owner"); /// Verify if destinationAddress isn't burn-address require(destinationAddress != address(0), "ERC721: transfer to the zero address"); /// Transfer the NFT to the new owner safeTransferFrom(originAddress, destinationAddress, nftIndex); emit txSecondary(originAddress, destinationAddress, nftIndex); } /** Returns the NFT of the ticketeer back to its address + cleans the ticket_execution metadata from the NFT * @notice This function doesn't require autorization of the NFT owner! This is basically a "seizing' of the NFT * @param nftIndex \uint256 ID of the token to be transferred * @param destinationAddress addres of the to-be owner of the NFT (should be tcketeer) * @dev It is possible for us to pass the "originAddress" in the contract call, but this can just as * well be fetched in the smart contract. Works ether way. */ function collectTransfer(uint256 nftIndex, address destinationAddress) public { /// Check if originAddress is actually the ticketeer owning the NFT require(getTicketeerOwner(nftIndex) == destinationAddress, "ERC721: transfer of token that is not own"); /// Check if the originAddress is the ticketeer require(getTicketeerOwner(nftIndex) == msg.sender, "ERC721: collection can only be done by ticketeer"); /// Fetch the address that owns the NFT address originAddress = ownerOf(nftIndex); address _ticketeerAddress = getTicketeerOwner(nftIndex); require(_ticketeerAddress == destinationAddress, "ERC721: collection of token that is not owned by the ticketeer"); /// Clean out ticketExectionHash _setnftMetadata(nftIndex, "NONE"); /// Transfer the NFT to the new owner _relayerTransferFrom(originAddress, destinationAddress, nftIndex); emit txCollect(originAddress, destinationAddress, nftIndex); } function exists(uint256 nftIndex) public view returns (bool) { return _exists(nftIndex); } function tokensOfOwner(address owner) public view returns (uint256[] memory) { return _tokensOfOwner(owner); } function setnftMetadata(uint256 nftIndex, string memory uri) private { _setnftMetadata(nftIndex, uri); } } /** @title A scalable implementation of all ERC721 NFT standards combined. * @author Kasper Keunen * @dev Extends SmartTicketingERC721 */ contract GET_NFTVPOC is SmartTicketingERC721 { constructor(string memory _nftName, string memory _nftSymbol) public SmartTicketingERC721(_nftName, _nftSymbol) { } }
Internal function to transfer ownership of a given token ID to another address. As opposed to transferoriginAddress, this imposes no restrictions on msg.sender. originAddress current owner of the token destinationAddress address to receive the ownership of the given token ID nftIndex uint256 ID of the token to be transferred/
function _transferFrom(address originAddress, address destinationAddress, uint256 nftIndex) internal { super._transferFrom(originAddress, destinationAddress, nftIndex); _removeTokenFromOwnerEnumeration(originAddress, nftIndex); _addTokenToOwnerEnumeration(destinationAddress, nftIndex); }
6,416,881
// Sources flattened with hardhat v2.0.5 https://hardhat.org // File @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol@v3.4.1 // 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); } } } } // File @openzeppelin/contracts-upgradeable/proxy/Initializable.sol@v3.4.1 // 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) { return !AddressUpgradeable.isContract(address(this)); } } // File @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol@v3.4.1 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 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 @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.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 OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.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 SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File @openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol@v3.4.1 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 ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol@v3.4.1 pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.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 SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File @openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol@v3.4.1 pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // File contracts/helpers/Sacrifice.sol pragma solidity 0.7.0; contract Sacrifice { constructor(address payable _recipient) payable { selfdestruct(_recipient); } } // File @openzeppelin/contracts/utils/Context.sol@v3.4.1 pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/token/ERC20/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/token/ERC20/ERC20.sol@v3.4.1 pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File @openzeppelin/contracts/utils/Pausable.sol@v3.4.1 pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File @openzeppelin/contracts/token/ERC20/ERC20Pausable.sol@v3.4.1 pragma solidity >=0.6.0 <0.8.0; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // 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/utils/EnumerableSet.sol@v3.4.1 pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File @openzeppelin/contracts/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/access/AccessControl.sol@v3.4.1 pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol@v3.4.1 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 @openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol@v3.4.1 pragma solidity >=0.6.0 <0.8.0; /** * @dev {ERC20} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC20PresetMinterPauser is Context, AccessControl, ERC20Burnable, ERC20Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor(string memory name, string memory symbol) public ERC20(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } } // File contracts/CentralexToken.sol pragma solidity 0.7.0; contract CentralexToken is ERC20, ERC20Pausable, Ownable, AccessControl { bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); constructor() ERC20("Centralex Token 3.0", "CenX3.0") { _mint(msg.sender, 5 * 1e8 ether); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "CentralexToken2: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "CentralexToken2: must have pauser role to unpause"); _unpause(); } } // File contracts/Staking.sol pragma solidity 0.7.0; /** * @title Compound reward staking * * Note: all percentage values are between 0 (0%) and 1 (100%) * and represented as fixed point numbers containing 18 decimals like with Ether * 100% == 1 ether */ contract Staking is OwnableUpgradeable, ReentrancyGuardUpgradeable, PausableUpgradeable { using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; /** * @dev Emitted when a user deposits tokens. * @param sender User address. * @param id User's unique deposit ID. * @param amount The amount of deposited tokens. * @param userBalance Current user balance. * @param reward User's reward. * @param prevDepositDuration Duration of the previous deposit in seconds. * @param currentRewardFactor Factor to calculate reward. * @param totalStaked Total staked amount. */ event Deposited( address indexed sender, uint256 indexed id, uint256 amount, uint256 userBalance, uint256 reward, uint256 prevDepositDuration, uint256 currentRewardFactor, uint256 totalStaked ); /** * @dev Emitted when a user requests withdrawal. * @param sender User address. * @param id User's unique deposit ID. */ event WithdrawalRequested(address indexed sender, uint256 indexed id); /** * @dev Emitted when deposit and reward are calculated before withdrawal. * @param sender User address. * @param id User's unique deposit ID. * @param deposit Removed deposit. * @param reward Assigned reward. */ event BeforeDepositAndRewardWithdrawn( address indexed sender, uint256 indexed id, uint256 deposit, uint256 reward ); /** * @dev Emitted when a user withdraws tokens. * @param sender User address. * @param id User's unique deposit ID. * @param withdrawalSum The amount of withdrawn tokens. * @param fee The withdrawal fee. * @param balance Current user balance. * @param reward User's reward assigned. * @param lastDepositDuration Duration of the last deposit in seconds. * @param totalStaked Total staked amount updated. * @param totalRemainingReward Total remaining reward which changes after someone withdraws his reward. */ event Withdrawn( address indexed sender, uint256 indexed id, uint256 withdrawalSum, uint256 fee, uint256 balance, uint256 reward, uint256 lastDepositDuration, uint256 totalStaked, uint256 totalRemainingReward ); /** * @dev Emitted when a new fee value is set. * @param value A new fee value. * @param sender The owner address at the moment of fee changing. */ event FeeSet(uint256 value, address sender); /** * @dev Emitted when a new reward distribution set. * @param value A new distribution ration value. * @param sender The owner address at the moment of ratio changing. */ event RewardDistributionSet(uint256 value, address sender); /** * @dev Emitted when a new reward maturity duration set. * @param value A new time in seconds. * @param sender The owner address at the time of changing. */ event RewardMaturityDurationSet(uint256 value, address sender); /** * @dev Emitted when a new withdrawal lock duration value is set. * @param value A new withdrawal lock duration value. * @param sender The owner address at the moment of value changing. */ event WithdrawalLockDurationSet(uint256 value, address sender); /** * @dev Emitted when a new withdrawal unlock duration value is set. * @param value A new withdrawal unlock duration value. * @param sender The owner address at the moment of value changing. */ event WithdrawalUnlockDurationSet(uint256 value, address sender); /** * @dev Emitted when a request to distribute the reward. * @param amount A reward received. */ event RewardDistributed( uint256 amount ); /** * @dev Emitted when a request to distribute the reward. * @param rewardFactor. * @param totalStaked - All staked amount */ event RewardFactorUpdated( uint256 rewardFactor, uint256 totalStaked ); /** * @dev Emitted when reward has been updated. * @param stakersReward - Added stakers reward * @param ownerReward - Added owner reward * @param totalRemainingReward - Total remaining reward which cnanges when reward is accrued and withdrawn * @param totalStakersReward - Total stakers reward value * @param totalOnwerReward - Total onwer reward value */ event RewardUpdated( uint256 stakersReward, uint256 ownerReward, uint256 totalRemainingReward, uint256 totalStakersReward, uint256 totalOnwerReward ); struct UintParam { uint256 oldValue; uint256 newValue; uint256 timestamp; } struct AddressParam { address oldValue; address newValue; uint256 timestamp; } // uint256 constant PPB = 10**9; // Withdrawal fee, in parts per billion. // uint256 constant FEE_RATIO_PPB = 30 * PPB / 1000; // 3.0% // The maximum emission rate (in percentage) // uint256 public constant MAX_EMISSION_RATE = 15 * 1e16 wei; // 15%, 0.15 ether // uint256 private constant YEAR = 365 days; // The period after which the new value of the parameter is set uint256 public constant PARAM_UPDATE_DELAY = 7 days; // The reward factor of the staker(j) = SUM ( reward(j) / SUM(stakes(0->N)) uint256 private currentRewardFactor = 0; // Saves the value of S at the time the participant j makes a deposit. mapping (address => mapping (uint256 => uint256)) public depositRewardFactor; // CenX token CentralexToken public token; // The fee of the forced withdrawal (in percentage) UintParam public feeParam; // The reward distribution (in percentage) fot stakeholders, i.e. 25% for the first year UintParam public rewardSharePercentParam; // The time from the request after which the withdrawal will be available (in seconds) UintParam public withdrawalLockDurationParam; // The time during which the withdrawal will be available from the moment of unlocking (in seconds) UintParam public withdrawalUnlockDurationParam; // The time during which the reward will be available to withdraw only partially depending on the deposit duration (in seconds) UintParam public rewardMaturityDurationParam; /// @notice The deposit balances of users mapping (address => mapping (uint256 => uint256)) public balances; /// @notice The dates of users' deposits mapping (address => mapping (uint256 => uint256)) public depositDates; /// @notice The dates of users' withdrawal requests mapping (address => mapping (uint256 => uint256)) public withdrawalRequestsDates; /// @notice The last deposit id mapping (address => uint256) public lastDepositIds; /// @notice The total staked amount uint256 public totalStaked; /// @notice The total remaining reward. Changes when user withdraws and when reward is distributed to stakeholders. uint256 public totalRemainingReward; /// @notice The total reward received by stakeholders. uint256 public totalStakersReward; /// @notice The total Cetralex reward. To be transfered back to CenX Token or liquidity providers. uint256 public totalOnwerReward; /** * @dev Initializes the contract. * @param _owner The owner of the contract. * @param _tokenAddress The address of the CenX token contract. * @param _fee The fee of the forced withdrawal (in percentage). * @param _withdrawalLockDuration The time from the request after which the withdrawal will be available (in seconds). * @param _withdrawalUnlockDuration The time during which the withdrawal will be available from the moment of unlocking (in seconds). */ function initialize( address _owner, address _tokenAddress, uint256 _fee, uint256 _withdrawalLockDuration, uint256 _withdrawalUnlockDuration, uint256 _rewardMaturityDuration, uint256 _rewardSharePercent ) external initializer { require(_owner != address(0), "zero address"); require(_tokenAddress.isContract(), "not a contract address"); OwnableUpgradeable.__Ownable_init_unchained(); ReentrancyGuardUpgradeable.__ReentrancyGuard_init_unchained(); PausableUpgradeable.__Pausable_init_unchained(); token = CentralexToken(_tokenAddress); setFee(_fee); setWithdrawalLockDuration(_withdrawalLockDuration); setWithdrawalUnlockDuration(_withdrawalUnlockDuration); setRewardMaturityDuration(_rewardMaturityDuration); setRewardSharePercent(_rewardSharePercent); OwnableUpgradeable.transferOwnership(_owner); } /** * @dev This method is used to deposit tokens to a new deposit. * It generates a new deposit ID and calls another public "deposit" method. See its description. * @param _amount The amount to deposit. */ function deposit(uint256 _amount) external whenNotPaused { deposit(++lastDepositIds[msg.sender], _amount); } /** * @dev This method is used to deposit tokens to the deposit opened before. * Sender must approve tokens first. * * Note: each call updates the deposit date so be careful if you want to make a long staking. * * @param _depositId User's unique deposit ID. * @param _amount The amount to deposit. */ function deposit(uint256 _depositId, uint256 _amount) public whenNotPaused nonReentrant { require(_depositId > 0 && _depositId <= lastDepositIds[msg.sender], "deposit: wrong deposit id"); _deposit(msg.sender, _depositId, _amount); require(token.transferFrom(msg.sender, address(this), _amount), "deposit: transfer failed"); } /** * @dev This method is used withdraw tokens from the staking back to owners token account. * Sender must approve tokens first. */ function ownerWithdraw() public whenNotPaused onlyOwner nonReentrant { require(token.transfer(owner(), totalOnwerReward), "_withdraw: transfer failed"); totalOnwerReward = 0; } /** * @dev This method is used to make a forced withdrawal with a fee. * It calls the internal "_withdraw" method. * @param depositId User's unique deposit ID. */ function makeForcedWithdrawal(uint256 depositId) external whenNotPaused nonReentrant { _withdraw(msg.sender, depositId, true); } /** * @dev This method is used to request a withdrawal without a fee. * It sets the date of the request. * * Note: each call updates the date of the request so don't call this method twice during the lock. * * @param _depositId User's unique deposit ID. */ function requestWithdrawal(uint256 _depositId) external whenNotPaused { require(_depositId > 0 && _depositId <= lastDepositIds[msg.sender], "wrong deposit id"); withdrawalRequestsDates[msg.sender][_depositId] = _now(); emit WithdrawalRequested(msg.sender, _depositId); } /** * @dev This method is used to make a requested withdrawal. * It calls the internal "_withdraw" method and resets the date of the request. * If sender didn't call this method during the unlock period (if timestamp >= lockEnd + withdrawalUnlockDuration) * they have to call "requestWithdrawal" one more time. * * @param _depositId User's unique deposit ID. */ function makeRequestedWithdrawal(uint256 _depositId) external whenNotPaused nonReentrant { uint256 requestDate = withdrawalRequestsDates[msg.sender][_depositId]; require(requestDate > 0, "withdrawal wasn't requested"); uint256 timestamp = _now(); uint256 lockEnd = requestDate.add(withdrawalLockDuration()); require(timestamp >= lockEnd, "too early"); require(timestamp < lockEnd.add(withdrawalUnlockDuration()), "too late"); withdrawalRequestsDates[msg.sender][_depositId] = 0; _withdraw(msg.sender, _depositId, false); } /** * @dev Sets the fee for forced withdrawals. Can only be called by owner. * @param _value The new fee value (in percentage). */ function setFee(uint256 _value) public onlyOwner whenNotPaused { require(_value <= 1 ether, "should be less than or equal to 1 ether"); _updateUintParam(feeParam, _value); emit FeeSet(_value, msg.sender); } /** * @dev Sets the fee for forced withdrawals. Can only be called by owner. * @param _value The new fee value (in percentage). */ function setRewardMaturityDuration(uint256 _value) public onlyOwner whenNotPaused { require(_value <= 180 days, "shouldn't be greater than 180 days"); _updateUintParam(rewardMaturityDurationParam, _value); emit RewardMaturityDurationSet(_value, msg.sender); } /** * @dev Sets the reward distribution. Can only be called by owner. * @param _value The new fee value (in percentage). */ function setRewardSharePercent(uint256 _value) public onlyOwner whenNotPaused { require(_value <= 1 ether, "should be less than or equal to 1 ether"); _updateUintParam(rewardSharePercentParam, _value); emit RewardDistributionSet(_value, msg.sender); } /** * @dev Sets the time from the request after which the withdrawal will be available. * Can only be called by owner. * @param _value The new duration value (in seconds). */ function setWithdrawalLockDuration(uint256 _value) public onlyOwner whenNotPaused { require(_value <= 30 days, "shouldn't be greater than 30 days"); _updateUintParam(withdrawalLockDurationParam, _value); emit WithdrawalLockDurationSet(_value, msg.sender); } /** * @dev Sets the time during which the withdrawal will be available from the moment of unlocking. * Can only be called by owner. * @param _value The new duration value (in seconds). */ function setWithdrawalUnlockDuration(uint256 _value) public onlyOwner whenNotPaused { require(_value >= 1 hours, "shouldn't be less than 1 hour"); _updateUintParam(withdrawalUnlockDurationParam, _value); emit WithdrawalUnlockDurationSet(_value, msg.sender); } /** * @dev Returns user total balance. * @param voter The user who votes. * @return Returns User total balance. */ function totalUserBalance(address voter) public view whenNotPaused returns(uint256) { require(voter != address(0), "totalUserBalance: voter address is not valid"); uint256 count = lastDepositIds[voter]; uint256 totalUserStaked = 0; for (uint i = 0; i <= count; i++) { totalUserStaked = totalUserStaked.add(balances[voter][i]); } return totalUserStaked; } /** * @return Returns current fee. */ function fee() public view whenNotPaused returns (uint256) { return _getUintParamValue(feeParam); } /** * @return Returns the current reward distribution. */ function rewardSharePercent() public view whenNotPaused returns (uint256) { return _getUintParamValue(rewardSharePercentParam); } /** * @return Returns current reward maturity duration in seconds. */ function rewardMaturityDuration() public view whenNotPaused returns (uint256) { return _getUintParamValue(rewardMaturityDurationParam); } /** * @return Returns current withdrawal lock duration. */ function withdrawalLockDuration() public view whenNotPaused returns (uint256) { return _getUintParamValue(withdrawalLockDurationParam); } /** * @return Returns current withdrawal unlock duration. */ function withdrawalUnlockDuration() public whenNotPaused view returns (uint256) { return _getUintParamValue(withdrawalUnlockDurationParam); } /** * @dev Reward _amount to be distributed proportionally to active stake. * @param _amount New reward coming into the staking. */ function distribute(uint256 _amount) public whenNotPaused onlyOwner nonReentrant { require(_amount > 0, "distribute: amount must be greater than 0"); _distribute(msg.sender, _amount, false); } /** * @dev Reward _amount to be distributed proportionally to active stake. * @param reward New reward coming into the staking. */ function _distribute(address sender, uint256 reward, bool isFee) internal { emit RewardDistributed(reward); uint256 stakersReward = reward.mul(rewardSharePercent()).div(1 ether); uint256 onwerReward = reward.sub(stakersReward); totalRemainingReward = totalRemainingReward.add(reward); totalStakersReward = totalStakersReward.add(stakersReward); totalOnwerReward = totalOnwerReward.add(onwerReward); emit RewardUpdated(stakersReward, onwerReward, totalRemainingReward, totalStakersReward, totalOnwerReward); if (totalStaked != 0) { // S = S + r / T; currentRewardFactor = currentRewardFactor.add(stakersReward.mul(1 ether).div(totalStaked)); emit RewardFactorUpdated(currentRewardFactor, totalStaked); } if (!isFee){ require(token.transferFrom(sender, address(this), reward), "_distribute: transfer failed"); } } /** * @dev Recalculate balance in case the deposit is already made. * @param _sender The address of the sender. * @param _id User's unique deposit ID. * @param _amount The amount to deposit. */ function _deposit(address _sender, uint256 _id, uint256 _amount) internal { require(_amount > 0, "deposit amount should be more than 0"); uint256 userBalance = balances[_sender][_id]; uint256 deposited = 0; uint256 reward = 0; uint256 timePassed = 0; // Recalculate balances if (userBalance > 0) { (deposited, reward, timePassed) = _withdrawDepositAndReward(_sender, _id); userBalance = _amount.add(deposited).add(reward); } else { userBalance = _amount; } // Assign amount balances[_sender][_id] = userBalance; // Update lastRewardFactor depositRewardFactor[_sender][_id] = currentRewardFactor; // Update total staked totalStaked = totalStaked.add(userBalance); // Update last deposit date depositDates[_sender][_id] = _now(); emit Deposited(_sender, _id, _amount, userBalance, reward, timePassed, currentRewardFactor, totalStaked); } /** * @dev Helper function to withdraw full amount and assign reward. * @param _user The address of the sender. * @param _id User's unique deposit ID. */ function _withdrawDepositAndReward(address _user, uint256 _id) internal returns (uint256 deposited, uint256 reward, uint256 timePassed) { deposited = balances[_user][_id]; uint256 depositTime = depositDates[_user][_id]; timePassed = _now().sub(depositTime); // Formula: reward = deposited * (S - S0[address]); reward = deposited.mul(currentRewardFactor.sub(depositRewardFactor[_user][_id])).div(1 ether); if (timePassed < 1 days) { reward = 0; } else if (timePassed < rewardMaturityDuration()) { reward = rewardMaturityDuration().div(timePassed).mul(reward).sub(reward); } // Finalizing with contract states balances[_user][_id] = 0; totalRemainingReward = totalRemainingReward.sub(reward); totalStaked = totalStaked.sub(deposited); depositDates[_user][_id] = 0; emit BeforeDepositAndRewardWithdrawn(_user, _id, deposited, reward); } /** * @dev Withdraw is possible only in full amount. * @dev Calls internal "_mint" method and then transfers tokens to the sender. * @param _sender The address of the sender. * @param _id User's unique deposit ID. * @param _forced Defines whether to apply fee (true), or not (false). */ function _withdraw(address _sender, uint256 _id, bool _forced) internal { require(_id > 0 && _id <= lastDepositIds[_sender], "wrong deposit id"); require(balances[_sender][_id] > 0, "insufficient funds"); (uint256 deposited, uint256 reward, uint timePassed) = _withdrawDepositAndReward(_sender, _id); uint256 feeValue = 0; if (_forced) { feeValue = deposited.mul(fee()).div(1 ether); deposited = deposited.sub(feeValue); _distribute(_sender, feeValue, true); } uint256 withdrawalSum = deposited.add(reward); require(token.transfer(_sender, withdrawalSum), "_withdraw: transfer failed"); emit Withdrawn(_sender, _id, withdrawalSum, feeValue, balances[_sender][_id], reward, timePassed, totalStaked, totalRemainingReward); } /** * @dev Sets the next value of the parameter and the timestamp of this setting. */ function _updateUintParam(UintParam storage _param, uint256 _newValue) internal { if (_param.timestamp == 0) { _param.oldValue = _newValue; } else if (_paramUpdateDelayElapsed(_param.timestamp)) { _param.oldValue = _param.newValue; } _param.newValue = _newValue; _param.timestamp = _now(); } /** * @return Returns the current value of the parameter. */ function _getUintParamValue(UintParam memory _param) internal view returns (uint256) { return _paramUpdateDelayElapsed(_param.timestamp) ? _param.newValue : _param.oldValue; } /** * @return Returns true if param update delay elapsed. */ function _paramUpdateDelayElapsed(uint256 _paramTimestamp) internal view returns (bool) { return _now() > _paramTimestamp.add(PARAM_UPDATE_DELAY); } /** * @dev Pauses all actions on the contract. * * See {ERC20Pausable} and {Pausable-_pause}. */ function pause() public onlyOwner virtual { _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * */ function unpause() public onlyOwner virtual { _unpause(); } /** * @return Returns current timestamp. */ function _now() internal view returns (uint256) { // Note that the timestamp can have a 900-second error: // https://github.com/ethereum/wiki/blob/c02254611f218f43cbb07517ca8e5d00fd6d6d75/Block-Protocol-2.0.md return block.timestamp; // solium-disable-line security/no-block-members } }
return Returns current withdrawal lock duration./
function withdrawalLockDuration() public view whenNotPaused returns (uint256) { return _getUintParamValue(withdrawalLockDurationParam); }
433,297
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; interface IOwnable { function policy() external view returns (address); function renounceManagement() external; function pushManagement(address newOwner_) external; function pullManagement() external; } contract Ownable is IOwnable { event OwnershipPushed(address indexed previousOwner, address indexed newOwner); event OwnershipPulled(address indexed previousOwner, address indexed newOwner); address internal _owner; address internal _newOwner; constructor() { _owner = msg.sender; emit OwnershipPushed(address(0), _owner); } function policy() public view override returns (address) { return _owner; } modifier onlyPolicy { require(_owner == msg.sender, "Ownable: caller is not the owner" ); _; } function renounceManagement() public virtual override onlyPolicy() { emit OwnershipPushed(_owner, address(0)); _owner = address(0); } function pushManagement(address newOwner_) public virtual override onlyPolicy() { require(newOwner_ != address(0), "Ownable: new owner is the zero address"); emit OwnershipPushed(_owner, newOwner_); _newOwner = newOwner_; } function pullManagement() public virtual override { require(msg.sender == _newOwner, "Ownable: must be new owner to pull"); emit OwnershipPulled(_owner, _newOwner); _owner = _newOwner; } } interface IERC2612Permit { function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function nonces(address owner) external view returns (uint256); } abstract contract ERC20Permit is ERC20, IERC2612Permit { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; bytes32 public DOMAIN_SEPARATOR; constructor() { uint256 chainID; assembly { chainID := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name())), keccak256(bytes("1")), // Version chainID, address(this) ) ); } function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "Permit: expired deadline"); bytes32 hashStruct = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline)); bytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct)); address signer = ecrecover(_hash, v, r, s); require(signer != address(0) && signer == owner, "ZeroSwapPermit: Invalid signature"); _nonces[owner].increment(); _approve(owner, spender, amount); } function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } } library FullMath { function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, ~uint256(0)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & ~d; d /= pow2; l /= pow2; l += h * ((~pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; require(h < d, 'FullMath::mulDiv: overflow'); return fullDiv(l, h, d); } } library FixedPoint { struct uq112x112 { uint224 _x; } struct uq144x112 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = 0x10000000000000000000000000000; uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } function decode112with18(uq112x112 memory self) internal pure returns (uint) { return uint(self._x) / 5192296858534827; } function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= ~uint144(0)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= ~uint224(0), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= ~uint224(0), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } } interface ITreasury { function deposit( uint _amount, address _token, uint _profit ) external; function valueOf( address _token, uint _amount ) external view returns ( uint value_ ); } interface IBondCalculator { function valuation( address _LP, uint _amount ) external view returns ( uint ); function markdown( address _LP ) external view returns ( uint ); } interface IStaking { function stake( uint _amount, address _recipient ) external returns ( bool ); } interface IStakingHelper { function stake( uint _amount, address _recipient ) external; } contract OlympusBondDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( uint indexed payout, uint indexed remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable OHM; // token given as payment for bond address public immutable principle; // token used to create bond, DAI, FRAX etc. address public immutable treasury; // mints OHM when receives principle address public immutable DAO; // receives profit share from bond bool public immutable isLiquidityBond; // LP and Reserve bonds are treated slightly different address public immutable bondCalculator; // calculates value of LP tokens address public staking; // to auto-stake payout address public stakingHelper; // to stake and claim if no staking warmup bool public useHelper; Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data uint public totalDebt; // total value of outstanding bonds; used for pricing uint public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint controlVariable; // scaling variable for price uint vestingTerm; // in blocks uint minimumPrice; // vs principle value uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint fee; // as % of bond payout, in hundreths. ( 500 = 5% = 0.05 for every 1 paid) uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } struct Bond { uint valueRemaining; // value of principle given uint payoutRemaining; // OHM remaining to be paid uint vestingPeriod; // Blocks left to vest uint lastBlock; // Last interaction uint pricePaid; // In DAI, for front end viewing } mapping(address => Bond) public bondInfo; // Stores bond information for depositor // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint buffer; // minimum length (in blocks) between adjustments uint lastBlock; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _OHM, address _principle, address _treasury, address _DAO, address _bondCalculator ) { require(_OHM != address(0)); OHM = _OHM; require(_principle != address(0)); principle = _principle; require(_treasury != address(0)); treasury = _treasury; require(_DAO != address(0)); DAO = _DAO; // bondCalculator should be address(0) if not LP bond bondCalculator = _bondCalculator; isLiquidityBond = (_bondCalculator != address(0)); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _fee uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms( uint _controlVariable, uint _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _fee, uint _maxDebt, uint _initialDebt ) external onlyPolicy() { require(terms.controlVariable == 0, "Bonds must be initialized from 0" ); terms = Terms({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, fee: _fee, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = block.number; } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER {VESTING, PAYOUT, FEE, DEBT} /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms(PARAMETER _parameter, uint _input) external onlyPolicy() { if (_parameter == PARAMETER.VESTING) { // 0 require(_input >= 10000, "Vesting must be longer than 36 hours"); terms.vestingTerm = _input; } else if (_parameter == PARAMETER.PAYOUT) { // 1 require(_input <= 1000, "Payout cannot be above 1 percent"); terms.maxPayout = _input; } else if (_parameter == PARAMETER.FEE) { // 2 require(_input <= 10000, "DAO fee cannot exceed payout"); terms.fee = _input; } else if (_parameter == PARAMETER.DEBT) { // 3 terms.maxDebt = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint _buffer ) external onlyPolicy() { require(_increment <= terms.controlVariable * 25 / 1000, "Increment too large"); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastBlock: block.number }); } /** * @notice set contract for auto stake * @param _staking address * @param _helper bool */ function setStaking(address _staking, bool _helper) external onlyPolicy() { require(_staking != address(0)); if (_helper) { useHelper = true; stakingHelper = _staking; } else { useHelper = false; staking = _staking; } } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor ) external returns (uint) { require(_depositor != address(0), "Invalid address"); decayDebt(); require(totalDebt <= terms.maxDebt, "Max capacity reached"); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require(_maxPrice >= nativePrice, "Slippage limit: more than max price"); // slippage protection uint value; if (isLiquidityBond) { // LP is calculated at risk-free value value = IBondCalculator(bondCalculator).valuation(principle, _amount); } else { // reserve is converted to OHM decimals value = _amount * 10**IERC20Metadata(OHM).decimals() / 10**IERC20Metadata(principle).decimals(); } uint payout = payoutFor(value); // payout to bonder is computed require(payout >= 10000000, "Bond too small"); // must be > 0.01 OHM ( underflow protection ) require(payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage // profits are calculated uint fee = payout * terms.fee / 10000; uint profit = value - payout - fee; /** principle is transferred in approved and deposited into the treasury, returning (_amount - profit) OHM */ // IERC20(principle).safeTransferFrom(msg.sender, address(this), _amount); // IERC20(principle).approve(address(treasury), _amount); // ITreasury(treasury).deposit(_amount, principle, profit); IERC20(principle).safeTransferFrom(msg.sender, treasury, _amount); // IERC20(principle).approve(address(treasury), _amount); ITreasury(treasury).deposit(_amount, principle, profit); IERC20(OHM).safeTransfer(DAO, fee); // total debt is increased totalDebt = totalDebt + value; // depositor info is stored Bond memory info = bondInfo[_depositor]; bondInfo[_depositor] = Bond({ valueRemaining: info.valueRemaining + value, // add on to previous payoutRemaining: info.payoutRemaining + payout, // amounts if they exist vestingPeriod: terms.vestingTerm, lastBlock: block.number, pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated(_amount, payout, block.number + terms.vestingTerm, priceInUSD); emit BondPriceChanged(bondPriceInUSD(), _bondPrice(), debtRatio()); adjust(); // control variable is adjusted return payout; } /** @notice redeem all unvested bonds @param _stake bool @return payout_ uint */ function redeem(bool _stake) external returns (uint) { Bond memory info = bondInfo[msg.sender]; uint percentVested = percentVestedFor(msg.sender); // (blocks since last interaction / vesting term remaining) if (percentVested >= 10000) { // if fully vested delete bondInfo[msg.sender]; // delete user info totalDebt -= info.valueRemaining; // reduce debt // emit BondRedeemed(info.payoutRemaining, 0); // emit bond data return stakeOrSend(_stake, info.payoutRemaining); // pay user everything due } else { // if unfinished // calculate payout vested uint value = info.valueRemaining * percentVested / 10000; uint payout = info.payoutRemaining * percentVested / 10000; uint blocksSinceLast = block.number - info.lastBlock; // store updated deposit info bondInfo[msg.sender] = Bond({ valueRemaining: info.valueRemaining - value, payoutRemaining: info.payoutRemaining - payout, vestingPeriod: info.vestingPeriod - blocksSinceLast, lastBlock: block.number, pricePaid: info.pricePaid }); // reduce total debt by vested amount totalDebt -= value; emit BondRedeemed(payout, bondInfo[msg.sender].payoutRemaining); return stakeOrSend(_stake, payout); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** @notice allow user to stake payout automatically @param _stake bool @param _amount uint @return uint */ function stakeOrSend(bool _stake, uint _amount) internal returns (uint) { emit BondPriceChanged(bondPriceInUSD(), _bondPrice(), debtRatio()); if (!_stake ) { // if user does not want to stake IERC20(OHM).transfer(msg.sender, _amount); // send payout } else { // if user wants to stake IERC20(OHM).approve(staking, _amount); IStaking(staking).stake(_amount, msg.sender); // stake payout } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint blockCanAdjust = adjustment.lastBlock + adjustment.buffer; if (adjustment.rate != 0 && block.number >= blockCanAdjust) { uint initial = terms.controlVariable; if (adjustment.add) { terms.controlVariable = terms.controlVariable + adjustment.rate; if (terms.controlVariable >= adjustment.target) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable - adjustment.rate; if (terms.controlVariable <= adjustment.target) { adjustment.rate = 0; } } adjustment.lastBlock = block.number; emit ControlVariableAdjustment(initial, terms.controlVariable, adjustment.rate, adjustment.add); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt - debtDecay(); lastDecay = block.number; } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns (uint) { return IERC20(OHM).totalSupply() * terms.maxPayout / 100000; } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor(uint _value) public view returns (uint) { return FixedPoint.fraction(_value, bondPrice()).decode112with18() / 1e16; } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns (uint price_) { price_ = (terms.controlVariable * debtRatio() + 1000000000) / 1e7; if (price_ < terms.minimumPrice) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns (uint price_) { price_ = (terms.controlVariable * debtRatio() + 1000000000)/1e7; if (price_ < terms.minimumPrice) { price_ = terms.minimumPrice; } else if (terms.minimumPrice != 0) { terms.minimumPrice = 0; } } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns (uint price_) { if (isLiquidityBond) { price_ = bondPrice() * IBondCalculator(bondCalculator).markdown(principle) / 100; } else { price_ = bondPrice() * 10**IERC20Metadata(principle).decimals() / 100; } } /** * @notice calculate current ratio of debt to OHM supply * @return debtRatio_ uint */ function debtRatio() public view returns (uint debtRatio_) { uint supply = IERC20(OHM).totalSupply(); debtRatio_ = FixedPoint.fraction(currentDebt() * 1e9, supply).decode112with18() / 1e18; } /** * @notice debt ratio in same terms for reserve or liquidity bonds * @return uint */ function standardizedDebtRatio() external view returns (uint) { if (isLiquidityBond) { return debtRatio() * (IBondCalculator(bondCalculator).markdown(principle)) / 1e9; } else { return debtRatio(); } } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns (uint) { return totalDebt - debtDecay(); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns (uint decay_) { uint blocksSinceLast = block.number - lastDecay; decay_ = totalDebt * blocksSinceLast / terms.vestingTerm; if (decay_ > totalDebt) { decay_ = totalDebt; } } /** @notice calculate how far into vesting a depositor is @param _depositor address @return percentVested_ uint */ function percentVestedFor(address _depositor) public view returns (uint percentVested_) { Bond memory bond = bondInfo[_depositor]; uint blocksSinceLast = block.number - bond.lastBlock; uint vestingPeriod = bond.vestingPeriod; if (vestingPeriod > 0) { percentVested_ = blocksSinceLast * 10000 / vestingPeriod; } else { percentVested_ = 0; } } /** @notice calculate amount of OHM available for claim by depositor @param _depositor address @return pendingPayout_ uint */ function pendingPayoutFor(address _depositor) external view returns (uint pendingPayout_) { uint percentVested = percentVestedFor(_depositor); uint payoutRemaining = bondInfo[_depositor].payoutRemaining; if (percentVested >= 10000) { pendingPayout_ = payoutRemaining; } else { pendingPayout_ = payoutRemaining * percentVested / 10000; } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or OHM) to the DAO * @return bool */ function recoverLostToken(address _token) external returns (bool) { require(_token != OHM); require(_token != principle); IERC20(_token).safeTransfer(DAO, IERC20(_token).balanceOf(address(this))); return true; } }
calculate current bond premium return price_ uint/
function bondPrice() public view returns (uint price_) { price_ = (terms.controlVariable * debtRatio() + 1000000000) / 1e7; if (price_ < terms.minimumPrice) { price_ = terms.minimumPrice; } }
1,040,923
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "./interfaces/IPoolTokensContainer.sol"; import "../../../utility/Owned.sol"; import "../../../utility/TokenHolder.sol"; import "../../../token/SmartToken.sol"; /** * @dev The PoolTokensContainer contract serves as a container for multiple pool tokens. * It is used by specific liquidity pool types that require more than a single pool token, * while still maintaining the single converter / anchor relationship. * * It maintains and provides a list of the underlying pool tokens. */ contract PoolTokensContainer is IPoolTokensContainer, Owned, TokenHolder { uint8 internal constant MAX_POOL_TOKENS = 5; // maximum pool tokens in the container string public name; // pool name string public symbol; // pool symbol uint8 public decimals; // underlying pool tokens decimals ISmartToken[] private _poolTokens; // underlying pool tokens /** * @dev initializes a new PoolTokensContainer instance * * @param _name pool name, also used as a prefix for the underlying pool token names * @param _symbol pool symbol, also used as a prefix for the underlying pool token symbols * @param _decimals used for the underlying pool token decimals */ constructor(string memory _name, string memory _symbol, uint8 _decimals) public { // validate input require(bytes(_name).length > 0, "ERR_INVALID_NAME"); require(bytes(_symbol).length > 0, "ERR_INVALID_SYMBOL"); name = _name; symbol = _symbol; decimals = _decimals; } /** * @dev returns the list of pool tokens * * @return list of pool tokens */ function poolTokens() external view override returns (ISmartToken[] memory) { return _poolTokens; } /** * @dev creates a new pool token and adds it to the list * * @return new pool token address */ function createToken() external override ownerOnly returns (ISmartToken) { // verify that the max limit wasn't reached require(_poolTokens.length < MAX_POOL_TOKENS, "ERR_MAX_LIMIT_REACHED"); string memory poolName = concatStrDigit(name, uint8(_poolTokens.length + 1)); string memory poolSymbol = concatStrDigit(symbol, uint8(_poolTokens.length + 1)); SmartToken token = new SmartToken(poolName, poolSymbol, decimals); _poolTokens.push(token); return token; } /** * @dev increases the pool token supply and sends the new tokens to the given account * can only be called by the contract owner * * @param _token pool token address * @param _to account to receive the newly minted tokens * @param _amount amount to mint */ function mint(ISmartToken _token, address _to, uint256 _amount) external override ownerOnly { _token.issue(_to, _amount); } /** * @dev removes tokens from the given account and decreases the pool token supply * can only be called by the contract owner * * @param _token pool token address * @param _from account to remove the tokens from * @param _amount amount to burn */ function burn(ISmartToken _token, address _from, uint256 _amount) external override ownerOnly { _token.destroy(_from, _amount); } /** * @dev concatenates a string and a digit (single only) and returns the result string * * @param _str string * @param _digit digit * @return concatenated string */ function concatStrDigit(string memory _str, uint8 _digit) private pure returns (string memory) { return string(abi.encodePacked(_str, uint8(bytes1('0')) + _digit)); } }
concatenates a string and a digit (single only) and returns the result string _str string _digit digit return concatenated string/
function concatStrDigit(string memory _str, uint8 _digit) private pure returns (string memory) { return string(abi.encodePacked(_str, uint8(bytes1('0')) + _digit)); }
12,855,218
./full_match/1/0xF1C7b9A188C071d397ef55440A028321D6D780A0/sources/contracts/BountyV2.sol
Sets a new minimum bounty newMinBounty The new minimum bounty
function setMinBounty(uint256 newMinBounty) external onlyOwner { _minBounty = newMinBounty; }
3,024,021
/** *Submitted for verification at Etherscan.io on 2021-03-09 */ /** *Submitted for verification at Etherscan.io on 2021-02-22 */ // File @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected] /* https://github.com/OpenZeppelin/openzeppelin-contracts The MIT License (MIT) Copyright (c) 2016-2019 zOS Global Limited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // SPDX-License-Identifier: MIT pragma solidity 0.6.8; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @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 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); } // File @animoca/ethereum-contracts-core_library/contracts/algo/[email protected] /* https://github.com/OpenZeppelin/openzeppelin-contracts The MIT License (MIT) Copyright (c) 2016-2019 zOS Global Limited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity 0.6.8; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumMap for EnumMap.Map; * * // Declare a set state variable * EnumMap.Map private myMap; * } * ``` */ library EnumMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // This means that we can only create new EnumMaps for types that fit // in bytes32. struct MapEntry { bytes32 key; bytes32 value; } struct Map { // Storage of map keys and values MapEntry[] entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(Map storage map, bytes32 key, bytes32 value) internal returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map.indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map.entries.push(MapEntry({ key: key, value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map.indexes[key] = map.entries.length; return true; } else { map.entries[keyIndex - 1].value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(Map storage map, bytes32 key) internal returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map.indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map.entries.length - 1; // When the entry 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. MapEntry storage lastEntry = map.entries[lastIndex]; // Move the last entry to the index where the entry to delete is map.entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map.indexes[lastEntry.key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map.entries.pop(); // Delete the index for the deleted slot delete map.indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function contains(Map storage map, bytes32 key) internal view returns (bool) { return map.indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function length(Map storage map) internal view returns (uint256) { return map.entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Map storage map, uint256 index) internal view returns (bytes32, bytes32) { require(map.entries.length > index, "EnumMap: index out of bounds"); MapEntry storage entry = map.entries[index]; return (entry.key, entry.value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(Map storage map, bytes32 key) internal view returns (bytes32) { uint256 keyIndex = map.indexes[key]; require(keyIndex != 0, "EnumMap: nonexistent key"); // Equivalent to contains(map, key) return map.entries[keyIndex - 1].value; // All indexes are 1-based } } // File @animoca/ethereum-contracts-core_library/contracts/algo/[email protected] /* https://github.com/OpenZeppelin/openzeppelin-contracts The MIT License (MIT) Copyright (c) 2016-2019 zOS Global Limited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity 0.6.8; /** * @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 EnumSet for EnumSet.Set; * * // Declare a set state variable * EnumSet.Set private mySet; * } * ``` */ library EnumSet { // 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. // 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) internal 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) internal 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) internal view returns (bool) { return set.indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function length(Set storage set) internal 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) internal view returns (bytes32) { require(set.values.length > index, "EnumSet: index out of bounds"); return set.values[index]; } } // File @openzeppelin/contracts/GSN/[email protected] pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File @animoca/ethereum-contracts-core_library/contracts/payment/[email protected] pragma solidity 0.6.8; /** @title PayoutWallet @dev adds support for a payout wallet Note: . */ contract PayoutWallet is Ownable { event PayoutWalletSet(address payoutWallet_); address payable public payoutWallet; constructor(address payoutWallet_) internal { setPayoutWallet(payoutWallet_); } function setPayoutWallet(address payoutWallet_) public onlyOwner { require(payoutWallet_ != address(0), "The payout wallet must not be the zero address"); require(payoutWallet_ != address(this), "The payout wallet must not be the contract itself"); require(payoutWallet_ != payoutWallet, "The payout wallet must be different"); payoutWallet = payable(payoutWallet_); emit PayoutWalletSet(payoutWallet); } } // File @animoca/ethereum-contracts-core_library/contracts/utils/[email protected] pragma solidity 0.6.8; /** * Contract module which allows derived contracts to implement a mechanism for * activating, or 'starting', a contract. * * This module is used through inheritance. It will make available the modifiers * `whenNotStarted` and `whenStarted`, which can be applied to the functions of * your contract. Those functions will only be 'startable' once the modifiers * are put in place. */ contract Startable is Context { event Started(address account); uint256 private _startedAt; /** * Modifier to make a function callable only when the contract has not started. */ modifier whenNotStarted() { require(_startedAt == 0, "Startable: started"); _; } /** * Modifier to make a function callable only when the contract has started. */ modifier whenStarted() { require(_startedAt != 0, "Startable: not started"); _; } /** * Constructor. */ constructor () internal {} /** * Returns the timestamp when the contract entered the started state. * @return The timestamp when the contract entered the started state. */ function startedAt() public view returns (uint256) { return _startedAt; } /** * Triggers the started state. * @dev Emits the Started event when the function is successfully called. */ function _start() internal virtual whenNotStarted { _startedAt = now; emit Started(_msgSender()); } } // File @openzeppelin/contracts/utils/Pau[email protected] pragma solidity ^0.6.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/math/[email protected] pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File @animoca/ethereum-contracts-sale_base/contracts/sale/interfaces/[email protected] pragma solidity 0.6.8; /** * @title ISale * * An interface for a contract which allows merchants to display products and customers to purchase them. * * Products, designated as SKUs, are represented by bytes32 identifiers so that an identifier can carry an * explicit name under the form of a fixed-length string. Each SKU can be priced via up to several payment * tokens which can be ETH and/or ERC20(s). ETH token is represented by the magic value TOKEN_ETH, which means * this value can be used as the 'token' argument of the purchase-related functions to indicate ETH payment. * * The total available supply for a SKU is fixed at its creation. The magic value SUPPLY_UNLIMITED is used * to represent a SKU with an infinite, never-decreasing supply. An optional purchase notifications receiver * contract address can be set for a SKU at its creation: if the value is different from the zero address, * the function `onPurchaseNotificationReceived` will be called on this address upon every purchase of the SKU. * * This interface is designed to be consistent while managing a variety of implementation scenarios. It is * also intended to be developer-friendly: all vital information is consistently deductible from the events * (backend-oriented), as well as retrievable through calls to public functions (frontend-oriented). */ interface ISale { /** * Event emitted to notify about the magic values necessary for interfacing with this contract. * @param names An array of names for the magic values used by the contract. * @param values An array of values for the magic values used by the contract. */ event MagicValues(bytes32[] names, bytes32[] values); /** * Event emitted to notify about the creation of a SKU. * @param sku The identifier of the created SKU. * @param totalSupply The initial total supply for sale. * @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase. * @param notificationsReceiver If not the zero address, the address of a contract on which `onPurchaseNotificationReceived` will be called after * each purchase. If this is the zero address, the call is not enabled. */ event SkuCreation(bytes32 sku, uint256 totalSupply, uint256 maxQuantityPerPurchase, address notificationsReceiver); /** * Event emitted to notify about a change in the pricing of a SKU. * @dev `tokens` and `prices` arrays MUST have the same length. * @param sku The identifier of the updated SKU. * @param tokens An array of updated payment tokens. If empty, interpret as all payment tokens being disabled. * @param prices An array of updated prices for each of the payment tokens. * Zero price values are used for payment tokens being disabled. */ event SkuPricingUpdate(bytes32 indexed sku, address[] tokens, uint256[] prices); /** * Event emitted to notify about a purchase. * @param purchaser The initiater and buyer of the purchase. * @param recipient The recipient of the purchase. * @param token The token used as the currency for the payment. * @param sku The identifier of the purchased SKU. * @param quantity The purchased quantity. * @param userData Optional extra user input data. * @param totalPrice The amount of `token` paid. * @param extData Implementation-specific extra purchase data, such as * details about discounts applied, conversion rates, purchase receipts, etc. */ event Purchase( address indexed purchaser, address recipient, address indexed token, bytes32 indexed sku, uint256 quantity, bytes userData, uint256 totalPrice, bytes extData ); /** * Returns the magic value used to represent the ETH payment token. * @dev MUST NOT be the zero address. * @return the magic value used to represent the ETH payment token. */ // solhint-disable-next-line func-name-mixedcase function TOKEN_ETH() external pure returns (address); /** * Returns the magic value used to represent an infinite, never-decreasing SKU's supply. * @dev MUST NOT be zero. * @return the magic value used to represent an infinite, never-decreasing SKU's supply. */ // solhint-disable-next-line func-name-mixedcase function SUPPLY_UNLIMITED() external pure returns (uint256); /** * Performs a purchase. * @dev Reverts if `recipient` is the zero address. * @dev Reverts if `token` is the address zero. * @dev Reverts if `quantity` is zero. * @dev Reverts if `quantity` is greater than the maximum purchase quantity. * @dev Reverts if `quantity` is greater than the remaining supply. * @dev Reverts if `sku` does not exist. * @dev Reverts if `sku` exists but does not have a price set for `token`. * @dev Emits the Purchase event. * @param recipient The recipient of the purchase. * @param token The token to use as the payment currency. * @param sku The identifier of the SKU to purchase. * @param quantity The quantity to purchase. * @param userData Optional extra user input data. */ function purchaseFor( address payable recipient, address token, bytes32 sku, uint256 quantity, bytes calldata userData ) external payable; /** * Estimates the computed final total amount to pay for a purchase, including any potential discount. * @dev This function MUST compute the same price as `purchaseFor` would in identical conditions (same arguments, same point in time). * @dev If an implementer contract uses the `pricingData` field, it SHOULD document how to interpret the values. * @dev Reverts if `recipient` is the zero address. * @dev Reverts if `token` is the zero address. * @dev Reverts if `quantity` is zero. * @dev Reverts if `quantity` is greater than the maximum purchase quantity. * @dev Reverts if `quantity` is greater than the remaining supply. * @dev Reverts if `sku` does not exist. * @dev Reverts if `sku` exists but does not have a price set for `token`. * @param recipient The recipient of the purchase used to calculate the total price amount. * @param token The payment token used to calculate the total price amount. * @param sku The identifier of the SKU used to calculate the total price amount. * @param quantity The quantity used to calculate the total price amount. * @param userData Optional extra user input data. * @return totalPrice The computed total price to pay. * @return pricingData Implementation-specific extra pricing data, such as details about discounts applied. * If not empty, the implementer MUST document how to interepret the values. */ function estimatePurchase( address payable recipient, address token, bytes32 sku, uint256 quantity, bytes calldata userData ) external view returns (uint256 totalPrice, bytes32[] memory pricingData); /** * Returns the information relative to a SKU. * @dev WARNING: it is the responsibility of the implementer to ensure that the * number of payment tokens is bounded, so that this function does not run out of gas. * @dev Reverts if `sku` does not exist. * @param sku The SKU identifier. * @return totalSupply The initial total supply for sale. * @return remainingSupply The remaining supply for sale. * @return maxQuantityPerPurchase The maximum allowed quantity for a single purchase. * @return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function. * @return tokens The list of supported payment tokens. * @return prices The list of associated prices for each of the `tokens`. */ function getSkuInfo(bytes32 sku) external view returns ( uint256 totalSupply, uint256 remainingSupply, uint256 maxQuantityPerPurchase, address notificationsReceiver, address[] memory tokens, uint256[] memory prices ); /** * Returns the list of created SKU identifiers. * @dev WARNING: it is the responsibility of the implementer to ensure that the * number of SKUs is bounded, so that this function does not run out of gas. * @return skus the list of created SKU identifiers. */ function getSkus() external view returns (bytes32[] memory skus); } // File @animoca/ethereum-contracts-sale_base/contracts/sale/interfaces/[email protected] pragma solidity 0.6.8; /** * @title IPurchaseNotificationsReceiver * Interface for any contract that wants to support purchase notifications from a Sale contract. */ interface IPurchaseNotificationsReceiver { /** * Handles the receipt of a purchase notification. * @dev This function MUST return the function selector, otherwise the caller will revert the transaction. * The selector to be returned can be obtained as `this.onPurchaseNotificationReceived.selector` * @dev This function MAY throw. * @param purchaser The purchaser of the purchase. * @param recipient The recipient of the purchase. * @param token The token to use as the payment currency. * @param sku The identifier of the SKU to purchase. * @param quantity The quantity to purchase. * @param userData Optional extra user input data. * @param totalPrice The total price paid. * @param pricingData Implementation-specific extra pricing data, such as details about discounts applied. * @param paymentData Implementation-specific extra payment data, such as conversion rates. * @param deliveryData Implementation-specific extra delivery data, such as purchase receipts. * @return `bytes4(keccak256( * "onPurchaseNotificationReceived(address,address,address,bytes32,uint256,bytes,uint256,bytes32[],bytes32[],bytes32[])"))` */ function onPurchaseNotificationReceived( address purchaser, address recipient, address token, bytes32 sku, uint256 quantity, bytes calldata userData, uint256 totalPrice, bytes32[] calldata pricingData, bytes32[] calldata paymentData, bytes32[] calldata deliveryData ) external returns (bytes4); } // File @animoca/ethereum-contracts-sale_base/contracts/sale/abstract/[email protected] pragma solidity 0.6.8; /** * @title PurchaseLifeCycles * An abstract contract which define the life cycles for a purchase implementer. */ abstract contract PurchaseLifeCycles { /** * Wrapper for the purchase data passed as argument to the life cycle functions and down to their step functions. */ struct PurchaseData { address payable purchaser; address payable recipient; address token; bytes32 sku; uint256 quantity; bytes userData; uint256 totalPrice; bytes32[] pricingData; bytes32[] paymentData; bytes32[] deliveryData; } /* Internal Life Cycle Functions */ /** * `estimatePurchase` lifecycle. * @param purchase The purchase conditions. */ function _estimatePurchase(PurchaseData memory purchase) internal view virtual returns (uint256 totalPrice, bytes32[] memory pricingData) { _validation(purchase); _pricing(purchase); totalPrice = purchase.totalPrice; pricingData = purchase.pricingData; } /** * `purchaseFor` lifecycle. * @param purchase The purchase conditions. */ function _purchaseFor(PurchaseData memory purchase) internal virtual { _validation(purchase); _pricing(purchase); _payment(purchase); _delivery(purchase); _notification(purchase); } /* Internal Life Cycle Step Functions */ /** * Lifecycle step which validates the purchase pre-conditions. * @dev Responsibilities: * - Ensure that the purchase pre-conditions are met and revert if not. * @param purchase The purchase conditions. */ function _validation(PurchaseData memory purchase) internal view virtual; /** * Lifecycle step which computes the purchase price. * @dev Responsibilities: * - Computes the pricing formula, including any discount logic and price conversion; * - Set the value of `purchase.totalPrice`; * - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it. * @param purchase The purchase conditions. */ function _pricing(PurchaseData memory purchase) internal view virtual; /** * Lifecycle step which manages the transfer of funds from the purchaser. * @dev Responsibilities: * - Ensure the payment reaches destination in the expected output token; * - Handle any token swap logic; * - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it. * @param purchase The purchase conditions. */ function _payment(PurchaseData memory purchase) internal virtual; /** * Lifecycle step which delivers the purchased SKUs to the recipient. * @dev Responsibilities: * - Ensure the product is delivered to the recipient, if that is the contract's responsibility. * - Handle any internal logic related to the delivery, including the remaining supply update; * - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it. * @param purchase The purchase conditions. */ function _delivery(PurchaseData memory purchase) internal virtual; /** * Lifecycle step which notifies of the purchase. * @dev Responsibilities: * - Manage after-purchase event(s) emission. * - Handle calls to the notifications receiver contract's `onPurchaseNotificationReceived` function, if applicable. * @param purchase The purchase conditions. */ function _notification(PurchaseData memory purchase) internal virtual; } // File @animoca/ethereum-contracts-sale_base/contracts/sale/abstract/[email protected] pragma solidity 0.6.8; /** * @title Sale * An abstract base sale contract with a minimal implementation of ISale and administration functions. * A minimal implementation of the `_validation`, `_delivery` and `notification` life cycle step functions * are provided, but the inheriting contract must implement `_pricing` and `_payment`. */ abstract contract Sale is PurchaseLifeCycles, ISale, PayoutWallet, Startable, Pausable { using Address for address; using SafeMath for uint256; using EnumSet for EnumSet.Set; using EnumMap for EnumMap.Map; struct SkuInfo { uint256 totalSupply; uint256 remainingSupply; uint256 maxQuantityPerPurchase; address notificationsReceiver; EnumMap.Map prices; } address public constant override TOKEN_ETH = address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); uint256 public constant override SUPPLY_UNLIMITED = type(uint256).max; EnumSet.Set internal _skus; mapping(bytes32 => SkuInfo) internal _skuInfos; uint256 internal immutable _skusCapacity; uint256 internal immutable _tokensPerSkuCapacity; /** * Constructor. * @dev Emits the `MagicValues` event. * @dev Emits the `Paused` event. * @param payoutWallet_ the payout wallet. * @param skusCapacity the cap for the number of managed SKUs. * @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU. */ constructor( address payoutWallet_, uint256 skusCapacity, uint256 tokensPerSkuCapacity ) internal PayoutWallet(payoutWallet_) { _skusCapacity = skusCapacity; _tokensPerSkuCapacity = tokensPerSkuCapacity; bytes32[] memory names = new bytes32[](2); bytes32[] memory values = new bytes32[](2); (names[0], values[0]) = ("TOKEN_ETH", bytes32(uint256(TOKEN_ETH))); (names[1], values[1]) = ("SUPPLY_UNLIMITED", bytes32(uint256(SUPPLY_UNLIMITED))); emit MagicValues(names, values); _pause(); } /* Public Admin Functions */ /** * Actvates, or 'starts', the contract. * @dev Emits the `Started` event. * @dev Emits the `Unpaused` event. * @dev Reverts if called by any other than the contract owner. * @dev Reverts if the contract has already been started. * @dev Reverts if the contract is not paused. */ function start() public virtual onlyOwner { _start(); _unpause(); } /** * Pauses the contract. * @dev Emits the `Paused` event. * @dev Reverts if called by any other than the contract owner. * @dev Reverts if the contract has not been started yet. * @dev Reverts if the contract is already paused. */ function pause() public virtual onlyOwner whenStarted { _pause(); } /** * Resumes the contract. * @dev Emits the `Unpaused` event. * @dev Reverts if called by any other than the contract owner. * @dev Reverts if the contract has not been started yet. * @dev Reverts if the contract is not paused. */ function unpause() public virtual onlyOwner whenStarted { _unpause(); } /** * Sets the token prices for the specified product SKU. * @dev Reverts if called by any other than the contract owner. * @dev Reverts if `tokens` and `prices` have different lengths. * @dev Reverts if `sku` does not exist. * @dev Reverts if one of the `tokens` is the zero address. * @dev Reverts if the update results in too many tokens for the SKU. * @dev Emits the `SkuPricingUpdate` event. * @param sku The identifier of the SKU. * @param tokens The list of payment tokens to update. * If empty, disable all the existing payment tokens. * @param prices The list of prices to apply for each payment token. * Zero price values are used to disable a payment token. */ function updateSkuPricing( bytes32 sku, address[] memory tokens, uint256[] memory prices ) public virtual onlyOwner { uint256 length = tokens.length; // solhint-disable-next-line reason-string require(length == prices.length, "Sale: tokens/prices lengths mismatch"); SkuInfo storage skuInfo = _skuInfos[sku]; require(skuInfo.totalSupply != 0, "Sale: non-existent sku"); EnumMap.Map storage tokenPrices = skuInfo.prices; if (length == 0) { uint256 currentLength = tokenPrices.length(); for (uint256 i = 0; i < currentLength; ++i) { // TODO add a clear function in EnumMap and EnumSet and use it (bytes32 token, ) = tokenPrices.at(0); tokenPrices.remove(token); } } else { _setTokenPrices(tokenPrices, tokens, prices); } emit SkuPricingUpdate(sku, tokens, prices); } /* ISale Public Functions */ /** * Performs a purchase. * @dev Reverts if the sale has not started. * @dev Reverts if the sale is paused. * @dev Reverts if `recipient` is the zero address. * @dev Reverts if `token` is the zero address. * @dev Reverts if `quantity` is zero. * @dev Reverts if `quantity` is greater than the maximum purchase quantity. * @dev Reverts if `quantity` is greater than the remaining supply. * @dev Reverts if `sku` does not exist. * @dev Reverts if `sku` exists but does not have a price set for `token`. * @dev Emits the Purchase event. * @param recipient The recipient of the purchase. * @param token The token to use as the payment currency. * @param sku The identifier of the SKU to purchase. * @param quantity The quantity to purchase. * @param userData Optional extra user input data. */ function purchaseFor( address payable recipient, address token, bytes32 sku, uint256 quantity, bytes calldata userData ) external payable virtual override whenStarted whenNotPaused { PurchaseData memory purchase; purchase.purchaser = _msgSender(); purchase.recipient = recipient; purchase.token = token; purchase.sku = sku; purchase.quantity = quantity; purchase.userData = userData; _purchaseFor(purchase); } /** * Estimates the computed final total amount to pay for a purchase, including any potential discount. * @dev This function MUST compute the same price as `purchaseFor` would in identical conditions (same arguments, same point in time). * @dev If an implementer contract uses the `pricingData` field, it SHOULD document how to interpret the values. * @dev Reverts if the sale has not started. * @dev Reverts if the sale is paused. * @dev Reverts if `recipient` is the zero address. * @dev Reverts if `token` is the zero address. * @dev Reverts if `quantity` is zero. * @dev Reverts if `quantity` is greater than the maximum purchase quantity. * @dev Reverts if `quantity` is greater than the remaining supply. * @dev Reverts if `sku` does not exist. * @dev Reverts if `sku` exists but does not have a price set for `token`. * @param recipient The recipient of the purchase used to calculate the total price amount. * @param token The payment token used to calculate the total price amount. * @param sku The identifier of the SKU used to calculate the total price amount. * @param quantity The quantity used to calculate the total price amount. * @param userData Optional extra user input data. * @return totalPrice The computed total price. * @return pricingData Implementation-specific extra pricing data, such as details about discounts applied. * If not empty, the implementer MUST document how to interepret the values. */ function estimatePurchase( address payable recipient, address token, bytes32 sku, uint256 quantity, bytes calldata userData ) external view virtual override whenStarted whenNotPaused returns (uint256 totalPrice, bytes32[] memory pricingData) { PurchaseData memory purchase; purchase.purchaser = _msgSender(); purchase.recipient = recipient; purchase.token = token; purchase.sku = sku; purchase.quantity = quantity; purchase.userData = userData; return _estimatePurchase(purchase); } /** * Returns the information relative to a SKU. * @dev WARNING: it is the responsibility of the implementer to ensure that the * number of payment tokens is bounded, so that this function does not run out of gas. * @dev Reverts if `sku` does not exist. * @param sku The SKU identifier. * @return totalSupply The initial total supply for sale. * @return remainingSupply The remaining supply for sale. * @return maxQuantityPerPurchase The maximum allowed quantity for a single purchase. * @return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function. * @return tokens The list of supported payment tokens. * @return prices The list of associated prices for each of the `tokens`. */ function getSkuInfo(bytes32 sku) external view override returns ( uint256 totalSupply, uint256 remainingSupply, uint256 maxQuantityPerPurchase, address notificationsReceiver, address[] memory tokens, uint256[] memory prices ) { SkuInfo storage skuInfo = _skuInfos[sku]; uint256 length = skuInfo.prices.length(); totalSupply = skuInfo.totalSupply; require(totalSupply != 0, "Sale: non-existent sku"); remainingSupply = skuInfo.remainingSupply; maxQuantityPerPurchase = skuInfo.maxQuantityPerPurchase; notificationsReceiver = skuInfo.notificationsReceiver; tokens = new address[](length); prices = new uint256[](length); for (uint256 i = 0; i < length; ++i) { (bytes32 token, bytes32 price) = skuInfo.prices.at(i); tokens[i] = address(uint256(token)); prices[i] = uint256(price); } } /** * Returns the list of created SKU identifiers. * @return skus the list of created SKU identifiers. */ function getSkus() external view override returns (bytes32[] memory skus) { skus = _skus.values; } /* Internal Utility Functions */ /** * Creates an SKU. * @dev Reverts if `totalSupply` is zero. * @dev Reverts if `sku` already exists. * @dev Reverts if `notificationsReceiver` is not the zero address and is not a contract address. * @dev Reverts if the update results in too many SKUs. * @dev Emits the `SkuCreation` event. * @param sku the SKU identifier. * @param totalSupply the initial total supply. * @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase. * @param notificationsReceiver The purchase notifications receiver contract address. * If set to the zero address, the notification is not enabled. */ function _createSku( bytes32 sku, uint256 totalSupply, uint256 maxQuantityPerPurchase, address notificationsReceiver ) internal virtual { require(totalSupply != 0, "Sale: zero supply"); require(_skus.length() < _skusCapacity, "Sale: too many skus"); require(_skus.add(sku), "Sale: sku already created"); if (notificationsReceiver != address(0)) { // solhint-disable-next-line reason-string require(notificationsReceiver.isContract(), "Sale: receiver is not a contract"); } SkuInfo storage skuInfo = _skuInfos[sku]; skuInfo.totalSupply = totalSupply; skuInfo.remainingSupply = totalSupply; skuInfo.maxQuantityPerPurchase = maxQuantityPerPurchase; skuInfo.notificationsReceiver = notificationsReceiver; emit SkuCreation(sku, totalSupply, maxQuantityPerPurchase, notificationsReceiver); } /** * Updates SKU token prices. * @dev Reverts if one of the `tokens` is the zero address. * @dev Reverts if the update results in too many tokens for the SKU. * @param tokenPrices Storage pointer to a mapping of SKU token prices to update. * @param tokens The list of payment tokens to update. * @param prices The list of prices to apply for each payment token. * Zero price values are used to disable a payment token. */ function _setTokenPrices( EnumMap.Map storage tokenPrices, address[] memory tokens, uint256[] memory prices ) internal virtual { for (uint256 i = 0; i < tokens.length; ++i) { address token = tokens[i]; require(token != address(0), "Sale: zero address token"); uint256 price = prices[i]; if (price == 0) { tokenPrices.remove(bytes32(uint256(token))); } else { tokenPrices.set(bytes32(uint256(token)), bytes32(price)); } } require(tokenPrices.length() <= _tokensPerSkuCapacity, "Sale: too many tokens"); } /* Internal Life Cycle Step Functions */ /** * Lifecycle step which validates the purchase pre-conditions. * @dev Responsibilities: * - Ensure that the purchase pre-conditions are met and revert if not. * @dev Reverts if `purchase.recipient` is the zero address. * @dev Reverts if `purchase.token` is the zero address. * @dev Reverts if `purchase.quantity` is zero. * @dev Reverts if `purchase.quantity` is greater than the SKU's `maxQuantityPerPurchase`. * @dev Reverts if `purchase.quantity` is greater than the available supply. * @dev Reverts if `purchase.sku` does not exist. * @dev Reverts if `purchase.sku` exists but does not have a price set for `purchase.token`. * @dev If this function is overriden, the implementer SHOULD super call this before. * @param purchase The purchase conditions. */ function _validation(PurchaseData memory purchase) internal view virtual override { require(purchase.recipient != address(0), "Sale: zero address recipient"); require(purchase.token != address(0), "Sale: zero address token"); require(purchase.quantity != 0, "Sale: zero quantity purchase"); SkuInfo storage skuInfo = _skuInfos[purchase.sku]; require(skuInfo.totalSupply != 0, "Sale: non-existent sku"); require(skuInfo.maxQuantityPerPurchase >= purchase.quantity, "Sale: above max quantity"); if (skuInfo.totalSupply != SUPPLY_UNLIMITED) { require(skuInfo.remainingSupply >= purchase.quantity, "Sale: insufficient supply"); } bytes32 priceKey = bytes32(uint256(purchase.token)); require(skuInfo.prices.contains(priceKey), "Sale: non-existent sku token"); } /** * Lifecycle step which delivers the purchased SKUs to the recipient. * @dev Responsibilities: * - Ensure the product is delivered to the recipient, if that is the contract's responsibility. * - Handle any internal logic related to the delivery, including the remaining supply update; * - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it. * @dev Reverts if there is not enough available supply. * @dev If this function is overriden, the implementer SHOULD super call it. * @param purchase The purchase conditions. */ function _delivery(PurchaseData memory purchase) internal virtual override { SkuInfo memory skuInfo = _skuInfos[purchase.sku]; if (skuInfo.totalSupply != SUPPLY_UNLIMITED) { _skuInfos[purchase.sku].remainingSupply = skuInfo.remainingSupply.sub(purchase.quantity); } } /** * Lifecycle step which notifies of the purchase. * @dev Responsibilities: * - Manage after-purchase event(s) emission. * - Handle calls to the notifications receiver contract's `onPurchaseNotificationReceived` function, if applicable. * @dev Reverts if `onPurchaseNotificationReceived` throws or returns an incorrect value. * @dev Emits the `Purchase` event. The values of `purchaseData` are the concatenated values of `priceData`, `paymentData` * and `deliveryData`. If not empty, the implementer MUST document how to interpret these values. * @dev If this function is overriden, the implementer SHOULD super call it. * @param purchase The purchase conditions. */ function _notification(PurchaseData memory purchase) internal virtual override { emit Purchase( purchase.purchaser, purchase.recipient, purchase.token, purchase.sku, purchase.quantity, purchase.userData, purchase.totalPrice, abi.encodePacked(purchase.pricingData, purchase.paymentData, purchase.deliveryData) ); address notificationsReceiver = _skuInfos[purchase.sku].notificationsReceiver; if (notificationsReceiver != address(0)) { // solhint-disable-next-line reason-string require( IPurchaseNotificationsReceiver(notificationsReceiver).onPurchaseNotificationReceived( purchase.purchaser, purchase.recipient, purchase.token, purchase.sku, purchase.quantity, purchase.userData, purchase.totalPrice, purchase.pricingData, purchase.paymentData, purchase.deliveryData ) == IPurchaseNotificationsReceiver(address(0)).onPurchaseNotificationReceived.selector, // TODO precompute return value "Sale: wrong receiver return value" ); } } } // File @animoca/ethereum-contracts-sale_base/contracts/sale/[email protected] pragma solidity 0.6.8; /** * @title FixedPricesSale * An Sale which implements a fixed prices strategy. * The final implementer is responsible for implementing any additional pricing and/or delivery logic. */ contract FixedPricesSale is Sale { /** * Constructor. * @dev Emits the `MagicValues` event. * @dev Emits the `Paused` event. * @param payoutWallet_ the payout wallet. * @param skusCapacity the cap for the number of managed SKUs. * @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU. */ constructor( address payoutWallet_, uint256 skusCapacity, uint256 tokensPerSkuCapacity ) internal Sale(payoutWallet_, skusCapacity, tokensPerSkuCapacity) {} /* Internal Life Cycle Functions */ /** * Lifecycle step which computes the purchase price. * @dev Responsibilities: * - Computes the pricing formula, including any discount logic and price conversion; * - Set the value of `purchase.totalPrice`; * - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it. * @dev Reverts if `purchase.sku` does not exist. * @dev Reverts if `purchase.token` is not supported by the SKU. * @dev Reverts in case of price overflow. * @param purchase The purchase conditions. */ function _pricing(PurchaseData memory purchase) internal view virtual override { SkuInfo storage skuInfo = _skuInfos[purchase.sku]; require(skuInfo.totalSupply != 0, "Sale: unsupported SKU"); EnumMap.Map storage prices = skuInfo.prices; uint256 unitPrice = _unitPrice(purchase, prices); purchase.totalPrice = unitPrice.mul(purchase.quantity); } /** * Lifecycle step which manages the transfer of funds from the purchaser. * @dev Responsibilities: * - Ensure the payment reaches destination in the expected output token; * - Handle any token swap logic; * - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it. * @dev Reverts in case of payment failure. * @param purchase The purchase conditions. */ function _payment(PurchaseData memory purchase) internal virtual override { if (purchase.token == TOKEN_ETH) { require(msg.value >= purchase.totalPrice, "Sale: insufficient ETH provided"); payoutWallet.transfer(purchase.totalPrice); uint256 change = msg.value.sub(purchase.totalPrice); if (change != 0) { purchase.purchaser.transfer(change); } } else { require(IERC20(purchase.token).transferFrom(_msgSender(), payoutWallet, purchase.totalPrice), "Sale: ERC20 payment failed"); } } /* Internal Utility Functions */ /** * Retrieves the unit price of a SKU for the specified payment token. * @dev Reverts if the specified payment token is unsupported. * @param purchase The purchase conditions specifying the payment token with which the unit price will be retrieved. * @param prices Storage pointer to a mapping of SKU token prices to retrieve the unit price from. * @return unitPrice The unit price of a SKU for the specified payment token. */ function _unitPrice(PurchaseData memory purchase, EnumMap.Map storage prices) internal view virtual returns (uint256 unitPrice) { unitPrice = uint256(prices.get(bytes32(uint256(purchase.token)))); require(unitPrice != 0, "Sale: unsupported payment token"); } } // File @animoca/ethereum-contracts-sale_base/contracts/sale/[email protected] pragma solidity 0.6.8; /** * @title FixedOrderInventorySale * A FixedPricesSale contract that handles the purchase of NFTs of an inventory contract to a * receipient. The provisioning of the NFTs occurs in a sequential order defined by a token list. * Only a single SKU is supported. */ contract FixedOrderInventorySale is FixedPricesSale { address public immutable inventory; uint256 public tokenIndex; uint256[] public tokenList; /** * Constructor. * @dev Reverts if `inventory_` is the zero address. * @dev Emits the `MagicValues` event. * @dev Emits the `Paused` event. * @param inventory_ The inventory contract from which the NFT sale supply is attributed from. * @param payoutWallet The payout wallet. * @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU. */ constructor( address inventory_, address payoutWallet, uint256 tokensPerSkuCapacity ) public FixedPricesSale( payoutWallet, 1, // single SKU tokensPerSkuCapacity ) { // solhint-disable-next-line reason-string require(inventory_ != address(0), "FixedOrderInventorySale: zero address inventory"); inventory = inventory_; } /** * Adds additional tokens to the sale supply. * @dev Reverts if called by any other than the contract owner. * @dev Reverts if `tokens` is empty. * @dev Reverts if any of `tokens` are zero. * @dev The list of tokens specified (in sequence) will be appended to the end of the ordered * sale supply list. * @param tokens The list of tokens to add. */ function addSupply(uint256[] memory tokens) public virtual onlyOwner { uint256 numTokens = tokens.length; // solhint-disable-next-line reason-string require(numTokens != 0, "FixedOrderInventorySale: empty tokens to add"); for (uint256 i = 0; i != numTokens; ++i) { uint256 token = tokens[i]; // solhint-disable-next-line reason-string require(token != 0, "FixedOrderInventorySale: adding zero token"); tokenList.push(token); } if (_skus.length() != 0) { bytes32 sku = _skus.at(0); SkuInfo storage skuInfo = _skuInfos[sku]; skuInfo.totalSupply += numTokens; skuInfo.remainingSupply += numTokens; } } /** * Sets the tokens of the ordered sale supply list. * @dev Reverts if called by any other than the contract owner. * @dev Reverts if called when the contract is not paused. * @dev Reverts if the sale supply is empty. * @dev Reverts if the lengths of `indexes` and `tokens` do not match. * @dev Reverts if `indexes` is zero length. * @dev Reverts if any of `indexes` are less than `tokenIndex`. * @dev Reverts if any of `indexes` are out-of-bounds. * @dev Reverts it `tokens` is zero length. * @dev Reverts if any of `tokens` are zero. * @dev Does not allow resizing of the sale supply, only the re-ordering or replacment of * existing tokens. * @dev Because the elements of `indexes` and `tokens` are processed in sequence, duplicate * entries in either array are permitted, which allows for ordered operations to be performed * on the ordered sale supply list in the same transaction. * @param indexes The list of indexes in the ordered sale supply list whose element values * will be set. * @param tokens The new tokens to set in the ordered sale supply list at the corresponding * positions provided by `indexes`. */ function setSupply(uint256[] memory indexes, uint256[] memory tokens) public virtual onlyOwner whenPaused { uint256 tokenListLength = tokenList.length; // solhint-disable-next-line reason-string require(tokenListLength != 0, "FixedOrderInventorySale: empty token list"); uint256 numIndexes = indexes.length; // solhint-disable-next-line reason-string require(numIndexes != 0, "FixedOrderInventorySale: empty indexes"); uint256 numTokens = tokens.length; // solhint-disable-next-line reason-string require(numIndexes == numTokens, "FixedOrderInventorySale: array length mismatch"); uint256 tokenIndex_ = tokenIndex; for (uint256 i = 0; i != numIndexes; ++i) { uint256 index = indexes[i]; // solhint-disable-next-line reason-string require(index >= tokenIndex_, "FixedOrderInventorySale: invalid index"); // solhint-disable-next-line reason-string require(index < tokenListLength, "FixedOrderInventorySale: index out-of-bounds"); uint256 token = tokens[i]; // solhint-disable-next-line reason-string require(token != 0, "FixedOrderInventorySale: zero token"); tokenList[index] = token; } } /** * Retrieves the amount of total sale supply. * @return The amount of total sale supply. */ function getTotalSupply() public view virtual returns (uint256) { return tokenList.length; } /** * Lifecycle step which delivers the purchased SKUs to the recipient. * @dev Responsibilities: * - Ensure the product is delivered to the recipient, if that is the contract's responsibility. * - Handle any internal logic related to the delivery, including the remaining supply update. * - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it. * @dev Reverts if there is not enough available supply. * @dev Updates `purchase.deliveryData` with the list of tokens allocated from `tokenList` for * this purchase. * @param purchase The purchase conditions. */ function _delivery(PurchaseData memory purchase) internal virtual override { super._delivery(purchase); purchase.deliveryData = new bytes32[](purchase.quantity); uint256 tokenCount = 0; uint256 tokenIndex_ = tokenIndex; while (tokenCount != purchase.quantity) { purchase.deliveryData[tokenCount] = bytes32(tokenList[tokenIndex_]); ++tokenCount; ++tokenIndex_; } tokenIndex = tokenIndex_; } } // File @animoca/f1dt-ethereum-contracts/contracts/sale/[email protected] pragma solidity 0.6.8; /** * @title FixedOrderTrackSale * A FixedOrderInventorySale contract implementation that handles the purchases of F1® DeltaTime * track NFTs by minting them from an inventory contract to the recipient. The provisioning of the * NFTs from the holder account occurs in a sequential order defined by a token list. Only a * single SKU is supported. */ contract FixedOrderTrackSale is FixedOrderInventorySale { /** * Constructor. * @dev Reverts if `inventory` is the zero address. * @dev Emits the `MagicValues` event. * @dev Emits the `Paused` event. * @param inventory The inventory contract from which the NFT sale supply is attributed from. * @param payoutWallet The payout wallet. * @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU. */ constructor( address inventory, address payoutWallet, uint256 tokensPerSkuCapacity ) public FixedOrderInventorySale( inventory, payoutWallet, tokensPerSkuCapacity) {} /** * Creates an SKU. * @dev Reverts if called by any other than the contract owner. * @dev Reverts if called when the contract is not paused. * @dev Reverts if the initial sale supply is empty. * @dev Reverts if `sku` already exists. * @dev Reverts if `notificationsReceiver` is not the zero address and is not a contract address. * @dev Reverts if the update results in too many SKUs. * @dev Emits the `SkuCreation` event. * @param sku the SKU identifier. * @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase. * @param notificationsReceiver The purchase notifications receiver contract address. * If set to the zero address, the notification is not enabled. */ function createSku( bytes32 sku, uint256 maxQuantityPerPurchase, address notificationsReceiver ) external onlyOwner whenPaused { _createSku(sku, tokenList.length, maxQuantityPerPurchase, notificationsReceiver); } /** * Lifecycle step which delivers the purchased SKUs to the recipient. * @dev Responsibilities: * - Ensure the product is delivered to the recipient, if that is the contract's responsibility. * - Handle any internal logic related to the delivery, including the remaining supply update. * - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it. * @dev Reverts if there is not enough available supply. * @dev Reverts if this contract does not have the minter role on the inventory contract. * @dev Updates `purchase.deliveryData` with the list of tokens allocated from `tokenList` for * this purchase. * @dev Mints the tokens allocated in `purchase.deliveryData` to the purchase recipient. * @param purchase The purchase conditions. */ function _delivery(PurchaseData memory purchase) internal virtual override { super._delivery(purchase); address[] memory to = new address[](purchase.quantity); uint256[] memory ids = new uint256[](purchase.quantity); bytes32[] memory uris = new bytes32[](purchase.quantity); uint256[] memory values = new uint256[](purchase.quantity); IFixedOrderInventoryMintable mintableInventory = IFixedOrderInventoryMintable(inventory); for (uint256 index = 0; index != purchase.quantity; ++index) { to[index] = purchase.recipient; ids[index] = uint256(purchase.deliveryData[index]); uris[index] = ""; values[index] = 1; } mintableInventory.batchMint( to, ids, uris, values, false); } } /** * @dev Interface for the mint function of the NFT inventory contract. */ interface IFixedOrderInventoryMintable { /* * Mints a batch of new tokens. * @dev Reverts if some the given token IDs already exist. * @param to address[] List of addresses that will own the minted tokens. * @param ids uint256[] List of ids of the tokens to be minted. * @param uris bytes32[] Concatenated metadata URIs of nfts to be minted. * @param values uint256[] List of quantities of ft to be minted. */ function batchMint( address[] calldata to, uint256[] calldata ids, bytes32[] calldata uris, uint256[] calldata values, bool safe ) external; }
Lifecycle step which delivers the purchased SKUs to the recipient. Responsibilities: - Ensure the product is delivered to the recipient, if that is the contract's responsibility. - Handle any internal logic related to the delivery, including the remaining supply update. - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it. Reverts if there is not enough available supply. Reverts if this contract does not have the minter role on the inventory contract. Updates `purchase.deliveryData` with the list of tokens allocated from `tokenList` for this purchase. Mints the tokens allocated in `purchase.deliveryData` to the purchase recipient. purchase The purchase conditions./
function _delivery(PurchaseData memory purchase) internal virtual override { super._delivery(purchase); address[] memory to = new address[](purchase.quantity); uint256[] memory ids = new uint256[](purchase.quantity); bytes32[] memory uris = new bytes32[](purchase.quantity); uint256[] memory values = new uint256[](purchase.quantity); IFixedOrderInventoryMintable mintableInventory = IFixedOrderInventoryMintable(inventory); for (uint256 index = 0; index != purchase.quantity; ++index) { to[index] = purchase.recipient; ids[index] = uint256(purchase.deliveryData[index]); uris[index] = ""; values[index] = 1; } mintableInventory.batchMint( to, ids, uris, values, false); }
7,883,523
/** *Submitted for verification at Etherscan.io on 2022-04-02 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // // // .;dkkkkkkkkkkkkkkkkkkd' .:xkkkkkkkkd, .:dk0XXXXXXXK0xdl,. .lxkkkkkkkkkkkkkkkkkk:.,okkkkkkko. .cxkkkkkkxc. ;dkkkkkko. // // ;xNMMMMMMMMMMMMMMMMMMMX: .:kNWMMMMMMMMWx. .l0NWWWWWMMMMMMMMMWNO;..lKWMMMMMMMMMMMMMMMMMMMKkKWMMMMMMMK, .c0WMMMMMMMMX: .;xXWMMMMMNo. // // .,lddddddddddddddddxKMMMK; .,lddddddx0WMMMX; .;llc::;;::cox0XWMMMMMWXdcoddddddddddddddddONMW0ddddddxXMMMK, .:odddddONMMMMO' .,lddddd0WWd. // // .. .dWWKl. . :XMMMWx. ... .,oKWMMMMWx. ,KMNc .kMMM0, .. .xWMMMWx'. 'kNk. // // .. .dKo' .. .xWMMMK; .. .'.. ,OWWMMWx. ,Okc' .kMMMK, .. ,0MMMMXl. .dNO' // // .. .:ooo;......,' . :XMMMWd. . .l0XXOc. ;xKMWNo. ,looc'......'... .kMMMK, .. cXMMM0, .oNK; // // .. '0MMMk. .. .kWMMMK,.' ;KMMMWNo. .;kNkc,. .dWMMK: .. .kMMMK, .. .dWMXc cXK: // // .. '0MMMXkxxxxxxxxd' . .:. cXMMMWd,' '0MMMMM0l;;;;;;:c;. .. .dWMMW0xxxxxxxxx; .kMMMK, .. 'ONd. :KXc // // .. '0MMMMMMMMMMMMMNc .. :O: .kMMMMK:. 'd0NWMWWWWWWWNXOl'... .dWMMMMMMMMMMMMWl .kMMMK, . :d' ;0No. // // .. .lkkkkkkkkkKWMMNc . .dNd. cNMMMWo.. .':dOXWMMMMMMMWXk:. :xkkkkkkkk0NMMWl .kMMMK, . . 'ONd. // // .. .oNMXd... '0M0' .kMMMM0, .. .;o0NMMMMMMWx. ,0MN0: .kMMMK, .. .kW0' // // .. cKk, . lNMNl cNMMMNo .',.. .;xXWMMMWx. 'O0c'. .kMMMK, .. .xWMO. // // .. .,ccc,.....,,. .. .kMMMk. .OMMMW0;'d0XX0xc,. :d0MMWx. ':cc:'....';. .. .kMMMK, .. .oNMMO. // // .. '0MMMk. .. ,kKKKk' lNMMMN0KWWWMMMWNKl. cXMWx. .dWMMX: .. .kMMMK, .. .OMMMO. // // .. '0MMMk'.......... ..... 'OMMKo:::::cxNMMMKl'. .OMWx. .dWMMXc.......... .kMMMK:.........,' .OMMMO. // // .. '0MMMNXKKKKKKKKd. lNM0' ;XMMMWN0c .OMWd. .dWMMWXKKKKKKKK0c .kMMMWXKKKKKKKKK0: .OMMMO. // // .. 'OWWWWWWWWWWMMNc 'llc' . '0MNc .kWMMMMX: ,KXx:. .oNWWWWWWWWWWMMWl .xWWWWWWWWWWWMMMN: .OMMMO. // // .. ,:::::::::cOWO. .xWWO' . oNMO' .lkOOx;. .'cd,... .::::::::::dXMWl '::::::::::xWMMX: .OMMWx. // // .. dNl ,0Xd. .. ,0MNo. . ..'. .. ,0WK: :NWOo, .OWKo. // // .' .oO, .co, .. .oOc.... ... .. ,xo,.. ckl..'. 'dd' // // ............................. .......... . .. . ..................... ..................... ......... // // // // // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @title 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); } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev 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 internal _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev 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 String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Implementation of 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}. * * This ERC721 Has been adjusted from OpenZepplins to have a totalSupply method. It also is set up to better handle * batch transactions. Namely it does not update _balances on a call to {_mint} and expects the minting method to do so. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; struct AddressData { uint128 balance; uint128 numberMinted; } // Token name string internal _name; // Token symbol string internal _symbol; // Tracking total minted // Only used when `_isSequential` is false uint256 internal _totalMinted; // Tracking total burned uint256 internal _totalBurned; // Tracking the next sequential mint uint256 internal _nextSequential; // This ensures that ownerOf() can still run in constant time // With a max runtime of checking 10 variables, but saves on batch mints tremendously. uint256 internal constant MAX_OWNER_SEQUENCE = 10; // Tracking if the collection is still sequentially minted bool internal _notSequentialMint; // Mapping from token ID to owner address mapping(uint256 => address) internal _owners; // Mapping from token ID to burned // This is necessary because to optimize gas fees for multiple mints a token with // `_owners[tokenId] = address(0)` is not necessarily a token with no owner. mapping(uint256 => bool) internal _burned; // Mapping owner address to token count mapping(address => AddressData) 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; /** * @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].balance; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: owner query for nonexistent token"); if (tokenId < _nextSequential) { uint256 lowestTokenToCheck; if (tokenId >= MAX_OWNER_SEQUENCE) { lowestTokenToCheck = tokenId - MAX_OWNER_SEQUENCE + 1; } for (uint256 i = tokenId; i >= lowestTokenToCheck; i--) { if (_owners[i] != address(0)) { return _owners[i]; } } } return _owners[tokenId]; } /** * @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 Returns the total current supply of the contract. * * WARNING - Underlying variables do NOT get automatically updated on mints * so that we can save gas on transactions that mint multiple tokens. * */ function totalSupply() public view virtual returns (uint256) { return totalMinted() - _totalBurned; } /** * @dev Returns the total ever minted from this contract. * * WARNING - Underlying variable do NOT get automatically updated on mints * so that we can save gas on transactions that mint multiple tokens. * */ function totalMinted() public view virtual returns (uint256) { if (_notSequentialMint) { return _totalMinted; } return _nextSequential; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721: 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, owner); } /** * @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 { address owner = ERC721.ownerOf(tokenId); require( _isApprovedOrOwner(_msgSender(), tokenId, owner), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId, owner); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * This was modified to not call _safeTransfer because that would require fetching * ownerOf() twice which is more expensive than doing it together. * _safeTransfer was not modified to take in owner because functions using that * method should be able to assume that it will check for the tokenOwner. * * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { address owner = ERC721.ownerOf(tokenId); require( _isApprovedOrOwner(_msgSender(), tokenId, owner), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId, owner); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @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, ERC721.ownerOf(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) { if (_burned[tokenId]) { return false; } if (tokenId < _nextSequential) { return true; } return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner( address spender, uint256 tokenId, address owner ) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * WARNING - this method does not update totalSupply or _balances, please update that externally. Doing so * will allow us to save gas on transactions that mint more than one NFT * * 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. * WARNING: This method does not update totalSupply, please update that externally. Doing so * will allow us to save gas on transactions */ 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 * WARNING: This method does not update totalSupply or _balances, please update that externally. Doing so * will allow us to save gas on transactions that mint more than one NFT * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(_notSequentialMint, "_notSequentialMint must be true"); require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Mints from `_nextSequential` to `_nextSequential + quantity` and transfers it to `to`. * * WARNING: This method does not update totalSupply or _balances, please update that externally. Doing so * will allow us to save gas on transactions that mint more than one NFT * * Requirements: * * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _safeMintSequential(address to, uint256 quantity) internal virtual { require(!_notSequentialMint, "_notSequentialMint must be false"); require(to != address(0), "ERC721: mint to the zero address"); uint256 lastNum = _nextSequential + quantity; // ensures ownerOf runs quickly even if user is minting a large number like 100 for ( uint256 i = _nextSequential; i < lastNum; i += MAX_OWNER_SEQUENCE ) { _owners[i] = to; } // Gas is cheaper to have two separate for loops for (uint256 i = _nextSequential; i < lastNum; i++) { emit Transfer(address(0), to, i); require( _checkOnERC721Received(address(0), to, i, ""), "ERC721: transfer to non ERC721Receiver implementer" ); } _balances[to] = AddressData( _balances[to].balance + uint128(quantity), _balances[to].numberMinted + uint128(quantity) ); _nextSequential = lastNum; } /** * @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); require(owner == _msgSender(), "Cannot burn a token you do not own"); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId, owner); _balances[owner].balance -= 1; _totalBurned += 1; _burned[tokenId] = true; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * WARNING this method assumes the passed in owner is the token owner. This is done because with the gas optimization * calling ownerOf can be an expensive calculation and should only be done once (in the outer most layer) * * 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, address owner ) internal virtual { require(owner == 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, from); _balances[from].balance -= 1; _balances[to].balance += 1; _owners[tokenId] = to; uint256 nextTokenId = tokenId + 1; if (nextTokenId < _nextSequential) { if (_owners[nextTokenId] == address(0)) { _owners[nextTokenId] = from; } } emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) internal virtual { if (_tokenApprovals[tokenId] != to) { _tokenApprovals[tokenId] = to; emit Approval(owner, 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 {} } /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981 is IERC165 { /** * ERC165 bytes to add to interface array - set in parent contract * implementing this standard * * bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a * bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; * _registerInterface(_INTERFACE_ID_ERC2981); */ /** * @notice 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); } /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and( vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if ( uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0 ) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", hash) ); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); } } /** * @dev External interface of the EaselyPayout contract */ interface IEaselyPayout { /** * @dev Takes in a payable amount and splits it among the given royalties. * Also takes a cut of the payable amount depending on the sender and the primaryPayout address. * Ensures that this method never splits over 100% of the payin amount. */ function splitPayable( address primaryPayout, address[] memory royalties, uint256[] memory bps ) external payable; } /** * @dev Extension of the ERC721Enumerable contract that integrates a marketplace so that simple lazy-sales * do not have to be done on another contract. This saves gas fees on secondary sales because * buyers will not have to pay a gas fee to setApprovalForAll for another marketplace contract after buying. * * Easely will help power the lazy-selling as well as lazy minting that take place on * directly on the collection, which is why we take a cut of these transactions. Our cut can * be publically seen in the connected EaselyPayout contract and cannot exceed 5%. * * Owners also set an alternate signer which they can change at any time. This alternate signer helps enable * sales for large batches of addresses without needing to manually sign hundreds or thousands of hashes. */ abstract contract ERC721Marketplace is ERC721, Ownable { using ECDSA for bytes32; using Strings for uint256; /* see {IEaselyPayout} for more */ address public constant PAYOUT_CONTRACT_ADDRESS = 0x68f5C1e24677Ac4ae845Dde07504EAaD98f82572; uint256 public constant TIME_PER_DECREMENT = 300; uint256 public constant MAX_ROYALTIES_BPS = 9500; /* Optional basis points for the owner for secondary sales of this collection */ uint256 public constant MAX_SECONDARY_BPS = 1000; /* Let's the owner enable another address to lazy mint */ address public alternateSignerAddress; /* Optional basis points for the owner for secondary sales of this collection */ uint256 public ownerRoyaltyBPS; /* Optional addresses to distribute revenue of primary sales of this collection */ address[] public revenueShare; /* Optional basis points for revenue share for primary sales of this collection */ uint256[] public revenueShareBPS; /* Mapping to the active version for all signed transactions */ mapping(address => uint256) internal _addressToActiveVersion; /* Cancelled or finalized sales by hash to determine buyabliity */ mapping(bytes32 => bool) internal _cancelledOrFinalizedSales; // Events related to lazy selling event SaleCancelled(address indexed seller, bytes32 hash); event SaleCompleted( uint256 indexed tokenId, uint256 price, address indexed seller, address indexed buyer, bytes32 hash ); // Miscellaneous events event VersionChanged(address indexed seller, uint256 version); event AltSignerChanged(address newSigner); event BalanceWithdrawn(uint256 balance); event RoyaltyUpdated(uint256 bps); event RevenueShareUpdated( address address1, address address2, uint256 bps1, uint256 bps2 ); /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(Ownable).interfaceId || interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @dev see {IERC2981-supportsInterface} */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { uint256 royalty = (_salePrice * ownerRoyaltyBPS) / 10000; return (owner(), royalty); } /** * @dev See {_currentPrice} */ function getCurrentPrice(uint256[4] memory pricesAndTimestamps) external view returns (uint256) { return _currentPrice(pricesAndTimestamps); } /** * @dev Returns the current activeVersion of an address both used to create signatures * and to verify signatures of {buyToken} and {buyNewToken} */ function getActiveVersion(address address_) external view returns (uint256) { return _addressToActiveVersion[address_]; } /** * This function, while callable by anybody will always ONLY withdraw the * contract's balance to: * * the owner's account * the addresses the owner has set up for revenue share * the easely payout contract cut - capped at 5% but can be lower for some users * * This is callable by anybody so that Easely can set up automatic payouts * after a contract has reached a certain minimum to save creators the gas fees * involved in withdrawing balances. */ function withdrawBalance(uint256 withdrawAmount) external { require(withdrawAmount <= address(this).balance); IEaselyPayout payoutContract = IEaselyPayout(PAYOUT_CONTRACT_ADDRESS); payoutContract.splitPayable{value: withdrawAmount}( owner(), revenueShare, revenueShareBPS ); emit BalanceWithdrawn(withdrawAmount); } /** * @dev Allows the owner to change who the alternate signer is */ function setAltSigner(address alt) external onlyOwner { alternateSignerAddress = alt; emit AltSignerChanged(alt); } /** * @dev see {_setRoyalties} */ function setRevenueShare( address[2] memory newAddresses, uint256[2] memory newBPS ) external onlyOwner { _setRevenueShare(newAddresses, newBPS); emit RevenueShareUpdated( newAddresses[0], newAddresses[1], newBPS[0], newBPS[1] ); } /** * @dev see {_setSecondary} */ function setRoyaltiesBPS(uint256 newBPS) external onlyOwner { _setRoyaltiesBPS(newBPS); emit RoyaltyUpdated(newBPS); } /** * @dev Usable by any user to update the version that they want their signatures to check. This is helpful if * an address wants to mass invalidate their signatures without having to call cancelSale on each one. */ function updateVersion(uint256 version) external { _addressToActiveVersion[_msgSender()] = version; emit VersionChanged(_msgSender(), version); } /** * @dev returns how many tokens the given address has minted. */ function mintCount(address addr) external view returns (uint256) { return _balances[addr].numberMinted; } /** * @dev Usable by the owner of any token initiate a sale for their token. This does not * lock the tokenId and the owner can freely trade their token, but doing so will * invalidate the ability for others to buy. */ function hashToSignToSellToken( uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) external view returns (bytes32) { require( _msgSender() == ERC721.ownerOf(tokenId), "Not the owner of the token" ); return _hashForSale( _msgSender(), version, nonce, tokenId, pricesAndTimestamps ); } /** * @dev With a hash signed by the method {hashToSignToSellToken} any user sending enough value can buy * the token from the seller. Tokens not owned by the contract owner are all considered secondary sales and * will give a cut to the owner of the contract based on the secondaryOwnerBPS. */ function buyToken( address seller, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps, bytes memory signature ) external payable { uint256 currentPrice = _currentPrice(pricesAndTimestamps); require( _addressToActiveVersion[seller] == version, "Incorrect signature version" ); require(msg.value >= currentPrice, "Not enough ETH to buy"); _markHashSold( seller, version, nonce, tokenId, pricesAndTimestamps, currentPrice, signature ); _safeTransfer(seller, _msgSender(), tokenId, ""); if (seller != owner()) { IEaselyPayout(PAYOUT_CONTRACT_ADDRESS).splitPayable{ value: currentPrice }(seller, _ownerRoyalties(), _ownerBPS()); } payable(_msgSender()).transfer(msg.value - currentPrice); } /** * @dev Usable to cancel hashes generated from {hashToSignToSellToken} */ function cancelSale( uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) external { bytes32 hash = _hashToCheckForSale( _msgSender(), version, nonce, tokenId, pricesAndTimestamps ); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @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 override returns (string memory) { return "ipfs://"; } /** * @dev helper method get ownerRoyalties into an array form */ function _ownerRoyalties() internal view returns (address[] memory) { address[] memory ownerRoyalties = new address[](1); ownerRoyalties[0] = owner(); return ownerRoyalties; } /** * @dev helper method get secondary BPS into array form */ function _ownerBPS() internal view returns (uint256[] memory) { uint256[] memory ownerBPS = new uint256[](1); ownerBPS[0] = ownerRoyaltyBPS; return ownerBPS; } /** * @dev Current price for a sale which is calculated for the case of a descending sale. So * the ending price must be less than the starting price and the timestamp is active. * Standard single fare sales will have a matching starting and ending price. */ function _currentPrice(uint256[4] memory pricesAndTimestamps) internal view returns (uint256) { uint256 startingPrice = pricesAndTimestamps[0]; uint256 endingPrice = pricesAndTimestamps[1]; uint256 startingTimestamp = pricesAndTimestamps[2]; uint256 endingTimestamp = pricesAndTimestamps[3]; uint256 currTime = block.timestamp; require(currTime >= startingTimestamp, "Has not started yet"); require( startingTimestamp < endingTimestamp, "Must end after it starts" ); require(startingPrice >= endingPrice, "Ending price cannot be bigger"); if (startingPrice == endingPrice || currTime > endingTimestamp) { return endingPrice; } uint256 diff = startingPrice - endingPrice; uint256 decrements = (currTime - startingTimestamp) / TIME_PER_DECREMENT; if (decrements == 0) { return startingPrice; } // decrements will equal 0 before totalDecrements does so we will not divide by 0 uint256 totalDecrements = (endingTimestamp - startingTimestamp) / TIME_PER_DECREMENT; return startingPrice - (diff / totalDecrements) * decrements; } /** * @dev Sets secondary BPS amount */ function _setRoyaltiesBPS(uint256 newBPS) internal { require( ownerRoyaltyBPS <= MAX_SECONDARY_BPS, "Cannot take more than 10% of secondaries" ); ownerRoyaltyBPS = newBPS; } /** * @dev Sets primary revenue share */ function _setRevenueShare( address[2] memory newAddresses, uint256[2] memory newBPS ) internal { require( newBPS[0] + newBPS[1] <= MAX_ROYALTIES_BPS, "Revenue share too high" ); revenueShare = newAddresses; revenueShareBPS = newBPS; } /** * @dev Checks if an address is either the owner, or the approved alternate signer. */ function _checkValidSigner(address signer) internal view { require( signer == owner() || signer == alternateSignerAddress, "Not valid signer." ); } /** * @dev First checks if a sale is valid by checking that the hash has not been cancelled or already completed * and that the correct address has given the signature. If both checks pass we mark the hash as complete and * emit an event. */ function _markHashSold( address seller, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps, uint256 salePrice, bytes memory signature ) internal { bytes32 hash = _hashToCheckForSale( seller, version, nonce, tokenId, pricesAndTimestamps ); require(!_cancelledOrFinalizedSales[hash], "Sale no longer active"); require( hash.recover(signature) == seller, "Not signed by current seller" ); _cancelledOrFinalizedSales[hash] = true; emit SaleCompleted(tokenId, salePrice, seller, _msgSender(), hash); } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @return Hash of message prefix and order hash per Ethereum format */ function _hashToCheckForSale( address owner, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return ECDSA.toEthSignedMessageHash( _hashForSale( owner, version, nonce, tokenId, pricesAndTimestamps ) ); } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @return Hash of message prefix and order hash per Ethereum format */ function _hashForSale( address owner, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return keccak256( abi.encode( address(this), block.chainid, owner, version, nonce, tokenId, pricesAndTimestamps ) ); } } /** * @dev This implements a lazy-minted, randomized collection of ERC721Marketplace. * It requires that the creator knows the total number of NFTs they want and has an IPFS * hash that is a directory with all the tokenIds from 0 to the #NFTs - 1. * * It has two main methods to lazy-mint, one allows the owner or alternate signer to approve single use signatures * for specific wallet addresses and the other allows a general mint signature that anyone can use. * * Minting from this collection is always random, this can be done either with a reveal * mechanism that has a random offset, or on-chain randomness if the collection is already revealed. */ contract ERC721RandomizedCollectionV2 is ERC721Marketplace { using ECDSA for bytes32; using Strings for uint256; bool public burnable; bool private hasInit = false; uint256 public constant MAX_SUPPLY_LIMIT = 10**9; uint256 public maxSupply; // Limits how much any single transaction can be uint256 public transactionMax; // Limits how much any single wallet can mint on a collection. uint256 public maxMint; // Used to shuffle tokenURI upon reveal uint256 public offset; // Mapping to enable constant time onchain randomness uint256[MAX_SUPPLY_LIMIT] private indices; string private ipfsHash; // Randomized Collection Events event Minted( address indexed buyer, uint256 amount, uint256 unitPrice, bytes32 hash ); event IpfsRevealed(string ipfsHash, bool locked); /** * @dev Constructor function */ constructor( bool[2] memory bools, address[3] memory addresses, uint256[6] memory uints, string[3] memory strings ) ERC721(strings[0], strings[1]) { addresses[0] = _msgSender(); _init(bools, addresses, uints, strings); } function init( bool[2] memory bools, address[3] memory addresses, uint256[6] memory uints, string[3] memory strings ) external { _init(bools, addresses, uints, strings); } function _init( bool[2] memory bools, address[3] memory addresses, uint256[6] memory uints, string[3] memory strings ) internal { require(!hasInit, "Already has be initiated"); hasInit = true; burnable = bools[0]; _notSequentialMint = bools[1]; _owner = msg.sender; address[2] memory revenueShare = [addresses[0], addresses[1]]; alternateSignerAddress = addresses[2]; _setRoyaltiesBPS(uints[0]); _setRevenueShare(revenueShare, [uints[1], uints[2]]); maxSupply = uints[3]; require(maxSupply < MAX_SUPPLY_LIMIT, "Collection is too big"); // Do not allow more than 100 mints a transaction so users cannot exceed gas limit if (uints[4] == 0 || uints[4] >= 25000) { transactionMax = 25000; } else { transactionMax = uints[4]; } maxMint = uints[5]; _name = strings[0]; _symbol = strings[1]; ipfsHash = strings[2]; if (_notSequentialMint) { emit IpfsRevealed(ipfsHash, false); } } function isRevealed() external view returns (bool) { return _notSequentialMint; } /** * @dev If this collection was created with burnable on, owners of tokens * can use this method to burn their tokens. Easely will keep track of * burns in case creators want to reward users for burning tokens. */ function burn(uint256 tokenId) external { require(burnable, "Tokens from this collection are not burnable"); _burn(tokenId); } /** * @dev Method used if the creator wants to keep their collection hidden until * a later release date. On reveal, a creator can decide if they want to * lock the unminted tokens or enable them for on-chain randomness minting. * * IMPORTANT - this function can only be called ONCE, if a wrong IPFS hash * is submitted by the owner, it cannot ever be switched to a different one. */ function lockTokenURI(string calldata revealIPFSHash, bool lockOnReveal) external onlyOwner { require(!_notSequentialMint, "The token URI has already been set"); offset = _random(maxSupply); ipfsHash = revealIPFSHash; _notSequentialMint = true; if (lockOnReveal) { // This will lock the unminted tokens at reveal time maxSupply = _nextSequential; } _totalMinted = _nextSequential; emit IpfsRevealed(revealIPFSHash, lockOnReveal); } /** * @dev tokenURI of a tokenId, will change to include the tokeId and an offset in * the URI once the collection has been revealed. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_notSequentialMint) { return string(abi.encodePacked(_baseURI(), ipfsHash)); } require(_exists(tokenId), "URI query for nonexistent token"); uint256 offsetId = (tokenId + offset) % maxSupply; return string( abi.encodePacked(_baseURI(), ipfsHash, "/", offsetId.toString()) ); } /** * @dev Hash that the owner or approved alternate signer then sign that the approved buyer * can use in order to call the {mintAllow} method. */ function hashToSignForAllowList( address allowedAddress, uint256 version, uint256 nonce, uint256 price, uint256 amount ) external view returns (bytes32) { _checkValidSigner(_msgSender()); return _hashForAllowList(allowedAddress, version, nonce, price, amount); } /** * @dev A way to invalidate a signature so the given params cannot be used in the {mintAllow} method. */ function cancelAllowList( address allowedAddress, uint256 version, uint256 nonce, uint256 price, uint256 amount ) external { _checkValidSigner(_msgSender()); bytes32 hash = _hashToCheckForAllowList( allowedAddress, version, nonce, price, amount ); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @dev Allows a user with an approved signature to mint at a price and quantity specified by the * contract. A user is still limited by totalSupply, transactionMax, and mintMax if populated. * signing with amount = 0 will allow any buyAmount less than the other limits. */ function mintAllow( address allowedAddress, uint256 version, uint256 nonce, uint256 price, uint256 amount, uint256 buyAmount, bytes memory signature ) external payable { require( totalMinted() + buyAmount <= maxSupply, "Over token supply limit" ); require(buyAmount == amount || amount == 0, "Over signature amount"); require(buyAmount <= transactionMax, "Over transaction limit"); require( version == _addressToActiveVersion[owner()], "This presale version is disabled" ); require(allowedAddress == _msgSender(), "Invalid sender"); uint256 totalPrice = price * buyAmount; require(msg.value >= totalPrice, "Msg value too small"); bytes32 hash = _hashToCheckForAllowList( allowedAddress, version, nonce, price, amount ); require( !_cancelledOrFinalizedSales[hash], "Signature no longer active" ); address signer = hash.recover(signature); _checkValidSigner(signer); _cancelledOrFinalizedSales[hash] = true; _mintRandom(_msgSender(), buyAmount); emit Minted(_msgSender(), buyAmount, price, hash); payable(_msgSender()).transfer(msg.value - totalPrice); } /** * @dev Hash that the owner or approved alternate signer then sign that buyers use * in order to call the {mint} method. */ function hashToSignForMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) external view returns (bytes32) { _checkValidSigner(_msgSender()); require(amount <= transactionMax, "Over transaction limit"); return _hashForMint(version, amount, pricesAndTimestamps); } /** * @dev A way to invalidate a signature so the given params cannot be used in the {mint} method. */ function cancelMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) external { _checkValidSigner(_msgSender()); bytes32 hash = _hashToCheckForMint( version, amount, pricesAndTimestamps ); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @dev Allows anyone to buy an amount of tokens at a price which matches * the signature that the owner or alternate signer has approved */ function mint( uint256 version, uint256 amount, uint256 buyAmount, uint256[4] memory pricesAndTimestamps, bytes memory signature ) external payable { require( totalMinted() + buyAmount <= maxSupply, "Over token supply limit" ); require(buyAmount == amount || amount == 0, "Over signature amount"); require(buyAmount <= transactionMax, "Over transaction limit"); require(version == _addressToActiveVersion[owner()], "Invalid version"); uint256 unitPrice = _currentPrice(pricesAndTimestamps); uint256 totalPrice = buyAmount * unitPrice; require(msg.value >= totalPrice, "Msg value too small"); bytes32 hash = _hashToCheckForMint( version, amount, pricesAndTimestamps ); require( !_cancelledOrFinalizedSales[hash], "Signature no longer active" ); address signer = hash.recover(signature); _checkValidSigner(signer); _mintRandom(_msgSender(), buyAmount); emit Minted(_msgSender(), buyAmount, totalPrice, hash); payable(_msgSender()).transfer(msg.value - totalPrice); } /** * @dev Hash an order that we need to check against the signature to see who the signer is. * see {_hashForAllowList} to see the hash that needs to be signed. */ function _hashToCheckForAllowList( address allowedAddress, uint256 nonce, uint256 version, uint256 price, uint256 amount ) internal view returns (bytes32) { return ECDSA.toEthSignedMessageHash( _hashForAllowList(allowedAddress, nonce, version, price, amount) ); } /** * @dev Hash that the owner or alternate wallet must sign to enable a {mintAllow} for a user * @return Hash of message prefix and order hash per Ethereum format */ function _hashForAllowList( address allowedAddress, uint256 nonce, uint256 version, uint256 price, uint256 amount ) internal view returns (bytes32) { return keccak256( abi.encode( address(this), block.chainid, owner(), allowedAddress, nonce, version, price, amount ) ); } /** * @dev Hash an order that we need to check against the signature to see who the signer is. * see {_hashForMint} to see the hash that needs to be signed. */ function _hashToCheckForMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return ECDSA.toEthSignedMessageHash( _hashForMint(version, amount, pricesAndTimestamps) ); } /** * @dev Hash that the owner or alternate wallet must sign to enable {mint} for all users */ function _hashForMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return keccak256( abi.encode( address(this), block.chainid, owner(), amount, pricesAndTimestamps, version ) ); } /// @notice Generates a pseudo random index of our tokens that has not been used so far function _mintRandomIndex(address buyer, uint256 amount) internal { // number of tokens left to create uint256 supplyLeft = maxSupply - _totalMinted; for (uint256 i = 0; i < amount; i++) { // generate a random index uint256 index = _random(supplyLeft); uint256 tokenAtPlace = indices[index]; uint256 tokenId; // if we havent stored a replacement token... if (tokenAtPlace == 0) { //... we just return the current index tokenId = index; } else { // else we take the replace we stored with logic below tokenId = tokenAtPlace; } // get the highest token id we havent handed out uint256 lastTokenAvailable = indices[supplyLeft - 1]; // we need to store a replacement token for the next time we roll the same index // if the last token is still unused... if (lastTokenAvailable == 0) { // ... we store the last token as index indices[index] = supplyLeft - 1; } else { // ... we store the token that was stored for the last token indices[index] = lastTokenAvailable; } _safeMint(buyer, tokenId + _nextSequential); supplyLeft--; } _balances[buyer] = AddressData( _balances[buyer].balance + uint128(amount), _balances[buyer].numberMinted + uint128(amount) ); } /// @notice Generates a pseudo random number based on arguments with decent entropy /// @param max The maximum value we want to receive /// @return A random number less than the max function _random(uint256 max) internal view returns (uint256) { if (max == 0) { return 0; } uint256 rand = uint256( keccak256( abi.encode( msg.sender, block.difficulty, block.timestamp, blockhash(block.number - 1) ) ) ); return rand % max; } /** * @dev Wrapper around {_mintRandomIndex} that incrementally if the collection has not * been revealed yet, which also checks the buyer has not exceeded maxMint count */ function _mintRandom(address buyer, uint256 amount) internal { require( maxMint == 0 || _balances[buyer].numberMinted + amount <= maxMint, "Buyer over mint maximum" ); if (_notSequentialMint) { _mintRandomIndex(buyer, amount); _totalMinted += amount; } else { _safeMintSequential(buyer, amount); } } }
First checks if a sale is valid by checking that the hash has not been cancelled or already completed and that the correct address has given the signature. If both checks pass we mark the hash as complete and emit an event./
function _markHashSold( address seller, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps, uint256 salePrice, bytes memory signature ) internal { bytes32 hash = _hashToCheckForSale( seller, version, nonce, tokenId, pricesAndTimestamps ); require(!_cancelledOrFinalizedSales[hash], "Sale no longer active"); require( hash.recover(signature) == seller, "Not signed by current seller" ); _cancelledOrFinalizedSales[hash] = true; emit SaleCompleted(tokenId, salePrice, seller, _msgSender(), hash); }
15,379,566
./full_match/42/0x1973FC2bAeE05598f79ac14c77C45C99166F07f7/sources/contracts/das_get_balance.sol
/ uint256 _gas = 35000; (bool sent, bytes memory data) = _receiver.call{value:_amount, gas: _gas}(""); require(sent, "Failed to send Ether");
function sendEth(address payable _receiver, uint256 _amount) public payable { _receiver.transfer(_amount); }
9,589,287