file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// File: contracts/vaults/IStrategy.sol pragma solidity 0.5.17; interface istrategy59 { //inject NONSTANDARD NAMING function GETNAME35() external pure returns (string memory); //inject NONSTANDARD NAMING function WANT31() external view returns (address); //inject NONSTANDARD NAMING function WITHDRAW24(address) external; //inject NONSTANDARD NAMING function WITHDRAW24(uint256) external; //inject NONSTANDARD NAMING function WITHDRAWALL24() external returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF3() external view returns (uint256); //inject NONSTANDARD NAMING } // File: contracts/IERC20.sol //SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.5.17; interface ierc2080 { //inject NONSTANDARD NAMING function TOTALSUPPLY74() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF3(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER92(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE58(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE17(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM23(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER57(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL94(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: contracts/ITreasury.sol pragma solidity 0.5.17; interface itreasury2 { //inject NONSTANDARD NAMING function DEFAULTTOKEN28() external view returns (ierc2080); //inject NONSTANDARD NAMING function DEPOSIT94(ierc2080 token, uint256 amount) external; //inject NONSTANDARD NAMING function WITHDRAW24(uint256 amount, address withdrawAddress) external; //inject NONSTANDARD NAMING } // File: contracts/vaults/IVault.sol pragma solidity 0.5.17; interface ivault53 { //inject NONSTANDARD NAMING function WANT31() external view returns (ierc2080); //inject NONSTANDARD NAMING function TRANSFERFUNDSTOSTRATEGY94(address strategy, uint256 amount) external; //inject NONSTANDARD NAMING function AVAILABLEFUNDS75() external view returns (uint256); //inject NONSTANDARD NAMING } // File: contracts/vaults/IVaultRewards.sol pragma solidity 0.5.17; interface ivaultrewards63 { //inject NONSTANDARD NAMING function WANT31() external view returns (ierc2080); //inject NONSTANDARD NAMING function NOTIFYREWARDAMOUNT2(uint256 reward) external; //inject NONSTANDARD NAMING } // File: contracts/vaults/IController.sol pragma solidity 0.5.17; interface icontroller20 { //inject NONSTANDARD NAMING function CURRENTEPOCHTIME27() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF3(address) external view returns (uint256); //inject NONSTANDARD NAMING function REWARDS0(address token) external view returns (ivaultrewards63); //inject NONSTANDARD NAMING function VAULT69(address token) external view returns (ivault53); //inject NONSTANDARD NAMING function ALLOWABLEAMOUNT15(address) external view returns (uint256); //inject NONSTANDARD NAMING function TREASURY79() external view returns (itreasury2); //inject NONSTANDARD NAMING function APPROVEDSTRATEGIES44(address, address) external view returns (bool); //inject NONSTANDARD NAMING function GETHARVESTINFO14(address strategy, address user) //inject NONSTANDARD NAMING external view returns ( uint256 vaultRewardPercentage, uint256 hurdleAmount, uint256 harvestPercentage ); function WITHDRAW24(address, uint256) external; //inject NONSTANDARD NAMING function EARN37(address, uint256) external; //inject NONSTANDARD NAMING function INCREASEHURDLERATE27(address token) external; //inject NONSTANDARD NAMING } // File: contracts/ISwapRouter.sol //SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.5.17; interface swaprouter18 { //inject NONSTANDARD NAMING function WETH90() external pure returns (address); //inject NONSTANDARD NAMING function SWAPEXACTTOKENSFORTOKENS91( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } // File: contracts/SafeMath.sol pragma solidity 0.5.17; // Note: This file has been modified to include the sqrt function for quadratic voting library math29 { //inject NONSTANDARD NAMING function MAX82(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN43(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE17(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } function SQRT87(uint256 x) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 n = x / 2; uint256 lstX = 0; while (n != lstX){ lstX = n; n = (n + x/n) / 2; } return uint256(n); } } library safemath85 { //inject NONSTANDARD NAMING function ADD14(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB75(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB75(a, b, "SafeMath: subtraction overflow"); } function SUB75(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL41(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV62(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV62(a, b, "SafeMath: division by zero"); } function DIV62(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD3(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD3(a, b, "SafeMath: modulo by zero"); } function MOD3(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // File: contracts/zeppelin/Address.sol pragma solidity 0.5.17; library address35 { //inject NONSTANDARD NAMING function ISCONTRACT42(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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); } function TOPAYABLE96(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE71(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: contracts/zeppelin/SafeERC20.sol pragma solidity 0.5.17; library safeerc2099 { //inject NONSTANDARD NAMING using safemath85 for uint256; using address35 for address; function SAFETRANSFER62(ierc2080 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.TRANSFER92.selector, to, value)); } function SAFETRANSFERFROM40(ierc2080 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.TRANSFERFROM23.selector, from, to, value)); } function SAFEAPPROVE5(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // 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.ALLOWANCE58(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, value)); } function SAFEINCREASEALLOWANCE71(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE58(address(this), spender).ADD14(value); CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE44(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE58(address(this), spender).SUB75(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, newAllowance)); } function CALLOPTIONALRETURN65(ierc2080 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).ISCONTRACT42(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/vaults/strategy/MStableStrategy.sol //SPDX-License-Identifier: MIT pragma solidity 0.5.17; interface ibpt3 { //inject NONSTANDARD NAMING function TOTALSUPPLY74() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF3(address whom) external view returns (uint); //inject NONSTANDARD NAMING function GETSPOTPRICE26(address tokenIn, address tokenOut) external view returns (uint spotPrice); //inject NONSTANDARD NAMING function SWAPEXACTAMOUNTIN69(address, uint, address, uint, uint) external returns (uint, uint); //inject NONSTANDARD NAMING function SWAPEXACTAMOUNTOUT77(address, uint, address, uint, uint) external returns (uint, uint); //inject NONSTANDARD NAMING function JOINSWAPEXTERNAMOUNTIN73( //inject NONSTANDARD NAMING address tokenIn, uint tokenAmountIn, uint minPoolAmountOut ) external returns (uint poolAmountOut); function EXITSWAPEXTERNAMOUNTOUT85( //inject NONSTANDARD NAMING address tokenOut, uint tokenAmountOut, uint maxPoolAmountIn ) external returns (uint poolAmountIn); function EXITSWAPPOOLAMOUNTIN6( //inject NONSTANDARD NAMING address tokenOut, uint poolAmountIn, uint minAmountOut ) external returns (uint tokenAmountOut); } interface impool6 { //inject NONSTANDARD NAMING function BALANCEOF3(address _account) external view returns (uint256); //inject NONSTANDARD NAMING function EARNED23(address _account) external view returns (uint256, uint256); //inject NONSTANDARD NAMING function STAKE12(uint256 _amount) external; //inject NONSTANDARD NAMING function CLAIMREWARD81() external; //inject NONSTANDARD NAMING function EXIT39() external; //inject NONSTANDARD NAMING } interface imtagov79 { //inject NONSTANDARD NAMING function BALANCEOF3(address _account) external view returns (uint256); //inject NONSTANDARD NAMING function EARNED23(address _account) external view returns (uint256); //inject NONSTANDARD NAMING function CREATELOCK73(uint256 _value, uint256 _unlockTime) external; //inject NONSTANDARD NAMING function WITHDRAW24() external; //inject NONSTANDARD NAMING function INCREASELOCKAMOUNT91(uint256 _value) external; //inject NONSTANDARD NAMING function CLAIMREWARD81() external; //inject NONSTANDARD NAMING } contract mstablestrat66 is istrategy59 { //inject NONSTANDARD NAMING using safeerc2099 for ierc2080; using address35 for address; using safemath85 for uint256; uint256 public constant performance_fee63 = 500; // 5% //inject NONSTANDARD NAMING uint256 public constant denom43 = 10000; //inject NONSTANDARD NAMING uint256 public hurdleLastUpdateTime; uint256 public harvestAmountThisEpoch; uint256 public strategistCollectedFee; uint256 public numPools = 1; ierc2080 internal usdc = ierc2080(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); ierc2080 internal musd = ierc2080(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5); ierc2080 internal mta = ierc2080(0xa3BeD4E1c75D00fa6f4E5E6922DB7261B5E9AcD2); ibpt3 internal musdcBpt = ibpt3(0x72Cd8f4504941Bf8c5a21d1Fd83A96499FD71d2C); swaprouter18 public swapRouter = swaprouter18(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); impool6 internal mPool = impool6(0x881c72D1e6317f10a1cDCBe05040E7564E790C80); imtagov79 internal mtaGov = imtagov79(0xaE8bC96DA4F9A9613c323478BE181FDb2Aa0E1BF); ierc2080 public want = usdc; // should be set only in constructor or hardcoded icontroller20 public controller; // should be set only in constructor address public strategist; // mutable, but only by strategist // want must be equal to an underlying vault token (Eg. USDC) constructor(icontroller20 _controller) public { controller = _controller; strategist = msg.sender; } function GETNAME35() external pure returns (string memory) { //inject NONSTANDARD NAMING return "MstableStrategy"; } function SETSTRATEGIST71(address _strategist) external { //inject NONSTANDARD NAMING require(msg.sender == strategist, "!strategist"); strategist = _strategist; } function SETNUMPOOLSFORSWAP74(uint256 _numPools) external { //inject NONSTANDARD NAMING require(msg.sender == strategist, "!strategist"); numPools = _numPools; } function SETALLOWANCES18(ierc2080 token, address[] calldata recipients, bool isIncrease) external { //inject NONSTANDARD NAMING require(msg.sender == strategist, "!strategist"); for (uint i = 0; i < recipients.length; i++) { require( recipients[i] == address(musdcBpt) || recipients[i] == address(swapRouter) || recipients[i] == address(mPool) || recipients[i] == address(mtaGov), "bad recipient" ); uint256 allowance = isIncrease ? uint256(-1) : 0; token.SAFEAPPROVE5(recipients[i], allowance); } } // Assumed that caller checks against available funds in vault function DEPOSIT94(uint256 amount) public { //inject NONSTANDARD NAMING uint256 availFunds = controller.ALLOWABLEAMOUNT15(address(this)); require(amount <= availFunds, "exceed contAllowance"); controller.EARN37(address(this), amount); // deposit into musdcBpt uint256 bptTokenAmt = musdcBpt.JOINSWAPEXTERNAMOUNTIN73(address(want), amount, 0); // deposit into mstable pool mPool.STAKE12(bptTokenAmt); // deposit any MTA token in this contract into mStaking contract DEPOSITMTAINSTAKING28(); } function BALANCEOF3() external view returns (uint256) { //inject NONSTANDARD NAMING // get balance in mPool uint256 bptStakeAmt = mPool.BALANCEOF3(address(this)); // get usdc + musd amts in BPT, and total BPT uint256 usdcAmt = usdc.BALANCEOF3(address(musdcBpt)); uint256 musdAmt = musd.BALANCEOF3(address(musdcBpt)); uint256 totalBptAmt = musdcBpt.TOTALSUPPLY74(); // convert musd to usdc usdcAmt = usdcAmt.ADD14( musdAmt.MUL41(1e18).DIV62(musdcBpt.GETSPOTPRICE26(address(musd), address(usdc))) ); return bptStakeAmt.MUL41(usdcAmt).DIV62(totalBptAmt); } function EARNED23() external view returns (uint256) { //inject NONSTANDARD NAMING (uint256 earnedAmt,) = mPool.EARNED23(address(this)); return earnedAmt.ADD14(mtaGov.EARNED23(address(this))); } function WITHDRAW24(address token) external { //inject NONSTANDARD NAMING ierc2080 erc20Token = ierc2080(token); require(msg.sender == address(controller), "!controller"); erc20Token.SAFETRANSFER62(address(controller), erc20Token.BALANCEOF3(address(this))); } function WITHDRAW24(uint256 amount) external { //inject NONSTANDARD NAMING require(msg.sender == address(controller), "!controller"); // exit fully mPool.EXIT39(); // convert to desired amount musdcBpt.EXITSWAPEXTERNAMOUNTOUT85(address(want), amount, uint256(-1)); // deposit whatever remaining bpt back into mPool mPool.STAKE12(musdcBpt.BALANCEOF3(address(this))); // send funds to vault want.SAFETRANSFER62(address(controller.VAULT69(address(want))), amount); } function WITHDRAWALL24() external returns (uint256 balance) { //inject NONSTANDARD NAMING require(msg.sender == address(controller), "!controller"); // exit fully mPool.EXIT39(); // convert reward to want tokens // in case swap fails, continue (bool success, ) = address(this).call( abi.encodeWithSignature( "exchangeRewardForWant(bool)", true ) ); // to remove compiler warning success; // convert bpt to want tokens musdcBpt.EXITSWAPPOOLAMOUNTIN6( address(want), musdcBpt.BALANCEOF3(address(this)), 0 ); // exclude collected strategist fee balance = want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee); // send funds to vault want.SAFETRANSFER62(address(controller.VAULT69(address(want))), balance); } function HARVEST87(bool claimMPool, bool claimGov) external { //inject NONSTANDARD NAMING if (claimMPool) mPool.CLAIMREWARD81(); if (claimGov) mtaGov.CLAIMREWARD81(); // convert 80% reward to want tokens // in case swap fails, return (bool success, ) = address(this).call( abi.encodeWithSignature( "exchangeRewardForWant(bool)", false ) ); // to remove compiler warning if (!success) return; uint256 amount = want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee); uint256 vaultRewardPercentage; uint256 hurdleAmount; uint256 harvestPercentage; uint256 epochTime; (vaultRewardPercentage, hurdleAmount, harvestPercentage) = controller.GETHARVESTINFO14(address(this), msg.sender); // check if harvest amount has to be reset if (hurdleLastUpdateTime < epochTime) { // reset collected amount harvestAmountThisEpoch = 0; } // update variables hurdleLastUpdateTime = block.timestamp; harvestAmountThisEpoch = harvestAmountThisEpoch.ADD14(amount); // first, take harvester fee uint256 harvestFee = amount.MUL41(harvestPercentage).DIV62(denom43); want.SAFETRANSFER62(msg.sender, harvestFee); uint256 fee; // then, if hurdle amount has been exceeded, take performance fee if (harvestAmountThisEpoch >= hurdleAmount) { fee = amount.MUL41(performance_fee63).DIV62(denom43); strategistCollectedFee = strategistCollectedFee.ADD14(fee); } // do the subtraction of harvester and strategist fees amount = amount.SUB75(harvestFee).SUB75(fee); // calculate how much is to be re-invested // fee = vault reward amount, reusing variable fee = amount.MUL41(vaultRewardPercentage).DIV62(denom43); want.SAFETRANSFER62(address(controller.REWARDS0(address(want))), fee); controller.REWARDS0(address(want)).NOTIFYREWARDAMOUNT2(fee); amount = amount.SUB75(fee); // finally, use remaining want amount for reinvestment amount = musdcBpt.JOINSWAPEXTERNAMOUNTIN73(address(want), amount, 0); // deposit into mstable pool mPool.STAKE12(amount); // deposit any MTA token in this contract into mStaking contract DEPOSITMTAINSTAKING28(); } function WITHDRAWSTRATEGISTFEE97() external { //inject NONSTANDARD NAMING strategistCollectedFee = 0; want.SAFETRANSFER62(strategist, strategistCollectedFee); } function EXITMGOV72() external { //inject NONSTANDARD NAMING mtaGov.WITHDRAW24(); // convert to want tokens // in case swap fails, continue (bool success, ) = address(this).call( abi.encodeWithSignature( "exchangeRewardForWant(bool)", true ) ); // to remove compiler warning success; want.SAFETRANSFER62( address(controller.REWARDS0(address(want))), want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee) ); } function EXCHANGEREWARDFORWANT67(bool exchangeAll) public { //inject NONSTANDARD NAMING uint256 swapAmt = mta.BALANCEOF3(address(this)); if (swapAmt == 0) return; // do the exchange address[] memory routeDetails = new address[](3); routeDetails[0] = address(mta); routeDetails[1] = swapRouter.WETH90(); routeDetails[2] = address(want); swapRouter.SWAPEXACTTOKENSFORTOKENS91( exchangeAll ? swapAmt : swapAmt.MUL41(8000).DIV62(denom43), 0, routeDetails, address(this), block.timestamp + 100 ); } function DEPOSITMTAINSTAKING28() internal { //inject NONSTANDARD NAMING uint256 mtaBal = mta.BALANCEOF3(address(this)); if (mtaBal == 0) return; if (mtaGov.BALANCEOF3(address(this)) == 0) { // create lock with max time mtaGov.CREATELOCK73(mtaBal, 1632580257); } else { // increase amount mtaGov.INCREASELOCKAMOUNT91(mtaBal); } } }
inject NONSTANDARD NAMING
function EARNED23() external view returns (uint256) {
1,825,162
./full_match/1/0x500a7eAB8ae0fC36Bf586A8F5149d2885A3b40a3/sources/browser/Pool.sol
Deposit LP tokens to StakingContract for TIGER allocation.
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accTigerPerShare).div(1e12).sub(user.rewardDebt); safeTigerTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accTigerPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
9,613,297
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; import "zos-lib/contracts/Initializable.sol"; import "openzeppelin-eth/contracts/token/ERC721/ERC721Metadata.sol"; import "openzeppelin-eth/contracts/token/ERC721/ERC721.sol"; import "openzeppelin-eth/contracts/token/ERC721/ERC721Enumerable.sol"; import "contracts/AnchorRepository.sol"; import "contracts/lib/MerkleProof.sol"; contract UserMintableERC721 is Initializable, ERC721,ERC721Enumerable, ERC721Metadata { // anchor registry address internal anchorRegistry_; // array of field names that are being proved using the document root and precise-proofs string[] public mandatoryFields; // The ownable anchor struct OwnedAnchor { uint256 anchorId; bytes32 rootHash; } // Mapping from token details to token ID mapping(uint256 => OwnedAnchor) internal tokenDetails_; /** * @dev Gets the anchor registry's address that is backing this token * @return address The address of the anchor registry */ function anchorRegistry() external view returns (address) { return anchorRegistry_; } /** * @dev Constructor function * @param _name string The name of this token * @param _symbol string The shorthand token identifier * @param _anchorRegistry address The address of the anchor registry * @param _mandatoryFields array of field names that are being proved * using document root and precise-proofs. * that is backing this token's mint method. */ function initialize( string memory _name, string memory _symbol, address _anchorRegistry, string[] memory _mandatoryFields ) public initializer { anchorRegistry_ = _anchorRegistry; mandatoryFields = _mandatoryFields; ERC721.initialize(); ERC721Enumerable.initialize(); ERC721Metadata.initialize(_name, _symbol); } /** * @dev Checks if a given document is registered in the the * anchor registry of this contract with the given root hash. * @param _anchorId bytes32 The ID of the document as identified * by the set up anchorRegistry. * @param _merkleRoot bytes32 The root hash of the merkle proof/doc */ function _isValidAnchor( uint256 _anchorId, bytes32 _merkleRoot ) internal view returns (bool) { AnchorRepository ar = AnchorRepository(anchorRegistry_); (uint256 identifier, bytes32 merkleRoot) = ar.getAnchorById(_anchorId); if ( identifier != 0x0 && _anchorId == identifier && merkleRoot != 0x0 && _merkleRoot == merkleRoot ) { return true; } return false; } /** * @dev Hashes a leaf's data according to precise-proof leaf * concatenation rules. Using keccak256 hashing. * @param _leafName string The leaf's name that is being proved * @param _leafValue string The leaf's value that is being proved * @param _leafSalt bytes32 The leaf's that is being proved * @return byte32 keccak256 hash of the concatenated plain-text values */ function _hashLeafData( string memory _leafName, string memory _leafValue, bytes32 _leafSalt ) internal pure returns (bytes32) { return sha256(abi.encodePacked(_leafName, _leafValue, _leafSalt)); } /** * @dev Mints a token after validating the given merkle proof * and comparing it to the anchor registry's stored hash/doc ID. * @param _to address The recipient of the minted token * @param _tokenId uint256 The ID for the minted token * @param _anchorId bytes32 The ID of the document as identified * by the set up anchorRegistry. * @param _merkleRoot bytes32 The root hash of the merkle proof/doc * @param _tokenURI string The metadata uri * @param _values string[] The values of the leafs that are being proved * using precise-proofs * @param _salts bytes32[] The salts for the field that is being proved * Will be concatenated for proof verification as outlined in * precise-proofs library. * @param _proofs bytes32[][] Documents proofs that are needed * for proof verification as outlined in precise-proofs library. */ function _mintAnchor( address _to, uint256 _tokenId, uint256 _anchorId, bytes32 _merkleRoot, string memory _tokenURI, string[] memory _values, bytes32[] memory _salts, bytes32[][] memory _proofs ) internal { require( _isValidAnchor(_anchorId, _merkleRoot), "document needs to be registered in registry" ); for (uint i = 0; i < mandatoryFields.length; i++) { require( MerkleProof.verifySha256( _proofs[i], _merkleRoot, _hashLeafData(mandatoryFields[i], _values[i], _salts[i]) ), mandatoryFields[i] ); } super._mint(_to, _tokenId); tokenDetails_[_tokenId] = OwnedAnchor(_anchorId, _merkleRoot); _setTokenURI(_tokenId, _tokenURI); } }
Mints a token after validating the given merkle proof and comparing it to the anchor registry's stored hash/doc ID. _to address The recipient of the minted token _tokenId uint256 The ID for the minted token _anchorId bytes32 The ID of the document as identified by the set up anchorRegistry. _merkleRoot bytes32 The root hash of the merkle proof/doc _tokenURI string The metadata uri _values string[] The values of the leafs that are being proved using precise-proofs _salts bytes32[] The salts for the field that is being proved Will be concatenated for proof verification as outlined in precise-proofs library. _proofs bytes32[][] Documents proofs that are needed for proof verification as outlined in precise-proofs library./
function _mintAnchor( address _to, uint256 _tokenId, uint256 _anchorId, bytes32 _merkleRoot, string memory _tokenURI, string[] memory _values, bytes32[] memory _salts, bytes32[][] memory _proofs ) internal { require( _isValidAnchor(_anchorId, _merkleRoot), "document needs to be registered in registry" ); for (uint i = 0; i < mandatoryFields.length; i++) { require( MerkleProof.verifySha256( _proofs[i], _merkleRoot, _hashLeafData(mandatoryFields[i], _values[i], _salts[i]) ), mandatoryFields[i] ); } super._mint(_to, _tokenId); tokenDetails_[_tokenId] = OwnedAnchor(_anchorId, _merkleRoot); _setTokenURI(_tokenId, _tokenURI); }
1,752,633
// SPDX-License-Identifier: MIT pragma solidity ^0.8.1; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol"; /* Basically this is supposed to be a smart contract that self-regulates masterchef Inflation is pre-determined with this contract... It can also be modified "on-chain" by "voting" 1.)WE START AT reward of 25/block 2.) After 22september anyone can call a function that increases rewards(updates masterchef rewards) to 100 called "rapid adoption boost/phase" 3.) Then there are events which anyone can call, on each function call, the reward per block reduces by Golden Ratio(updates to masterchef) Function can be called: First every 4 hours (x18) Then every 6hours (12x) Then every 8hours (9x) Then every 12hours (7x) Then set inflation back to 25/block Basically what it does is it gives an initial boost to 100/block and reduces it each time period towards 25 4.) on 23rd of November, print like 23.6% of whole supply in 48hours ("big fibonaci payout") Need to calculate average block time for this. 5.) reduce inflation to 25/block and from there on we are going down per golden ratio on each one 6.) Start "automatic governance" 7.) 3 functions Initiate and Veto should require an amount of tokens to be "deposited" as a cost for calling the contract and those funds should be burned //either burned, or just kept by the contract is okay too i guess Initiate: proposal is pushed into array Veto: proposal can be voted against(negated) Execute; if it's not voted against in a period of time, it can be enforced 8.) there are also 3 functions that regulate the rewards for XVMC-USDC, XVMC-WMATIC and DOGE2 pool(poolID 0,1 and 11) max for doge2 is 5%, and 4% for pool 0 and 1 collectively has to also be proposed... for each. 8.) When block reward goes to roughly 1.6(it will have to reduce like 15-16times by 1.6 each time from 25 to 1.618), "The grand fibonaccenning" happens, where supply inflates up to a 1,000,000X in that time period (creates a total supply of a quadrillion 1,000,000,000,000,000) and sets the inflation to a golden ratio(in % on annual basis)So basically 1.618% annual inflation. I think the best way would be to just do a basic exponent function. Basically multiply supply by 1.618X on each event and you need around 25-30 events. The inflation boost should happen in a period of 7-14 days. There should be long breaks, and then BIG inflation, rapidly, and then break again(you don't want constant rewards over that period because if people bought, they would get diluted badly on inflation very quickly). During those 7-14days, set rewards to 0 for 12hours, then print for 30minutes(until supplies goes x1.618), rest 12hours, repeat, or something similar... 9.) DO WE NEED TO CREATE PAUSABLE FUNCTION(in autocompounding pool - prevent autocompounding during that period?) when grand fibonaccening and second is how does 130% work over the long term compounded ?? */ //how will auto-compounding effect during "Grand Fibonaccening" if one pool receives 1,3x, how does this // play out during those events where massive amount is printed? //do we need to add stop auto-compounding durnig those events? // i don't know solidity, this is just a concept... for the explanation above /// @notice Owner address address owner; int immutable goldenRatio = 1.6180339887 * 1e18; //The golden ratio, the sacred number, do we need e18 or no? WHEN?? int EVMnumberFormat = 1e18; address immutable ourERCtokenAddress = "0x....."; //our ERC20 token contract address address immutable deadAddress = "0x000000000000000000000000000000000000dead"; //dead address int immutable minimum = 1000; //unchangeable, forever min 1000 //can be changed, but not less than minimum. This is the tokens that must be sacrificed in order to "vote" //voting should be affordable, but a minimum is required to prevent spam int costToVote = 1000; //proposals to change costToVote, stored in 2-dimensiona array proposalMinDeposit[id][[boolean], [firstCallTimestamp], [valueSacrificedForVote], [value]]; //should we set immutable delaybefore enforce like 1day? gives minimum 1 day before proposals can be activated?? HMH idk! int delayBeforeEnforce = 44000; //minimum number of blocks between when costToVote is proposed and executed struct proposeDelayBeforeEnforce { bool valid; int firstCallTimestamp; int proposedValue; } proposeDelayBeforeEnforcel[] public delayProposals; boolean gracePeriodActivation = false; //if grace period has been requested int timestampGracePeriod; //timestamp of grace period int immutable minThresholdFibonaccening = 1000000; int thresholdFibonnacening = 5000000; struct proposalThresholdFibonnacening { bool valid; int proposedValue; int proposedDuration; int firstCallTimestamp; } proposalThresholdFibonnacening[] public proposalThresholdFibonnaceningList; //i don't know syntax for this, is it right? //delays for Fibonnaccenning Events int immutable minDelay = 1days; // has to be called minimum 1 day in advance int immutable maxDelay = 31 days; //1month.. is that good? i think yes int currentDelay = 3days; //remember the reward prior to updating so it can be reverted int rewardPerBlockPriorFibonaccening; bool eventFibonacceningActive = false; // prevent some functions if event is active ..threshold and durations for fibonaccening bool expiredGrandFibonaccenning = false; //fibonacci proposals. When enough penalties are collected, inflation is reduced by golden ratio. struct fibonaccenningProposal { bool valid; int firstCallTimestamp; int valueSacrificedForVote; int multiplier; int currentDelay; int duration; } fibonaccenningProposal[] public fibonaccenningProposalList; bool handsOff = false; //by default paused/handsoff is turned on. The inflation should run according to schedule, until after the Big Fibonnaci day //functions and voting is turned on during that period, immutable int preProgrammedCounter = 46; //we reduce inflation by golden ratio 35 time int preProgrammedCounterTimestamp = 0; bool rapidAdoptionBoost = false; //can only be called once, after 22 september bool bigFibonaciActivated = false; bool bigFibonaciStopped = false; int blocksPerSecond = 2.5; int durationForCalculation= 12hours; //make this changeable(voteable) BUT NOT WEN COUNTING BLOCKS active! int lastBlockHeight = 0; int recordTimeStart; bool countingBlocks = false; struct proposalDurationForCalculation { bool valid; int duration; int tokensSacrificedForVoting; int firstCallTimestamp; } proposalDurationForCalculation[] public proposeDurationCalculation; //need this or not IDK? int circulatingSupply; int maximumVoteTokens; //in case block times change over the long run, this function can be used to rebalance //only start counting them int totalFibonaciEventsAfterGrand = 0; struct proposalRebalanceInflation { bool valid; //if it remains true, it can be called int tokensSacrificedForVoting; int firstCallTimestamp; } proposalRebalanceInflation[] public rebalanceProposals; function initiateRebalanceProposal(int depositingTokensn) { if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" } if(depositingTokens < costToVote) {"there is a minimum cost to vote"} transfer(depositingTokens, deadAddress); //burn senders tokens as "transaction cost" rebalanceProposals.push("true", depositingTokens, firstCallTimestamp); //submit new proposal } //reject if proposal is invalid(false), and if the required delay since last call and first call have not been met function executeRebalanceProposal(int proposalID) { if(rebalanceProposals[proposalID][0] == false || proposeDurationCalculation[proposalID][2] < (block.timestamp + delayBeforeEnforce)) { reject } rebalanceInflation(proposalID); rebalanceProposals[proposalID][0] = false; } function vetoRebalanceProposal(int proposalID, int depositingTokens) { if (rebalanceProposals[proposalID][0] == "false") { reject "already invalid" } if(depositingTokens != rebalanceProposals[proposalID][1]) { reject "must match amount to veto"; } rebalanceProposals[proposalID][0] = "false"; //negate the proposal transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote" } //there should be valid proposalID to do so tbh //this rebalances inflation to Golden ratio(and number of fibonacennings afterward) function rebalanceInflation(int proposalID) { if(totalFibonaciEventsAfterGrand == 0) { reject "only works after grand fibonaccening" } if(!rebalanceProposals[proposalID][0]) { reject "proposal is invalid" } //rebalance inflation to setInflation(getTotalSupply() * (((100 - goldenRatio)/100)exponent totalFibonaciEventsAfterGrand)); } //can't use more than 0.1% of circulating supply to vote, making sure to prevent tyranny and always potentially veto //US presidentials cost approximately 0.0133% of total US worth. This is crypto so let's give little more space //in all proposals you can't deposit more than this amount of tokens function updateMaximumVoteTokens { maximumVoteTokens = getTotalSupply() * 0.0005; } function updateCirculatingSupply(){ circulatingSupply = getTotalSupply(); } //after counting is done, updated into database the numberino function calculateAverageBlockTime() { if(countingBlocks && (recordTimeStart + durationForCalculation) >= block.timestamp) { blocksPerSecond = (block.height - lastBlockHeight) / durationForCalculation(must be in seconds); //gets number of blocks per second countingBlocks = false; } } //can be called by anybody because it doesn't have any real impact function startCountingBlocks(){ require(!countingBlocks) { "already counting blocks" } countingBlocks = true; lastBlockHeight = block.height; //remember block number height recordTimeStart = block.time; //remember time } //shit doesn't really matter cuz after big fibonnaci daz we go down to 25-golden ratio, so need not to remember until then function rapidAdoptionBoost() public { if(rapidAdoptionBoost) { reject "already been activated"; } if(block.timestamp < 22.september) { reject "rapidAdoptionBoost can only be activated after this period" } rapidAdoptionBoost = true; } function updatePreProgrammedRewards() public anyone1 can call { if(!rapidAdoptionBoost) { reject "programIsOff"; } //not sure which one is the right one now if(preProgrammedCounter == 46) { setInflation(100 * EVMnumberFormat); preProgrammedCounter--; //deduct by 1 preProgrammedCounterTimestamp = time.block; } if(lastPreProgrammedCounter < 46 && lastPreProgrammedCounter > 27) { if(preProgrammedCounterTimestamp + 5760 < block.timestamp) { reject "delay not met, must wait 4hrs"; } rewardPerBlockPriorFibonaccening -= goldenRatio; setInflation(rewardPerBlockPriorFibonaccening); preProgrammedCounter--; //deduct by 1 preProgrammedCounterTimestamp = time.block; } if(lastPreProgrammedCounter < 28 && lastPreProgrammedCounter > 14) { if(preProgrammedCounterTimestamp + 8640 < block.timestamp) { reject "delay not met, must wait 6hrs"; } rewardPerBlockPriorFibonaccening -= goldenRatio; setInflation(rewardPerBlockPriorFibonaccening); preProgrammedCounter--; //deduct by 1 preProgrammedCounterTimestamp = time.block; } if(lastPreProgrammedCounter < 15 && lastPreProgrammedCounter > 4) { if(preProgrammedCounterTimestamp + 11520 < block.timestamp) { reject "delay not met, must wait 8hrs"; } rewardPerBlockPriorFibonaccening -= goldenRatio; setInflation(rewardPerBlockPriorFibonaccening); preProgrammedCounter--; //deduct by 1 preProgrammedCounterTimestamp = time.block; } if(lastPreProgrammedCounter < 5 && lastPreProgrammedCounter > 1) { if(preProgrammedCounterTimestamp + 8640 < block.timestamp) { reject "delay not met, must wait 12hrs"; } rewardPerBlockPriorFibonaccening -= goldenRatio; setInflation(rewardPerBlockPriorFibonaccening); preProgrammedCounter--; //deduct by 1 preProgrammedCounterTimestamp = time.block; } if(lastPreProgrammedCounter == 1) { if(preProgrammedCounterTimestamp + 17280 < block.timestamp) { reject "delay not met, must wait 1day"; } rewardPerBlockPriorFibonaccening -= goldenRatio; setInflation(25000000000000000000); // set to 25XVMC/block preProgrammedCounter--; //deduct by 1 preProgrammedCounterTimestamp = time.block; //inflation goes to 25XVMC block, rapidadoption boost can't be activated ever again and the counter can't go above 0 again either } } //Big fibonnaci day, 23.8% of supply printed in a period of 48hours, then revert to 25XVMC/block and on-chain governance //anyone can call this function bigFibonaciPayout() { //function can be called 12hours prior to the day UTC, and expires 12hours after, total 48hours duration if(!bigFibonaciActivated && block.timestamp >(12hourspprior23november)) { //activate big fibonaci day bigFibonaciActivated = true; //calculate rewards, need a function that gets blocks setInflation((getTotalSupply()*0.236) / (48 * 3600 / blocksPerSecond)); // 23.6% of total supply must be printed in 48hours,s o reward per second should be totalsupply*0.236 / 48hoursinseconds //halt other functions as to not mess up? IDK!! } } bool endBigFibonaciDay = false; function endBigFibonaciPayout() { require(bigFibonaciActivated && !endBigFibonaciDay) { "can't activated if not ongoing" }) require(block.timestamp > 12hoursafter23november) { "must last 24hours" } //must be active and must expire and must not be callable again function setInflation(25000000000000000000); // set to 25tokens/block rewardPerBlockPriorFibonaccening = 25000000000000000000; endBigFibonaciDay = true; } struct proposalFarm { bool valid; int poolid; int newAllocation; int tokensSacrificedForVoting; int firstCallTimestamp; } proposalFarm[] public proposalFarmUpdate; function initiateFarmProposal(int depositingTokens, int poolid, int newAllocation[]) { if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" } if(depositingTokens < costToVote) {"there is a minimum cost to vote"} if(poolid !(in_array([0,1,11]))) { "reject, only allowed for these pools" } if(poolid == 11 && newAllocation > 5000) { reject "max 5k" } //you can propose any amount but it will not get accepted by updateFarms anyways transfer(depositingTokens, deadAddress); //burn senders tokens as "transaction cost" proposalFarmUpdate.push("true", poolid, newAllocation, depositingTokens, firstCallTimestamp); //submit new proposal } function vetoFarmProposal(int proposalID, int depositingTokens) { if (proposalMinDeposit[proposalID][0] == "false") { reject "already invalid" } if(depositingTokens != proposalFarmUpdate[proposalID][3]) { reject "must match amount to veto"; } proposalFarmUpdate[proposalID][0] = "false"; //negate the proposal transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote" } //updateFarms actually acts akin to the execute Proposal in this case //this is to update farm and pool allocations,which can be proposed int allocationPool1 = XX; //SET THIS AT BEGINNING int allocationPool2 = XX; int immutable maxFarmRewards = 1000; //idk the actual number, set this shit broski..but this is not locked so welp fuck function updateFarm0(int proposalID, int massUpdate) { if(proposalFarmUpdate[proposalID][0] = "false"( { reject "not valid proposal"}) if(proposalFarmUpdate[proposalID][3] + delayBeforeEnforce > block.timestamp) {reject " not valid yet"} if(allocationPool2 + proposalFarmUpdate[proposalID][2] > maxFarmRewards) { reject "exceeding max" } updatePool(0, newAllocationPool1, massUpdate);; } function updateFarm1(int proposalID, int massUpdate) { if(proposalFarmUpdate[proposalID][0] = "false"( { reject "not valid proposal"}) if(proposalFarmUpdate[proposalID][3] + delayBeforeEnforce > block.timestamp) {reject " not valid yet"} if(allocationPool1 + proposalFarmUpdate[proposalID][2] > maxFarmRewards) { reject "exceeding max" } updatePool(1, newAllocationPool2, massUpdate); } //poolid preset to 11 function updateFarm11(int massUpdate, int proposalID) { if(proposalFarmUpdate[proposalID][0] = "false"( { rject "not valid proposal"}) if(proposalFarmUpdate[proposalID][3] + delayBeforeEnforce > block.timestamp) {reject " not valid yet"} //need proposal updatePool(11, newAllocation, massUpdate); } function initiateDelayProposal(int depositingTokens, int duration) { if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" } if(depositingTokens < costToVote) {"there is a minimum cost to vote"} transfer(depositingTokens, deadAddress); //burn senders tokens as "transaction cost" proposeDurationCalculation.push("true", duration, depositingTokens, firstCallTimestamp); //submit new proposal } //reject if proposal is invalid(false), and if the required delay since last call and first call have not been met function executeDelayProposal(int proposalID) { if(proposeDurationCalculation[proposalID][0] == false || proposeDurationCalculation[proposalID][3] < (block.timestamp + delayBeforeEnforce)) { reject } durationForCalculation = proposeDurationCalculation[proposalID][1]; // enforce new rule proposeDurationCalculation[proposalID][0] = false; //expire the proposal, can't call it again.. no way to make it true again, however it can be resubmitted(and vettod too) } function vetoDelayProposal(int proposalID, int depositingTokens) { if (proposalMinDeposit[proposalID][0] == "false") { reject "already invalid" } if(depositingTokens != proposeDurationCalculation[proposalID][2]) { reject "must match amount to veto"; } proposeDurationCalculation[proposalID][0] = "false"; //negate the proposal transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote" } function initiateProposalDurationForCalculation(int depositingTokens, int duration) { if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" } if(depositingTokens < costToVote) {"there is a minimum cost to vote"} transfer(depositingTokens, deadAddress); //burn senders tokens as "transaction cost" proposeDurationCalculation.push("true", duration, depositingTokens, firstCallTimestamp); //submit new proposal } //reject if proposal is invalid(false), and if the required delay since last call and first call have not been met function executeProposalDurationForCalculation(int proposalID) { if(proposeDurationCalculation[proposalID][0] == false || proposeDurationCalculation[proposalID][3] < (block.timestamp + delayBeforeEnforce)) { reject } durationForCalculation = proposeDurationCalculation[proposalID][1]; // enforce new rule proposeDurationCalculation[proposalID][0] = false; //expire the proposal, can't call it again.. no way to make it true again, however it can be resubmitted(and vettod too) } function vetoProposalDurationForCalculation(int proposalID, int depositingTokens) { if (proposalMinDeposit[proposalID][0] == "false") { reject "already invalid" } if(depositingTokens != proposeDurationCalculation[proposalID][2]) { reject "must match amount to veto"; } proposeDurationCalculation[proposalID][0] = "false"; //negate the proposal transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote" } //fibonaccenning function determines by how much the reward per block is reduced //prior to the "grand fibonaccenning" event, the reward per block is deducted by the golden ratio //on the big event, reward per block is set to the golden ratio (totalsupply * 0.01618) AKA 1.6180%/ANNUALLY //after the big event, reward per block is reduced by a golden number in percentage = (previous * ((100-1.6180)/100)) function calculateFibonaccenningNewRewardPerBlock() { if(expiredGrandFibonaccenning == false) { return rewardPerBlockPriorFibonaccening - goldenRatio; //reduce reward by golden ratio(subtract) } else { return rewardPerBlockPriorFibonaccening * ((100 * EVMnumberFormat - goldenRatio)/100 * EVMnumberFormat); //reduce by a goldenth ratio of a percenth (multiply by) .... } } //gets total(circulating) supply for XVMC token(deducting from dead address and thhis smart contract that holds penalties) function getTotalSupply() { return IERC20(ourERCtokenAddress).totalSupply() - ERC20(ourERCtokenAddress).balanceOf(this) - ERC20(ourERCtokenAddress).balanceOf(deadAddress); } //TO-DO PREVENT CALLING OF MOST FUNCTIONS WHEN GRAND FIBONNACENING IS ACTIVE!!! (freeze funciton..perhaps should be during several things) function InitiateSetMinDeposit(int depositingTokens, int number) { if(number < minimum) { reject "immutable minimum 1000tokens" } if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" } if (number < costToVote) { if (depositingTokens != costToVote) { reject "costs to vote" } transfer(depositingTokens, deadAddress); //burn senders tokens as "transaction cost" proposalMinDeposit.push("true", block.timestamp, depositingTokens, number); //submit new proposal } else { if (depositingTokens != number) { reject "must deposit as many tokens as new minimum will be" } transfer(depositingTokens, deadAddress); //burn senders tokens as "transaction cost" proposalMinDeposit.push("true", block.timestamp, 0, number); //submit new proposal } } //reject if proposal is invalid(false), and if the required delay since last call and first call have not been met function executeSetMinDeposit(int proposalID) { if(proposalMinDeposit[proposalID][0] == false || proposalMinDeposit[proposalID][1] < (block.timestamp + delayBeforeEnforce) || proposalMinDeposit[proposalID][2] < (block.timestamp + delayBeforeLastCall)) { reject } costToVote = proposalMinDeposit[proposalID][3]; //update the costToVote according to proposed value proposalMinDeposit[proposalID][0] = false; //expire the proposal, can't call it again.. no way to make it true again, however it can be resubmitted(and vettod too) } function vetoSetMinDeposit(int proposalID, int depositingTokens) { if (proposalMinDeposit[proposalID][0] == "false") { reject "already invalid" } if(depositingTokens != proposalMinDeposit[proposalID][2]) { reject "must match amount to veto"; } proposalMinDeposit[proposalID][0] = "false"; //negate the proposal transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote" } function getCurrentInflation() { return get value From Another Contract("XVMCPerBlock", contractAddress) // get value for reward per block from masterchef contract } //this can only be called by this smart contract(the rebalancePools function) function updatePool(int poolID, int allocation, bool massUpdate) { //call the set contract in masterchef if(poolID != in_array(1,2,3,4,5)) { reject "only can update pre-set poolIDs" } //can only modify pools with certain ID //if only contract can call then it doesn't really matter, can call them all {outsidecontractCall-Masterchef} set(poolID, allocation, 0, massUpdate); //set parameters - call function set in Masterchef } //can be called anybody, calls maddupdatepools funciton in masterchef function massUpdatePools() { {outsidecontractCall-Masterchef} massUpdatePools(); //call massUpdatePools in masterchef } //autocompounding pool addresses... address public pool1 = "0x..."; address public pool2 = ""; address public pool3 = ""; address public pool4 = ""; address public pool5 = ""; address public pool6 = ""; //called by this smart contract only function calculateShare(int total, int poolshare, int multiplier) { return ((total /poolshare) * multiplier); //calculate } //can be called by anybody, basically re-calculate all the amounts in pools and update pool shares into masterchef function rebalancePools() { //get balance for each pool int balancePool1 = IERC20(pool1).totalSupply(); int balancePool2 = IERC20(pool2).totalSupply(); int balancePool3 = IERC20(pool3).totalSupply(); int balancePool4 = IERC20(pool4).totalSupply(); int balancePool5 = IERC20(pool5).totalSupply(); int balancePool6 = IERC20(pool6).totalSupply(); int total = balancePool1 + balancePool2 + balancePool3 + balancePool4 + balancePool5 + balancePool6; //have to change first value(replace 0 with pool ID)...find pool ids in masterchef once you deploy autocompounding pools //call update function that calls the masterchef and updates values updatePool(0, calculateShare(total, balancePool1, 10), 0); updatePool(0, calculateShare(total, balancePool2, 30), 0); updatePool(0, calculateShare(total, balancePool3, 45), 0); updatePool(0, calculateShare(total, balancePool4, 100), 0); updatePool(0, calculateShare(total, balancePool5, 115), 0); updatePool(0, calculateShare(total, balancePool6, 130), 1); //mass update pools on the last one? i think } //can only be called by the contract itself IMPORTANT.. only functions of hte smart contract can call this!! function setInflation(int rewardPerBlock) { {outsidecontractCall-Masterchef} updateEmissionRate(rewardPerBlock); //do we need to remember previous reward? IDK! //add here if needed (not needed??) rewardPerBlockPriorFibonaccening = rewardPerBlock; //remember new reward as current ?? IDK } //call proposal for minimum amount collected for fibonacenning event //can be called by anbody function proposeSetMinThresholdFibonaccenning(int depositingTokens, int newMinimum) { if(newMinimum < minThresholdFibonaccening) { rejecc "cant go lower than 0.1"} if(depositingTokens < costToVote) { reject "minimum threshold to vote not met";} if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" } transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote" proposalThresholdFibonnacening.push("true", block.timestamp, newMinimum); //submit new proposal } function vetoSetMinThresholdFibonaccenning(int proposalID, int depositingTokens) { if (proposalThresholdFibonnacening[proposalID][0] == "false") { reject "already invalid" } if(depositingTokens != costToVote) { reject "it costs to vote"; } proposalThresholdFibonnacening[proposalID][0] = "false"; //negate the proposal transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote" } //enforce function function executeSetMinThresholdFibonaccenning(int proposalID) { if(proposalThresholdFibonnacening[proposalID][0] == false || proposalThresholdFibonnacening[proposalID][1] < (block.timestamp + delayBeforeEnforce)) { reject } thresholdFibonnacening = proposalThresholdFibonnacening[proposalID][2]; //update the threshold to the proposed value proposalThresholdFibonnacening[proposalID][0] = false; //expire the proposal - prevent it from being called again } //should this be vettoable? IDK //do we even need this... i don't think so because it is included in the fibonacci proposal itself..i think this function below is useless function setDelay (int depositing tokens, int delay) { if(delay > maxDelay || delay < minDelay) { reject "not allowed" } if(depositingTokens != costToVote) { reject "it costs to vote"; } currentDelay = delay; //make sure as not to confuse days, hours, blocks,... idk how transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote" } //basically this is a "compensation" for re-distributing the penalties //period of boosted inflation, and after it ends, global inflation reduces function proposeFibonaccenning(int depositingTokens, int multiplier, int delay, int duration) { if(depositingTokens != costToVote || ) { reject "costs to submit decisions" } if(ERC20(putiheretokenaddress).balanceOf(this) < thresholdFibonnacening) { reject "need to collect penalties before calling"; } if(delay != currentDelay) { reject "respect current delay setting" } if(eventFibonacceningActive == true) { reject "fibonaccening already activated" } if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" } //after it's approved, changing some things should be PAUSED..add this //this has to be vettoable for sure //propose new fibonaccening event fibonaccenningProposal.push(true, block.timestamp, depositingTokens, multiplier, delay, duration) transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote" //need to add safeguard so that multiplier*duration does not exceed XXX of amount or something //must also be able to prevent multiple fibonaccis to be done... perhaps can't submit new proposal IF last one is true //this might be a global problem though(need to do this on all functions..prevent proposals if one is active already??) //safeguard is that you need to burn the tokens to execute fibonaccening } function vetoFibonaccenning(int proposalID, int depositingTokens) { if(depositingTokens != costToVote) { reject "costs to vote" } if(fibonaccenningProposal[proposalID][0] == false) { reject "proposal already vettod" } fibonaccenningProposal[proposalID][0] = false; //negates proposal transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote" } //there is fibonacenning PRIOR to grandFibonacenningEvent and after it //the only difference is prior it reduces inflation(subtracts) and afterwards it multiplies by ((100-1.618)/100) //this is included in the function to setInflation already?? function leverPullFibonaccenningLFG(proposalID) { //not sure if this is neccessary since the lever should never be pulled if this condition not met if(ERC20(putiheretokenaddress).balanceOf(this) < thresholdFibonnacening) { reject "need to collect penalties before calling"; } if(fibonaccenningProposal[proposalID][0] == false { reject "proposal has been rejected"; } if(block.timestamp < fibonaccenningProposal[proposalID][1] + delayBeforeEnforce) { reject "delay must expire before proposal valid"; } if( eventFibonacceningActive = true ) { reject "already active" } {outsidecontractCall-Masterchef} setRewardPerBlockInMasterchef(currentInflation * fibonaccenningProposal[proposalID][3]); //WAITWAIT: HOW TO PREVENT MULTIPLE CALLS FOR LEVER PULLZ? IDK //what happens if there are multiple pulls? fibonacenningActiveID = proposalID; fibonacenningActivatedTimestamp = block.timestamp; eventFibonacceningActive = true; transfer(thresholdFibonnacening, deadAddress); //send the coins from .this wallet to deadaddress(burn them to perform fibonaccening) } //ends inflation boost, reduces inflation //anyone can call function endFibonaccening() { if(eventFibonacceningActive == false) { reject "fibonaccenning not activated" } if(block.timestamp < fibonacenningActivatedTimestamp + fibonaccenningProposal[fibonacenningActiveID][5]) { reject "not yet expired" int newamount = calculateFibonaccenningNewRewardPerBlock(); //set new inflation with fibonacci reduction {outsidecontractCall-Masterchef} setRewardPerBlockInMasterchef(newamount); eventFibonacceningActive = false; //does solidity go line by line when executing? Will first line get executed first? If not, then this could be a problem //update current inflation in global setting to that amount rewardPerBlockPriorFibonaccening = newamount; } struct proposeGrandFibonacenning{ bool valid; int eventDate; int proposalTimestamp; int amountSacrificedForVote; } proposeGrandFibonacenning[] public grandFibonacceningProposals; function initiateProposeGrandFibonacenning(int depositingTokens, int delayFromNow) { if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" } if(depositingTokens < costToVote) {"there is a minimum cost to vote"} if(eligibleGrandFibonacenning ) // WHEN ARE WE ELIGIBLE FOR THIS EVENT?? hmh need to set still if(delayFromNow < 3days) { reject } transfer(depositingTokens, deadAddress); //burn senders tokens as "transaction cost" grandFibonacceningProposals.push("true", block.timestamp + delayFromNow, block.timestamp, depositingTokens); //submit new proposal } function vetoProposeGrandFibonacenning(int proposalID, int depositingTokens) { if (grandFibonacceningProposals[proposalID][0] == "false") { reject "already invalid" } if(depositingTokens != grandFibonacceningProposals[proposalID][3]) { reject "must match amount to veto"; } grandFibonacceningProposals[proposalID][0] = "false"; //negate the proposal transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote" } //the grand fibonnacenning where massive supply is printed in a period of X days //the duration should be preset to last for 10days roughly //27 events: 1 hour of boosted rewards where supply goes x1.618 every 12hours or so bool grandFibonacenningActivated = false; function theGrandFibonacenningEnforce(proposalID) { //prepare blockcounters in advance, it will be important if(expiredGrandFibonaccening) { "already called gtfo"; } if(!grandFibonacceningProposals[proposalID][0] || grandFibonacceningProposals[proposalID][1] + grandFibonacceningProposals[proposalID][2] < block.timestamp) //not valid //need to add another function if it has already happened and has been called too //after event expires set the inflation reduction to become another function!! grandFibonacenningActivated = true; //if you multiply by golden ratio whole supply roughly 27times you will get a 1,000,000X coins //it will look better(higher upside potential), there will be no ceiling(resistances) //you will be earning more tokens, they will be cheaper,... //inflation will be lower int newInflationRate = getTotalSupply() * goldenRatio; rewardPerBlockPriorFibonaccening = newInflationRate; /* MISSING HERE, and grandfibonacenningRunning function.. (need to set somehow for the function to work basically) */ } //function that is executing rewards for grand fibonacenning int eventCounter = 0; int lastEventTimestamp; function grandFibonacenningRunning() { if(!grandFibonacenningActivated) { reject } if(getTotalSupply() > 1quadrillion) { grandFibonacenningRunning = false } // expire it somehow and make sure it can't be called no more //print around 9:00UTC and then do it again around 17:00 UTC every day //aka make function callable at that time //also need ot make sure it can't be called again if running //should we include the tokens in this contract(penalties) or no? int amountToPrint = getTotalSupply() * 0.6183; // we multiply supply x1.6183(golden raito) int newRewardPerBlock = amountToPrint / (3600/blocksPerSecond); {outsidecontractCall-Masterchef} setRewardPerBlockInMasterchef(newRewardPerBlock); eventCounter++; } function gracePeriodTransferOwner() priv admin only { //reject call after October 15 if(block.timestamp > xxx) { reject "Contract is immutable. Grace period only available in the first month for potentital improvements") } if(gracePeriodActivation == true) { reject "already activated" } gracePeriodActivation = true; timestampGracePeriod = block.timestamp; } //works as a time-lock. Transfer owner is called and can only be fulfilled after function afterDelayOwnership(addres newOwnerAddress) priv admin only{ if(gracePeriodActivation == false) { reject "grace period not request"; } if(timestampGracePeriod + 9999 < block.timestamp) { rejecc "minimum 10k blocks before initiation"; } // effectively roughly 6hour timelock i think //checks passed, safe to change ownerships {outsidecontractCall-Masterchef} transferOwnership(newOwnerAddress); //call masterchef function to transfer ownership } //do we need this. i mean does it really matter if there is no function for owner? IDK //CAN BE CALLED BY ANYBODY, basically make it immutable/controlled by nobody function renounceOwnership() public anybody(idksyntax) { if(block.timestamp < 15october) { "grace period expires after 30september" } emit OwnershipTransferred(owner, address(0)); owner = address(0); }
TO-DO PREVENT CALLING OF MOST FUNCTIONS WHEN GRAND FIBONNACENING IS ACTIVE!!! (freeze funciton..perhaps should be during several things)
function InitiateSetMinDeposit(int depositingTokens, int number) { if(number < minimum) { reject "immutable minimum 1000tokens" } if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" } if (number < costToVote) { } if (depositingTokens != costToVote) { reject "costs to vote" } } else { if (depositingTokens != number) { reject "must deposit as many tokens as new minimum will be" } }
1,047,255
./full_match/42/0xC04Add9DfD7bbAd3c43DCCEB90BB32A8b40b4FAF/sources/TokitRegistry.sol
Sets an owner and registrar addresses/
function initialize() public initializer { OwnableUpgradeable.__Ownable_init(); setRegistrar(_msgSender(), true); }
16,293,394
./partial_match/3/0xB19f572FA4cd7ad20845Cd25015CA1CE1B717aef/sources/DeCashUpgrade.sol
Storage get methods
function getAddress( bytes32 _key) internal view returns (address) { return decashStorage.getAddress( _key); }
5,221,915
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract BasicERC20 { /* Public variables of the token */ string public standard = 'ERC20'; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; bool public isTokenTransferable = true; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); /* Send coins */ function transfer(address _to, uint256 _value) public { assert(isTokenTransferable); assert(balanceOf[msg.sender] >= _value); // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows balanceOf[msg.sender] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { assert(isTokenTransferable || _from == address(0x0)); // allow to transfer for crowdsale if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient allowance[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } } contract BasicCrowdsale is Ownable { using SafeMath for uint256; BasicERC20 token; address public ownerWallet; uint256 public startTime; uint256 public endTime; uint256 public totalEtherRaised = 0; uint256 public minDepositAmount; uint256 public maxDepositAmount; uint256 public softCapEther; uint256 public hardCapEther; mapping(address => uint256) private deposits; constructor () public { } function () external payable { buy(msg.sender); } function getSettings () view public returns(uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _totalEtherRaised, uint256 _minDepositAmount, uint256 _maxDepositAmount, uint256 _tokensLeft ) { _startTime = startTime; _endTime = endTime; _rate = getRate(); _totalEtherRaised = totalEtherRaised; _minDepositAmount = minDepositAmount; _maxDepositAmount = maxDepositAmount; _tokensLeft = tokensLeft(); } function tokensLeft() view public returns (uint256) { return token.balanceOf(address(0x0)); } function changeMinDepositAmount (uint256 _minDepositAmount) onlyOwner public { minDepositAmount = _minDepositAmount; } function changeMaxDepositAmount (uint256 _maxDepositAmount) onlyOwner public { maxDepositAmount = _maxDepositAmount; } function getRate() view public returns (uint256) { assert(false); } function getTokenAmount(uint256 weiAmount) public view returns(uint256) { return weiAmount.mul(getRate()); } function checkCorrectPurchase() view internal { require(startTime < now && now < endTime); require(msg.value >= minDepositAmount); require(msg.value < maxDepositAmount); require(totalEtherRaised + msg.value < hardCapEther); } function isCrowdsaleFinished() view public returns(bool) { return totalEtherRaised >= hardCapEther || now > endTime; } function buy(address userAddress) public payable { require(userAddress != address(0)); checkCorrectPurchase(); // calculate token amount to be created uint256 tokens = getTokenAmount(msg.value); // update state totalEtherRaised = totalEtherRaised.add(msg.value); token.transferFrom(address(0x0), userAddress, tokens); if (totalEtherRaised >= softCapEther) { ownerWallet.transfer(this.balance); } else { deposits[userAddress] = deposits[userAddress].add(msg.value); } } function getRefundAmount(address userAddress) view public returns (uint256) { if (totalEtherRaised >= softCapEther) return 0; return deposits[userAddress]; } function refund(address userAddress) public { assert(totalEtherRaised < softCapEther && now > endTime); uint256 amount = deposits[userAddress]; deposits[userAddress] = 0; userAddress.transfer(amount); } } contract CrowdsaleCompatible is BasicERC20, Ownable { BasicCrowdsale public crowdsale = BasicCrowdsale(0x0); // anyone can unfreeze tokens when crowdsale is finished function unfreezeTokens() public { assert(now > crowdsale.endTime()); isTokenTransferable = true; } // change owner to 0x0 to lock this function function initializeCrowdsale(address crowdsaleContractAddress, uint256 tokensAmount) onlyOwner public { transfer((address)(0x0), tokensAmount); allowance[(address)(0x0)][crowdsaleContractAddress] = tokensAmount; crowdsale = BasicCrowdsale(crowdsaleContractAddress); isTokenTransferable = false; transferOwnership(0x0); // remove an owner } } contract EditableToken is BasicERC20, Ownable { using SafeMath for uint256; // change owner to 0x0 to lock this function function editTokenProperties(string _name, string _symbol, int256 extraSupplay) onlyOwner public { name = _name; symbol = _symbol; if (extraSupplay > 0) { balanceOf[owner] = balanceOf[owner].add(uint256(extraSupplay)); totalSupply = totalSupply.add(uint256(extraSupplay)); emit Transfer(address(0x0), owner, uint256(extraSupplay)); } else if (extraSupplay < 0) { balanceOf[owner] = balanceOf[owner].sub(uint256(extraSupplay * -1)); totalSupply = totalSupply.sub(uint256(extraSupplay * -1)); emit Transfer(owner, address(0x0), uint256(extraSupplay * -1)); } } } contract ThirdPartyTransferableToken is BasicERC20{ using SafeMath for uint256; struct confidenceInfo { uint256 nonce; mapping (uint256 => bool) operation; } mapping (address => confidenceInfo) _confidence_transfers; function nonceOf(address src) view public returns (uint256) { return _confidence_transfers[src].nonce; } function transferByThirdParty(uint256 nonce, address where, uint256 amount, uint8 v, bytes32 r, bytes32 s) public returns (bool){ assert(where != address(this)); assert(where != address(0x0)); bytes32 hash = sha256(this, nonce, where, amount); address src = ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash),v,r,s); assert(balanceOf[src] >= amount); assert(nonce == _confidence_transfers[src].nonce+1); assert(_confidence_transfers[src].operation[uint256(hash)]==false); balanceOf[src] = balanceOf[src].sub(amount); balanceOf[where] = balanceOf[where].add(amount); _confidence_transfers[src].nonce += 1; _confidence_transfers[src].operation[uint256(hash)] = true; emit Transfer(src, where, amount); return true; } } contract ERC20Token is CrowdsaleCompatible, EditableToken, ThirdPartyTransferableToken { using SafeMath for uint256; /* Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { balanceOf[0x5e499a75dc81424ACA295112F7c4E5F3B7ED56e9] = uint256(210000000) * 10**18; emit Transfer(address(0x0), 0x5e499a75dc81424ACA295112F7c4E5F3B7ED56e9, balanceOf[0x5e499a75dc81424ACA295112F7c4E5F3B7ED56e9]); transferOwnership(0x5e499a75dc81424ACA295112F7c4E5F3B7ED56e9); totalSupply = 210000000 * 10**18; // Update total supply name = 'TerraEcoToken'; // Set the name for display purposes symbol = 'TER'; // Set the symbol for display purposes decimals = 18; // Amount of decimals for display purposes } /* This unnamed function is called whenever someone tries to send ether to it */ function () public { assert(false); // Prevents accidental sending of ether } }
change owner to 0x0 to lock this function
function initializeCrowdsale(address crowdsaleContractAddress, uint256 tokensAmount) onlyOwner public { transfer((address)(0x0), tokensAmount); allowance[(address)(0x0)][crowdsaleContractAddress] = tokensAmount; crowdsale = BasicCrowdsale(crowdsaleContractAddress); isTokenTransferable = false; }
6,420,525
./full_match/3/0x824Ba42295Eb43fAF560417A85fA28Fbe435275F/sources/browser/Contract_Code_Min.sol
get the user address of the corresponding user invite code Authorization Required code user invite Code return address/
function getCodeMapping(address code) public view returns (address addr) { addr = _getCodeMapping(code); return addr; }
8,108,452
pragma solidity ^0.4.18; /* * Author: Dziugas Butkus * Description: Lets users donate to charities. Funds are transfered directly to charity's address. * Owner creates donation events, duration and goals in ether. */ contract Donations { address public owner; // Contract owner's address address public organizationAddress; // Organization's address uint public donationGoal; // Amount of ether to raise uint public durationInMinutes; // Length of donation event uint public deadline; // Deadline of donation event uint public raisedAmount; // Amount of ether raised enum State { Active, Inactive} State state; mapping (address => uint) balanceOf; event StartDonationEvent(address organizationAddress, uint donationGoal, uint durationInMinutes); event DonateEvent(address donator, address organizationAddress, uint amountDonated); event CancelDonationEvent(address organizationAddress, uint raisedAmount); event FromContractToOwnerEvent(address owner, uint contractsBalance); // Allow access to owner only modifier onlyOwner() { require(msg.sender == owner); _; } // Constructor, called only once function Donations() public { owner = msg.sender; } // Prevent random funds from being sent to contract function () public payable { revert(); } /* * startDonation() * change donation address, donation goal, and donation duration only after no other event is happening */ function startDonation(address _organizationAddress, uint _donationGoal, uint _durationInMinutes) public onlyOwner { require(state == State.Inactive); // Donation event must have ended organizationAddress = _organizationAddress; // Set organization's address donationGoal = (_donationGoal * 1 ether); // Set donation's goal durationInMinutes = _durationInMinutes; deadline = now + (durationInMinutes * 1 minutes); // Set donation's deadline state = State.Active; StartDonationEvent(organizationAddress, donationGoal, durationInMinutes); } /* * sendDonation() * send donation directly to organization's address */ function sendDonation() public payable returns(bool success) { //require(msg.sender != owner); require(state == State.Active); require(msg.value > 0); uint amount = msg.value; if (balanceOf[msg.sender] <= amount) { organizationAddress.transfer(amount); raisedAmount += amount; DonateEvent(msg.sender, organizationAddress, amount); return true; } return false; } /* * checkDonationEnded() * check if donation event has ended * allow access only during active event, as there is no need to check status when it is ended */ function checkDonationEnded() public { require(state == State.Active); // Donation even must be active if(now >= deadline) { state = State.Inactive; raisedAmount = 0; } } /* * cancelDonation() * Let owner cancel donation event. Useful if there is a typo in organization address, duration. * When users donate, funds are automatically transfered to organization address, so owner can't * steal. */ function cancelDonation() public onlyOwner { require(state == State.Active); deadline += durationInMinutes; state = State.Inactive; CancelDonationEvent(organizationAddress, raisedAmount); raisedAmount = 0; } /* * fromContractToOwner() * If for some reason ether is sent to contract's address, owner can gete the funds back. * Future plans: keep track of transactions and send back if they end up in contract's address * to prevent owner from stealing. */ function fromContractToOwner() public onlyOwner { uint contractsBalance = this.balance; owner.transfer(contractsBalance); FromContractToOwnerEvent(owner, contractsBalance); } /* * getRaisedAmount() * Return amount of ether raised during current event, to keep track of statistics * ***SHOULD USE ALREADY EXISTING EVENTS INSTEAD OF THIS FUNCTION TO SAVE GAS*** */ function getRaisedAmount() public onlyOwner returns(uint) { require(state == State.Active); return raisedAmount; } /* * kill() * delete this smart contract from blockchain */ function kill() public onlyOwner { if (msg.sender == owner) { selfdestruct(owner); } } }
sendDonation() send donation directly to organization's address/require(msg.sender != owner);
function sendDonation() public payable returns(bool success) { require(state == State.Active); require(msg.value > 0); uint amount = msg.value; if (balanceOf[msg.sender] <= amount) { organizationAddress.transfer(amount); raisedAmount += amount; DonateEvent(msg.sender, organizationAddress, amount); return true; } return false; }
2,480,833
/* Copyright 2022 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 { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { ISetToken } from "@setprotocol/set-protocol-v2/contracts/interfaces/ISetToken.sol"; import { PreciseUnitMath } from "@setprotocol/set-protocol-v2/contracts/lib/PreciseUnitMath.sol"; import { BaseGlobalExtension } from "../lib/BaseGlobalExtension.sol"; import { IDelegatedManager } from "../interfaces/IDelegatedManager.sol"; import { IIssuanceModule } from "../interfaces/IIssuanceModule.sol"; import { IManagerCore } from "../interfaces/IManagerCore.sol"; /** * @title IssuanceExtension * @author Set Protocol * * Smart contract global extension which provides DelegatedManager owner and methodologist the ability to accrue and split * issuance and redemption fees. Owner may configure the fee split percentages. * * Notes * - the fee split is set on the Delegated Manager contract * - when fees distributed via this contract will be inclusive of all fee types that have already been accrued */ contract IssuanceExtension is BaseGlobalExtension { using Address for address; using PreciseUnitMath for uint256; using SafeMath for uint256; /* ============ Events ============ */ event IssuanceExtensionInitialized( address indexed _setToken, address indexed _delegatedManager ); event FeesDistributed( address _setToken, address indexed _ownerFeeRecipient, address indexed _methodologist, uint256 _ownerTake, uint256 _methodologistTake ); /* ============ State Variables ============ */ // Instance of IssuanceModule IIssuanceModule public immutable issuanceModule; /* ============ Constructor ============ */ constructor( IManagerCore _managerCore, IIssuanceModule _issuanceModule ) public BaseGlobalExtension(_managerCore) { issuanceModule = _issuanceModule; } /* ============ External Functions ============ */ /** * ANYONE CALLABLE: Distributes fees accrued to the DelegatedManager. Calculates fees for * owner and methodologist, and sends to owner fee recipient and methodologist respectively. */ function distributeFees(ISetToken _setToken) public { IDelegatedManager delegatedManager = _manager(_setToken); uint256 totalFees = _setToken.balanceOf(address(delegatedManager)); address methodologist = delegatedManager.methodologist(); address ownerFeeRecipient = delegatedManager.ownerFeeRecipient(); uint256 ownerTake = totalFees.preciseMul(delegatedManager.ownerFeeSplit()); uint256 methodologistTake = totalFees.sub(ownerTake); if (ownerTake > 0) { delegatedManager.transferTokens(address(_setToken), ownerFeeRecipient, ownerTake); } if (methodologistTake > 0) { delegatedManager.transferTokens(address(_setToken), methodologist, methodologistTake); } emit FeesDistributed(address(_setToken), ownerFeeRecipient, methodologist, ownerTake, methodologistTake); } /** * ONLY OWNER: Initializes IssuanceModule on the SetToken associated with the DelegatedManager. * * @param _delegatedManager Instance of the DelegatedManager to initialize the IssuanceModule for * @param _maxManagerFee Maximum fee that can be charged on issue and redeem * @param _managerIssueFee Fee to charge on issuance * @param _managerRedeemFee Fee to charge on redemption * @param _feeRecipient Address to send fees to * @param _managerIssuanceHook Instance of the contract with the Pre-Issuance Hook function */ function initializeModule( IDelegatedManager _delegatedManager, uint256 _maxManagerFee, uint256 _managerIssueFee, uint256 _managerRedeemFee, address _feeRecipient, address _managerIssuanceHook ) external onlyOwnerAndValidManager(_delegatedManager) { require(_delegatedManager.isInitializedExtension(address(this)), "Extension must be initialized"); _initializeModule( _delegatedManager.setToken(), _delegatedManager, _maxManagerFee, _managerIssueFee, _managerRedeemFee, _feeRecipient, _managerIssuanceHook ); } /** * ONLY OWNER: Initializes IssuanceExtension to the DelegatedManager. * * @param _delegatedManager Instance of the DelegatedManager to initialize */ function initializeExtension(IDelegatedManager _delegatedManager) external onlyOwnerAndValidManager(_delegatedManager) { require(_delegatedManager.isPendingExtension(address(this)), "Extension must be pending"); ISetToken setToken = _delegatedManager.setToken(); _initializeExtension(setToken, _delegatedManager); emit IssuanceExtensionInitialized(address(setToken), address(_delegatedManager)); } /** * ONLY OWNER: Initializes IssuanceExtension to the DelegatedManager and IssuanceModule to the SetToken * * @param _delegatedManager Instance of the DelegatedManager to initialize * @param _maxManagerFee Maximum fee that can be charged on issue and redeem * @param _managerIssueFee Fee to charge on issuance * @param _managerRedeemFee Fee to charge on redemption * @param _feeRecipient Address to send fees to * @param _managerIssuanceHook Instance of the contract with the Pre-Issuance Hook function */ function initializeModuleAndExtension( IDelegatedManager _delegatedManager, uint256 _maxManagerFee, uint256 _managerIssueFee, uint256 _managerRedeemFee, address _feeRecipient, address _managerIssuanceHook ) external onlyOwnerAndValidManager(_delegatedManager) { require(_delegatedManager.isPendingExtension(address(this)), "Extension must be pending"); ISetToken setToken = _delegatedManager.setToken(); _initializeExtension(setToken, _delegatedManager); _initializeModule( setToken, _delegatedManager, _maxManagerFee, _managerIssueFee, _managerRedeemFee, _feeRecipient, _managerIssuanceHook ); emit IssuanceExtensionInitialized(address(setToken), address(_delegatedManager)); } /** * ONLY MANAGER: Remove an existing SetToken and DelegatedManager tracked by the IssuanceExtension */ function removeExtension() external override { IDelegatedManager delegatedManager = IDelegatedManager(msg.sender); ISetToken setToken = delegatedManager.setToken(); _removeExtension(setToken, delegatedManager); } /** * ONLY OWNER: Updates issuance fee on IssuanceModule. * * @param _setToken Instance of the SetToken to update issue fee for * @param _newFee New issue fee percentage in precise units (1% = 1e16, 100% = 1e18) */ function updateIssueFee(ISetToken _setToken, uint256 _newFee) external onlyOwner(_setToken) { bytes memory callData = abi.encodeWithSignature("updateIssueFee(address,uint256)", _setToken, _newFee); _invokeManager(_manager(_setToken), address(issuanceModule), callData); } /** * ONLY OWNER: Updates redemption fee on IssuanceModule. * * @param _setToken Instance of the SetToken to update redeem fee for * @param _newFee New redeem fee percentage in precise units (1% = 1e16, 100% = 1e18) */ function updateRedeemFee(ISetToken _setToken, uint256 _newFee) external onlyOwner(_setToken) { bytes memory callData = abi.encodeWithSignature("updateRedeemFee(address,uint256)", _setToken, _newFee); _invokeManager(_manager(_setToken), address(issuanceModule), callData); } /** * ONLY OWNER: Updates fee recipient on IssuanceModule * * @param _setToken Instance of the SetToken to update fee recipient for * @param _newFeeRecipient Address of new fee recipient. This should be the address of the DelegatedManager */ function updateFeeRecipient(ISetToken _setToken, address _newFeeRecipient) external onlyOwner(_setToken) { bytes memory callData = abi.encodeWithSignature("updateFeeRecipient(address,address)", _setToken, _newFeeRecipient); _invokeManager(_manager(_setToken), address(issuanceModule), callData); } /* ============ Internal Functions ============ */ /** * Internal function to initialize IssuanceModule on the SetToken associated with the DelegatedManager. * * @param _setToken Instance of the SetToken corresponding to the DelegatedManager * @param _delegatedManager Instance of the DelegatedManager to initialize the TradeModule for * @param _maxManagerFee Maximum fee that can be charged on issue and redeem * @param _managerIssueFee Fee to charge on issuance * @param _managerRedeemFee Fee to charge on redemption * @param _feeRecipient Address to send fees to * @param _managerIssuanceHook Instance of the contract with the Pre-Issuance Hook function */ function _initializeModule( ISetToken _setToken, IDelegatedManager _delegatedManager, uint256 _maxManagerFee, uint256 _managerIssueFee, uint256 _managerRedeemFee, address _feeRecipient, address _managerIssuanceHook ) internal { bytes memory callData = abi.encodeWithSignature( "initialize(address,uint256,uint256,uint256,address,address)", _setToken, _maxManagerFee, _managerIssueFee, _managerRedeemFee, _feeRecipient, _managerIssuanceHook ); _invokeManager(_delegatedManager, address(issuanceModule), callData); } } // 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); } 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 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; } } /* 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/contracts/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); } /* 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 { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/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 * - 4/21/21: Added approximatelyEquals function * - 12/13/21: Added preciseDivCeil (int overloads) function * - 12/13/21: Added abs function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; using SafeCast 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 up or away from 0). When `a` is 0, 0 is * returned. When `b` is 0, method reverts with divide-by-zero error. */ function preciseDivCeil(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); a = a.mul(PRECISE_UNIT_INT); int256 c = a.div(b); if (a % b != 0) { // a ^ b == 0 case is covered by the previous if statement, hence it won't resolve to --c (a ^ b > 0) ? ++c : --c; } return c; } /** * @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; } /** * @dev Returns true if a =~ b within range, false otherwise. */ function approximatelyEquals(uint256 a, uint256 b, uint256 range) internal pure returns (bool) { return a <= b.add(range) && a >= b.sub(range); } /** * Returns the absolute value of int256 `a` as a uint256 */ function abs(int256 a) internal pure returns (uint) { return a >= 0 ? a.toUint256() : a.mul(-1).toUint256(); } /** * Returns the negation of a */ function neg(int256 a) internal pure returns (int256) { require(a > MIN_INT_256, "Inversion overflow"); return -a; } } /* Copyright 2022 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 "@setprotocol/set-protocol-v2/contracts/interfaces/ISetToken.sol"; import { AddressArrayUtils } from "../lib/AddressArrayUtils.sol"; import { IDelegatedManager } from "../interfaces/IDelegatedManager.sol"; import { IManagerCore } from "../interfaces/IManagerCore.sol"; /** * @title BaseGlobalExtension * @author Set Protocol * * Abstract class that houses common global extension-related functions. Global extensions must * also have their own initializeExtension function (not included here because interfaces will vary). */ abstract contract BaseGlobalExtension { using AddressArrayUtils for address[]; /* ============ Events ============ */ event ExtensionRemoved( address indexed _setToken, address indexed _delegatedManager ); /* ============ State Variables ============ */ // Address of the ManagerCore IManagerCore public immutable managerCore; // Mapping from Set Token to DelegatedManager mapping(ISetToken => IDelegatedManager) public setManagers; /* ============ Modifiers ============ */ /** * Throws if the sender is not the SetToken manager contract owner */ modifier onlyOwner(ISetToken _setToken) { require(msg.sender == _manager(_setToken).owner(), "Must be owner"); _; } /** * Throws if the sender is not the SetToken methodologist */ modifier onlyMethodologist(ISetToken _setToken) { require(msg.sender == _manager(_setToken).methodologist(), "Must be methodologist"); _; } /** * Throws if the sender is not a SetToken operator */ modifier onlyOperator(ISetToken _setToken) { require(_manager(_setToken).operatorAllowlist(msg.sender), "Must be approved operator"); _; } /** * Throws if the sender is not the SetToken manager contract owner or if the manager is not enabled on the ManagerCore */ modifier onlyOwnerAndValidManager(IDelegatedManager _delegatedManager) { require(msg.sender == _delegatedManager.owner(), "Must be owner"); require(managerCore.isManager(address(_delegatedManager)), "Must be ManagerCore-enabled manager"); _; } /** * Throws if asset is not allowed to be held by the Set */ modifier onlyAllowedAsset(ISetToken _setToken, address _asset) { require(_manager(_setToken).isAllowedAsset(_asset), "Must be allowed asset"); _; } /* ============ Constructor ============ */ /** * Set state variables * * @param _managerCore Address of managerCore contract */ constructor(IManagerCore _managerCore) public { managerCore = _managerCore; } /* ============ External Functions ============ */ /** * ONLY MANAGER: Deletes SetToken/Manager state from extension. Must only be callable by manager! */ function removeExtension() external virtual; /* ============ Internal Functions ============ */ /** * Invoke call from manager * * @param _delegatedManager Manager to interact with * @param _module Module to interact with * @param _encoded Encoded byte data */ function _invokeManager(IDelegatedManager _delegatedManager, address _module, bytes memory _encoded) internal { _delegatedManager.interactManager(_module, _encoded); } /** * Internal function to grab manager of passed SetToken from extensions data structure. * * @param _setToken SetToken who's manager is needed */ function _manager(ISetToken _setToken) internal view returns (IDelegatedManager) { return setManagers[_setToken]; } /** * Internal function to initialize extension to the DelegatedManager. * * @param _setToken Instance of the SetToken corresponding to the DelegatedManager * @param _delegatedManager Instance of the DelegatedManager to initialize */ function _initializeExtension(ISetToken _setToken, IDelegatedManager _delegatedManager) internal { setManagers[_setToken] = _delegatedManager; _delegatedManager.initializeExtension(); } /** * ONLY MANAGER: Internal function to delete SetToken/Manager state from extension */ function _removeExtension(ISetToken _setToken, IDelegatedManager _delegatedManager) internal { require(msg.sender == address(_manager(_setToken)), "Must be Manager"); delete setManagers[_setToken]; emit ExtensionRemoved(address(_setToken), address(_delegatedManager)); } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { ISetToken } from "@setprotocol/set-protocol-v2/contracts/interfaces/ISetToken.sol"; interface IDelegatedManager { function interactManager(address _module, bytes calldata _encoded) external; function initializeExtension() external; function transferTokens(address _token, address _destination, uint256 _amount) external; function updateOwnerFeeSplit(uint256 _newFeeSplit) external; function updateOwnerFeeRecipient(address _newFeeRecipient) external; function setMethodologist(address _newMethodologist) external; function transferOwnership(address _owner) external; function setToken() external view returns(ISetToken); function owner() external view returns(address); function methodologist() external view returns(address); function operatorAllowlist(address _operator) external view returns(bool); function assetAllowlist(address _asset) external view returns(bool); function isAllowedAsset(address _asset) external view returns(bool); function isPendingExtension(address _extension) external view returns(bool); function isInitializedExtension(address _extension) external view returns(bool); function getExtensions() external view returns(address[] memory); function getOperators() external view returns(address[] memory); function getAllowedAssets() external view returns(address[] memory); function ownerFeeRecipient() external view returns(address); function ownerFeeSplit() external view returns(uint256); } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { ISetToken } from "./ISetToken.sol"; /** * @title IDebtIssuanceModule * @author Set Protocol * * Interface for interacting with Debt Issuance module interface. */ interface IIssuanceModule { function updateIssueFee(ISetToken _setToken, uint256 _newIssueFee) external; function updateRedeemFee(ISetToken _setToken, uint256 _newRedeemFee) external; function updateFeeRecipient(ISetToken _setToken, address _newRedeemFee) external; function initialize( ISetToken _setToken, uint256 _maxManagerFee, uint256 _managerIssueFee, uint256 _managerRedeemFee, address _feeRecipient, address _managerIssuanceHook ) external; } /* Copyright 2022 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 IManagerCore { function addManager(address _manager) external; function isExtension(address _extension) external view returns(bool); function isFactory(address _factory) external view returns(bool); function isManager(address _manager) external view returns(bool); } // 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; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } /* 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 * * CHANGELOG: * - 4/27/21: Added validatePairsWithArray methods */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } } // SPDX-License-Identifier: Apache License, Version 2.0 pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/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); }
Returns the absolute value of int256 `a` as a uint256/
function abs(int256 a) internal pure returns (uint) { return a >= 0 ? a.toUint256() : a.mul(-1).toUint256(); }
1,613,486
./partial_match/1/0xA02Ff43513c55009541b26491E616c3f3CFA3b06/sources/JETYFIPool.sol
stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount, address staker) public override updateReward(staker) checkStart onlyHelper { require(amount > 0, "PoolStake: Cannot stake 0"); uint256 newDeposit = deposits[staker].add(amount); require( newDeposit <= 25000e18, "PoolStake: deposit amount exceeds maximum 25000" ); deposits[staker] = newDeposit; super.stake(amount, staker); emit Staked(staker, amount); }
4,200,176
pragma solidity 0.6.1; pragma experimental ABIEncoderV2; contract productContract { Product[] public supplyChain; //stores all of the products created. mapping(string => Transaction) public transactionDetail; // uses the trackingID as the key to view current custodian and their address. mapping(string => string) public miscellaneous; // use the trackingID as the key to view miscellaneous messages. mapping(string => string[]) public counterparties; // counterparties stores the current custodian plus the previous participants address manufacturer; // stores the account address of the where this contract is deployed on in a variable called manufacturer. modifier onlyManufacturer() { // only manufacturer can call the addProduct function. require(msg.sender == manufacturer); _; } uint256 public totalProductsCreated = 0; struct Product{ string productName; string health; bool sold; bool recalled; string custodian; //who currently owns the product string trackingID; string lastScannedAt; } struct Transaction{ //stores current information of the product uint256 timestamp; string containerID; string custodian; address custodianAddress; string lastScannedAt; } event productAdded (string ID); event sendArray(Product[] array); constructor() public{ manufacturer = msg.sender; } // The addProduct will create a new product only if they are the manufacturer. Sold and Recall values are set to false and containerID is "" when a product is created. function addProduct(string memory _productName, string memory _health, string memory _misc, string memory _trackingID, string memory _lastScannedAt) public onlyManufacturer{ uint256 _timestamp = block.timestamp; bool _sold = false; bool _recalled = false; string memory _containerID = ""; string memory _custodian = "manufacturer"; transactionDetail[_trackingID] = (Transaction(_timestamp, _containerID, _custodian, manufacturer,_lastScannedAt)); // uses trackingID to get the timestamp, containerID, custodian and custodian_Address. supplyChain.push(Product(_productName,_health,_sold,_recalled,_custodian,_trackingID,_lastScannedAt)); // pushes the new product to the array miscellaneous[_trackingID] = _misc; // use trackingID as the key to view string value. addCounterParties(_trackingID,_custodian);//calls an internal function and appends the custodian to the product using the trackingID emit productAdded(_trackingID); totalProductsCreated += 1; } //addCounterParties is a private method that updates the custodian of the product using the trackingID function addCounterParties(string memory _trackingID, string memory _custodian) internal{ counterparties[_trackingID].push(_custodian); } //The updateCustodian method updates custodian when custodianship changes function updateCustodian(string memory _trackingID, string memory longLatsCoordinates ) public { if(msg.sender != manufacturer){ // if the account calling this function is not the manufacturer, the following will be performed: address _custodianAddress = msg.sender; string memory _custodian = 'store'; uint256 _timestamp = block.timestamp; transactionDetail[_trackingID].timestamp = _timestamp; transactionDetail[_trackingID].lastScannedAt = longLatsCoordinates; transactionDetail[_trackingID].custodian = _custodian; transactionDetail[_trackingID].custodianAddress = _custodianAddress; addCounterParties(_trackingID,_custodian); //the new custodian gets added to the counterparties map. } } function getAllProducts() public returns(Product[] memory) { emit sendArray(supplyChain); return supplyChain; } }
The addProduct will create a new product only if they are the manufacturer. Sold and Recall values are set to false and containerID is "" when a product is created.
function addProduct(string memory _productName, string memory _health, string memory _misc, string memory _trackingID, string memory _lastScannedAt) public onlyManufacturer{ uint256 _timestamp = block.timestamp; bool _sold = false; bool _recalled = false; string memory _containerID = ""; string memory _custodian = "manufacturer"; emit productAdded(_trackingID); totalProductsCreated += 1; }
950,904
./full_match/1/0x2270D7733cBDD45ab265F4b5f0B8c2364b62e7eB/sources/localhost/oracle/RebasedPriceOracle.sol
Get the average price of 1 REB in Wei
function getRebEthRate() public view returns (uint256, uint256, uint32, uint256) { (uint price0Cumulative, uint price1Cumulative, uint32 _blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(_eth_reb)); FixedPoint.uq112x112 memory rebEthAverage = FixedPoint.uq112x112(uint224(1e9 * (price1Cumulative - ethRebPrice1CumulativeLast) / (_blockTimestamp - ethRebBlockTimestampLast))); return (price0Cumulative, price1Cumulative, _blockTimestamp, rebEthAverage.mul(1).decode144()); }
2,982,735
./partial_match/1/0x0E6D46Bf4Af093b8DCCd2BDDC0dAf6f30205Abb4/sources/OpenPeerEscrowsDeployer.sol
Updates the implementation _implementation Address of the implementation
function setImplementation(address payable _implementation) public onlyOwner { require(_implementation != address(0), "Invalid implementation"); implementation = _implementation; }
3,581,124
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; /// @title Eleven-Yellow BOTTO governance service /// @notice Staked BOTTO tokens represent a weighting for influence on governance issues contract BottoGovernance is OwnableUpgradeable { using SafeMath for uint256; address public botto; uint256 public totalStaked; mapping(address => uint256) public userStakes; event Staked(address indexed staker, uint256 amount); event Unstaked(address indexed staker, uint256 amount); event RecoveryTransfer(address token, uint256 amount, address recipient); /// @param botto_ ERC20 contract address of BOTTO token /// @dev BOTTO token contract address is initialized function initialize(address botto_) public initializer { __Ownable_init(); botto = botto_; } /// @notice Stake BOTTO tokens for governance purposes /// @param amount_ the amount of BOTTO tokens to stake /// @dev Stake requires approval for governance contract to transfer & hold BOTTO tokens function stake(uint256 amount_) public virtual { require(amount_ > 0, "Invalid amount"); userStakes[msg.sender] = userStakes[msg.sender].add(amount_); IERC20(botto).transferFrom(msg.sender, address(this), amount_); totalStaked = totalStaked.add(amount_); emit Staked(msg.sender, amount_); } /// @notice Unstake previously staked tokens /// @dev Existing token stake is transferred back to owner function unstake() public virtual { uint256 amount = userStakes[msg.sender]; require(amount > 0, "No existing stake"); userStakes[msg.sender] = 0; totalStaked = totalStaked.sub(amount); IERC20(botto).transfer(msg.sender, amount); emit Unstaked(msg.sender, amount); } /// @notice Sweeps excess tokens to a specified recipient address /// @param token_ address of token to recover /// @param recipient_ payable address for token beneficiary /// @dev Total token balance is recovered; only excess non-staked tokens in case of BOTTO function recover(address token_, address payable recipient_) public virtual onlyOwner { uint256 _balance = IERC20(token_).balanceOf(address(this)); if (token_ == botto) { _balance = _balance.sub(totalStaked); } TransferHelper.safeTransfer(token_, recipient_, _balance); emit RecoveryTransfer(token_, _balance, recipient_); } }
Sweeps excess tokens to a specified recipient address token_ address of token to recover recipient_ payable address for token beneficiary Total token balance is recovered; only excess non-staked tokens in case of BOTTO
function recover(address token_, address payable recipient_) public virtual onlyOwner { uint256 _balance = IERC20(token_).balanceOf(address(this)); if (token_ == botto) { _balance = _balance.sub(totalStaked); } TransferHelper.safeTransfer(token_, recipient_, _balance); emit RecoveryTransfer(token_, _balance, recipient_); }
12,806,237
./full_match/5/0x10eE298D8445e507D6245ff2418C6608804486Cc/sources/contracts/L1/messaging/L1CrossDomainMessenger.sol
Sends a cross domain message. _messageQueue Address of the _messageQueue instance. _message Message to send. _gasLimit NVM gas limit for the message./ slither-disable-next-line reentrancy-events
function _sendXDomainMessage( address _messageQueue, bytes memory _message, uint256 _gasLimit ) internal { IMessageQueue(_messageQueue).enqueue( Lib_PredeployAddresses.L2_CROSS_DOMAIN_MESSENGER, _gasLimit, _message ); }
1,894,258
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./VeRipToken.sol"; /// @title Vote Escrow Rip Staking /// @author Dex Rip /// @notice Stake Rip to earn veRip, which you can use to earn higher farm yields and gain /// voting power. Note that unstaking any amount of Rip will burn all of your existing veRip. contract VeRipStaking is Initializable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; /// @notice Info for each user /// `balance`: Amount of Rip currently staked by user /// `rewardDebt`: The reward debt of the user /// `lastClaimTimestamp`: The timestamp of user's last claim or withdraw /// `speedUpEndTimestamp`: The timestamp when user stops receiving speed up benefits, or /// zero if user is not currently receiving speed up benefits struct UserInfo { uint256 balance; uint256 rewardDebt; uint256 lastClaimTimestamp; uint256 speedUpEndTimestamp; /** * @notice We do some fancy math here. Basically, any point in time, the amount of veRip * entitled to a user but is pending to be distributed is: * * pendingReward = pendingBaseReward + pendingSpeedUpReward * * pendingBaseReward = (user.balance * accVeRipPerShare) - user.rewardDebt * * if user.speedUpEndTimestamp != 0: * speedUpCeilingTimestamp = min(block.timestamp, user.speedUpEndTimestamp) * speedUpSecondsElapsed = speedUpCeilingTimestamp - user.lastClaimTimestamp * pendingSpeedUpReward = speedUpSecondsElapsed * user.balance * speedUpVeRipPerSharePerSec * else: * pendingSpeedUpReward = 0 */ } IERC20Upgradeable public Rip; VeRipToken public veRip; /// @notice The maximum limit of veRip user can have as percentage points of staked Rip /// For example, if user has `n` Rip staked, they can own a maximum of `n * maxCapPct / 100` veRip. uint256 public maxCapPct; /// @notice The upper limit of `maxCapPct` uint256 public upperLimitMaxCapPct; /// @notice The accrued veRip per share, scaled to `ACC_VERip_PER_SHARE_PRECISION` uint256 public accVeRipPerShare; /// @notice Precision of `accVeRipPerShare` uint256 public ACC_VERip_PER_SHARE_PRECISION; /// @notice The last time that the reward variables were updated uint256 public lastRewardTimestamp; /// @notice veRip per sec per Rip staked, scaled to `VERip_PER_SHARE_PER_SEC_PRECISION` uint256 public veRipPerSharePerSec; /// @notice Speed up veRip per sec per Rip staked, scaled to `VERip_PER_SHARE_PER_SEC_PRECISION` uint256 public speedUpVeRipPerSharePerSec; /// @notice The upper limit of `veRipPerSharePerSec` and `speedUpVeRipPerSharePerSec` uint256 public upperLimitVeRipPerSharePerSec; /// @notice Precision of `veRipPerSharePerSec` uint256 public VERip_PER_SHARE_PER_SEC_PRECISION; /// @notice Percentage of user's current staked Rip user has to deposit in order to start /// receiving speed up benefits, in parts per 100. /// @dev Specifically, user has to deposit at least `speedUpThreshold/100 * userStakedRip` Rip. /// The only exception is the user will also receive speed up benefits if they are depositing /// with zero balance uint256 public speedUpThreshold; /// @notice The length of time a user receives speed up benefits uint256 public speedUpDuration; mapping(address => UserInfo) public userInfos; event Claim(address indexed user, uint256 amount); event Deposit(address indexed user, uint256 amount); event UpdateMaxCapPct(address indexed user, uint256 maxCapPct); event UpdateRewardVars(uint256 lastRewardTimestamp, uint256 accVeRipPerShare); event UpdateSpeedUpThreshold(address indexed user, uint256 speedUpThreshold); event UpdateVeRipPerSharePerSec(address indexed user, uint256 veRipPerSharePerSec); event Withdraw(address indexed user, uint256 amount); /// @notice Initialize with needed parameters /// @param _Rip Address of the Rip token contract /// @param _veRip Address of the veRip token contract /// @param _veRipPerSharePerSec veRip per sec per Rip staked, scaled to `VERip_PER_SHARE_PER_SEC_PRECISION` /// @param _speedUpVeRipPerSharePerSec Similar to `_veRipPerSharePerSec` but for speed up /// @param _speedUpThreshold Percentage of total staked Rip user has to deposit receive speed up /// @param _speedUpDuration Length of time a user receives speed up benefits /// @param _maxCapPct Maximum limit of veRip user can have as percentage points of staked Rip function initialize( IERC20Upgradeable _Rip, VeRipToken _veRip, uint256 _veRipPerSharePerSec, uint256 _speedUpVeRipPerSharePerSec, uint256 _speedUpThreshold, uint256 _speedUpDuration, uint256 _maxCapPct ) public initializer { __Ownable_init(); require(address(_Rip) != address(0), "VeRipStaking: unexpected zero address for _Rip"); require(address(_veRip) != address(0), "VeRipStaking: unexpected zero address for _veRip"); upperLimitVeRipPerSharePerSec = 1e36; require( _veRipPerSharePerSec <= upperLimitVeRipPerSharePerSec, "VeRipStaking: expected _veRipPerSharePerSec to be <= 1e36" ); require( _speedUpVeRipPerSharePerSec <= upperLimitVeRipPerSharePerSec, "VeRipStaking: expected _speedUpVeRipPerSharePerSec to be <= 1e36" ); require( _speedUpThreshold != 0 && _speedUpThreshold <= 100, "VeRipStaking: expected _speedUpThreshold to be > 0 and <= 100" ); require(_speedUpDuration <= 365 days, "VeRipStaking: expected _speedUpDuration to be <= 365 days"); upperLimitMaxCapPct = 10000000; require( _maxCapPct != 0 && _maxCapPct <= upperLimitMaxCapPct, "VeRipStaking: expected _maxCapPct to be non-zero and <= 10000000" ); maxCapPct = _maxCapPct; speedUpThreshold = _speedUpThreshold; speedUpDuration = _speedUpDuration; Rip = _Rip; veRip = _veRip; veRipPerSharePerSec = _veRipPerSharePerSec; speedUpVeRipPerSharePerSec = _speedUpVeRipPerSharePerSec; lastRewardTimestamp = block.timestamp; ACC_VERip_PER_SHARE_PRECISION = 1e18; VERip_PER_SHARE_PER_SEC_PRECISION = 1e18; } /// @notice Set maxCapPct /// @param _maxCapPct The new maxCapPct function setMaxCapPct(uint256 _maxCapPct) external onlyOwner { require(_maxCapPct > maxCapPct, "VeRipStaking: expected new _maxCapPct to be greater than existing maxCapPct"); require( _maxCapPct != 0 && _maxCapPct <= upperLimitMaxCapPct, "VeRipStaking: expected new _maxCapPct to be non-zero and <= 10000000" ); maxCapPct = _maxCapPct; emit UpdateMaxCapPct(msg.sender, _maxCapPct); } /// @notice Set veRipPerSharePerSec /// @param _veRipPerSharePerSec The new veRipPerSharePerSec function setVeRipPerSharePerSec(uint256 _veRipPerSharePerSec) external onlyOwner { require( _veRipPerSharePerSec <= upperLimitVeRipPerSharePerSec, "VeRipStaking: expected _veRipPerSharePerSec to be <= 1e36" ); updateRewardVars(); veRipPerSharePerSec = _veRipPerSharePerSec; emit UpdateVeRipPerSharePerSec(msg.sender, _veRipPerSharePerSec); } /// @notice Set speedUpThreshold /// @param _speedUpThreshold The new speedUpThreshold function setSpeedUpThreshold(uint256 _speedUpThreshold) external onlyOwner { require( _speedUpThreshold != 0 && _speedUpThreshold <= 100, "VeRipStaking: expected _speedUpThreshold to be > 0 and <= 100" ); speedUpThreshold = _speedUpThreshold; emit UpdateSpeedUpThreshold(msg.sender, _speedUpThreshold); } /// @notice Deposits Rip to start staking for veRip. Note that any pending veRip /// will also be claimed in the process. /// @param _amount The amount of Rip to deposit function deposit(uint256 _amount) external { require(_amount > 0, "VeRipStaking: expected deposit amount to be greater than zero"); updateRewardVars(); UserInfo storage userInfo = userInfos[msg.sender]; if (_getUserHasNonZeroBalance(msg.sender)) { // Transfer to the user their pending veRip before updating their UserInfo _claim(); // We need to update user's `lastClaimTimestamp` to now to prevent // passive veRip accrual if user hit their max cap. userInfo.lastClaimTimestamp = block.timestamp; uint256 userStakedRip = userInfo.balance; // User is eligible for speed up benefits if `_amount` is at least // `speedUpThreshold / 100 * userStakedRip` if (_amount.mul(100) >= speedUpThreshold.mul(userStakedRip)) { userInfo.speedUpEndTimestamp = block.timestamp.add(speedUpDuration); } } else { // If user is depositing with zero balance, they will automatically // receive speed up benefits userInfo.speedUpEndTimestamp = block.timestamp.add(speedUpDuration); userInfo.lastClaimTimestamp = block.timestamp; } userInfo.balance = userInfo.balance.add(_amount); userInfo.rewardDebt = accVeRipPerShare.mul(userInfo.balance).div(ACC_VERip_PER_SHARE_PRECISION); Rip.safeTransferFrom(msg.sender, address(this), _amount); emit Deposit(msg.sender, _amount); } /// @notice Withdraw staked Rip. Note that unstaking any amount of Rip means you will /// lose all of your current veRip. /// @param _amount The amount of Rip to unstake function withdraw(uint256 _amount) external { require(_amount > 0, "VeRipStaking: expected withdraw amount to be greater than zero"); UserInfo storage userInfo = userInfos[msg.sender]; require( userInfo.balance >= _amount, "VeRipStaking: cannot withdraw greater amount of Rip than currently staked" ); updateRewardVars(); // Note that we don't need to claim as the user's veRip balance will be reset to 0 userInfo.balance = userInfo.balance.sub(_amount); userInfo.rewardDebt = accVeRipPerShare.mul(userInfo.balance).div(ACC_VERip_PER_SHARE_PRECISION); userInfo.lastClaimTimestamp = block.timestamp; userInfo.speedUpEndTimestamp = 0; // Burn the user's current veRip balance veRip.burnFrom(msg.sender, veRip.balanceOf(msg.sender)); // Send user their requested amount of staked Rip Rip.safeTransfer(msg.sender, _amount); emit Withdraw(msg.sender, _amount); } /// @notice Claim any pending veRip function claim() external { require(_getUserHasNonZeroBalance(msg.sender), "VeRipStaking: cannot claim veRip when no Rip is staked"); updateRewardVars(); _claim(); } /// @notice Get the pending amount of veRip for a given user /// @param _user The user to lookup /// @return The number of pending veRip tokens for `_user` function getPendingVeRip(address _user) public view returns (uint256) { if (!_getUserHasNonZeroBalance(_user)) { return 0; } UserInfo memory user = userInfos[_user]; // Calculate amount of pending base veRip uint256 _accVeRipPerShare = accVeRipPerShare; uint256 secondsElapsed = block.timestamp.sub(lastRewardTimestamp); if (secondsElapsed > 0) { _accVeRipPerShare = _accVeRipPerShare.add( secondsElapsed.mul(veRipPerSharePerSec).mul(ACC_VERip_PER_SHARE_PRECISION).div( VERip_PER_SHARE_PER_SEC_PRECISION ) ); } uint256 pendingBaseVeRip = _accVeRipPerShare.mul(user.balance).div(ACC_VERip_PER_SHARE_PRECISION).sub( user.rewardDebt ); // Calculate amount of pending speed up veRip uint256 pendingSpeedUpVeRip; if (user.speedUpEndTimestamp != 0) { uint256 speedUpCeilingTimestamp = block.timestamp > user.speedUpEndTimestamp ? user.speedUpEndTimestamp : block.timestamp; uint256 speedUpSecondsElapsed = speedUpCeilingTimestamp.sub(user.lastClaimTimestamp); uint256 speedUpAccVeRipPerShare = speedUpSecondsElapsed.mul(speedUpVeRipPerSharePerSec); pendingSpeedUpVeRip = speedUpAccVeRipPerShare.mul(user.balance).div(VERip_PER_SHARE_PER_SEC_PRECISION); } uint256 pendingVeRip = pendingBaseVeRip.add(pendingSpeedUpVeRip); // Get the user's current veRip balance uint256 userVeRipBalance = veRip.balanceOf(_user); // This is the user's max veRip cap multiplied by 100 uint256 scaledUserMaxVeRipCap = user.balance.mul(maxCapPct); if (userVeRipBalance.mul(100) >= scaledUserMaxVeRipCap) { // User already holds maximum amount of veRip so there is no pending veRip return 0; } else if (userVeRipBalance.add(pendingVeRip).mul(100) > scaledUserMaxVeRipCap) { return scaledUserMaxVeRipCap.sub(userVeRipBalance.mul(100)).div(100); } else { return pendingVeRip; } } /// @notice Update reward variables function updateRewardVars() public { if (block.timestamp <= lastRewardTimestamp) { return; } if (Rip.balanceOf(address(this)) == 0) { lastRewardTimestamp = block.timestamp; return; } uint256 secondsElapsed = block.timestamp.sub(lastRewardTimestamp); accVeRipPerShare = accVeRipPerShare.add( secondsElapsed.mul(veRipPerSharePerSec).mul(ACC_VERip_PER_SHARE_PRECISION).div( VERip_PER_SHARE_PER_SEC_PRECISION ) ); lastRewardTimestamp = block.timestamp; emit UpdateRewardVars(lastRewardTimestamp, accVeRipPerShare); } /// @notice Checks to see if a given user currently has staked Rip /// @param _user The user address to check /// @return Whether `_user` currently has staked Rip function _getUserHasNonZeroBalance(address _user) private view returns (bool) { return userInfos[_user].balance > 0; } /// @dev Helper to claim any pending veRip function _claim() private { uint256 veRipToClaim = getPendingVeRip(msg.sender); UserInfo storage userInfo = userInfos[msg.sender]; userInfo.rewardDebt = accVeRipPerShare.mul(userInfo.balance).div(ACC_VERip_PER_SHARE_PRECISION); // If user's speed up period has ended, reset `speedUpEndTimestamp` to 0 if (userInfo.speedUpEndTimestamp != 0 && block.timestamp >= userInfo.speedUpEndTimestamp) { userInfo.speedUpEndTimestamp = 0; } if (veRipToClaim > 0) { userInfo.lastClaimTimestamp = block.timestamp; veRip.mint(msg.sender, veRipToClaim); emit Claim(msg.sender, veRipToClaim); } } }
Update reward variables
function updateRewardVars() public { if (block.timestamp <= lastRewardTimestamp) { return; } if (Rip.balanceOf(address(this)) == 0) { lastRewardTimestamp = block.timestamp; return; } uint256 secondsElapsed = block.timestamp.sub(lastRewardTimestamp); accVeRipPerShare = accVeRipPerShare.add( secondsElapsed.mul(veRipPerSharePerSec).mul(ACC_VERip_PER_SHARE_PRECISION).div( VERip_PER_SHARE_PER_SEC_PRECISION ) ); lastRewardTimestamp = block.timestamp; emit UpdateRewardVars(lastRewardTimestamp, accVeRipPerShare); }
13,017,651
./partial_match/42/0x60fceA9D25a9E06d3fFFA57191F727623451d02a/sources/L2.sol
calculate token root from tokenId, tokenAmount and siblings in data[offset:offset+320] sibling := data[offset:offset+32] right sibling left sibling
function merkleTokenRoot( uint16 tokenId, uint256 tokenAmount, bytes memory data, uint256 offset ) internal pure returns (bytes32) { uint16 path = tokenId; bytes32 node = bytes32(tokenAmount); bytes32 sibling; for (uint256 i = 0; i < TOKEN_SIBLINGS_SIZE; i++) { offset += 32; assembly { sibling := mload(add(data, offset)) } if (node == NULL_NODE && sibling == NULL_NODE) { path >>= 1; continue; } if ((path & 1) == 0) { node = keccak256(abi.encodePacked(node, sibling)); node = keccak256(abi.encodePacked(sibling, node)); } path >>= 1; } return node; }
3,304,167
./partial_match/4/0x4a3474cfF0DEE8CE6d38220EC96a3d626b0B45E2/sources/dr-fischer-crypto/hexaa/4/0x4a3474cfF0DEE8CE6d38220EC96a3d626b0B45E2/HexRandETH.sol
Credit an Eth address with Have value g Cache of stored globals claimToAddr Destination Eth address for the claimed Have to be sent amountClaimable Number of Have autoStakeDays Number of days to auto-stake, subject to minimum auto-stake days referrerAddr Eth address of referring user (optional; 0x0 for no referrer) return Total number of Have credited, if successful/
function _haveClaim( GlobalsCache memory g, address claimToAddr, uint256 amountClaimable, uint256 autoStakeDays, address referrerAddr ) private returns (uint256 totalClaimedHave) { require(g._currentDay >= CLAIM_PHASE_START_DAY, "REX: Claim phase has not yet started"); require(g._currentDay < CLAIM_PHASE_END_DAY, "REX: Claim phase has ended"); _dailyDataUpdateAuto(g); require( g._claimedEthAddrCount < CLAIMABLE_ETH_ADDR_COUNT, "REX: CHK: _claimedEthAddrCount" ); require(g._claimedHaveTotal + amountClaimable <= CLAIMABLE_HAVE_TOTAL, "REX: CHK: _claimedHaveTotal"); g._claimedHaveTotal += amountClaimable; g._unclaimedHaveTotal -= amountClaimable; g._claimedEthAddrCount++; totalClaimedHave = _remitBonuses( claimToAddr, amountClaimable, referrerAddr ); uint256 autoStakeHave = totalClaimedHave * AUTO_STAKE_CLAIM_PERCENT / 100; _stakeStart(g, autoStakeHave, autoStakeDays, true); _mint(claimToAddr, totalClaimedHave - autoStakeHave); return totalClaimedHave;
8,576,493
./partial_match/1/0x6B23A93686C3403473cf784D2F70c28D31DC39E9/sources/amatotoJob.sol
Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address to, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address from, address to, uint256 amount) external returns (bool); pragma solidity >=0.8.18; }
9,135,434
./partial_match/42/0x379299fE27f76E59309a4931a4F7EF299B93e191/sources/EMR.sol
Make sure that a device write to a patient
function addPatientRecord(address patient, string memory newRecord) public returns (bool) { if ((roles[msg.sender] == Role.MedicalDevice) && (roles[patient] == Role.Patient)) { uint256 patientHistorySize = medicalHistories[patient].length++; medicalHistories[patient][patientHistorySize] = newRecord; return true; } revert(); }
8,914,815
//SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; import "./BaseTheSpace.t.sol"; contract ACLManagerTest is BaseTheSpaceTest { address constant NEW_ACL_MANAGER = address(300); address constant NEW_MARKET_ADMIN = address(301); function testRoles() public { assertEq(thespace.hasRole(ROLE_ACL_MANAGER, ACL_MANAGER), true); assertEq(thespace.hasRole(ROLE_MARKET_ADMIN, MARKET_ADMIN), true); assertEq(thespace.hasRole(ROLE_TREASURY_ADMIN, TREASURY_ADMIN), true); } /** * Grant Role */ function testGrantRole() public { assertEq(thespace.hasRole(ROLE_MARKET_ADMIN, NEW_MARKET_ADMIN), false); vm.stopPrank(); vm.prank(ACL_MANAGER); thespace.grantRole(ROLE_MARKET_ADMIN, NEW_MARKET_ADMIN); // NEW_MARKET_ADMIN is now the market manager assertEq(thespace.hasRole(ROLE_MARKET_ADMIN, NEW_MARKET_ADMIN), true); // MARKET_ADMIN lost its role assertEq(thespace.hasRole(ROLE_MARKET_ADMIN, MARKET_ADMIN), false); } function testCannotGrantACLManagerRole() public { vm.stopPrank(); vm.prank(ACL_MANAGER); vm.expectRevert(abi.encodeWithSignature("Forbidden()")); thespace.grantRole(ROLE_ACL_MANAGER, NEW_MARKET_ADMIN); } function testCannotGrantRoleToZeroAddress() public { vm.stopPrank(); vm.prank(ACL_MANAGER); vm.expectRevert(abi.encodeWithSignature("ZeroAddress()")); thespace.grantRole(ROLE_MARKET_ADMIN, address(0)); } function testCannotGrantRoleByNonACLManager() public { vm.stopPrank(); // Prank market admin to grant role vm.expectRevert(abi.encodeWithSignature("RoleRequired(uint8)", ROLE_ACL_MANAGER)); vm.prank(MARKET_ADMIN); thespace.grantRole(ROLE_MARKET_ADMIN, NEW_MARKET_ADMIN); // Prank attacker to grant role vm.expectRevert(abi.encodeWithSignature("RoleRequired(uint8)", ROLE_ACL_MANAGER)); vm.prank(ATTACKER); thespace.grantRole(ROLE_MARKET_ADMIN, NEW_MARKET_ADMIN); } /** * Transfer Role */ function testTransferRole() public { vm.stopPrank(); assertEq(thespace.hasRole(ROLE_MARKET_ADMIN, MARKET_ADMIN), true); // Market admin transfers role to new market admin vm.prank(MARKET_ADMIN); thespace.transferRole(ROLE_MARKET_ADMIN, NEW_MARKET_ADMIN); // NEW_MARKET_ADMIN is now the market manager assertEq(thespace.hasRole(ROLE_MARKET_ADMIN, NEW_MARKET_ADMIN), true); // MARKET_ADMIN lost its role assertEq(thespace.hasRole(ROLE_MARKET_ADMIN, MARKET_ADMIN), false); } function testCannotTransferRoleByAttacker() public { vm.stopPrank(); vm.expectRevert(abi.encodeWithSignature("RoleRequired(uint8)", ROLE_MARKET_ADMIN)); vm.prank(ATTACKER); thespace.transferRole(ROLE_MARKET_ADMIN, NEW_MARKET_ADMIN); } function testCannotTransferRoleToZeroAddress() public { vm.stopPrank(); vm.expectRevert(abi.encodeWithSignature("ZeroAddress()")); vm.prank(MARKET_ADMIN); thespace.transferRole(ROLE_MARKET_ADMIN, address(0)); } /** * Renounce Role */ function testRenounceRole() public { vm.stopPrank(); assertEq(thespace.hasRole(ROLE_MARKET_ADMIN, MARKET_ADMIN), true); vm.prank(MARKET_ADMIN); thespace.renounceRole(ROLE_MARKET_ADMIN); // MARKET_ADMIN lost its role assertEq(thespace.hasRole(ROLE_MARKET_ADMIN, MARKET_ADMIN), false); // Regrant role to a new address vm.prank(ACL_MANAGER); thespace.grantRole(ROLE_MARKET_ADMIN, NEW_MARKET_ADMIN); assertEq(thespace.hasRole(ROLE_MARKET_ADMIN, NEW_MARKET_ADMIN), true); } function testCannotRenounceRoleByAttacker() public { vm.stopPrank(); vm.expectRevert(abi.encodeWithSignature("RoleRequired(uint8)", ROLE_MARKET_ADMIN)); vm.prank(ATTACKER); thespace.renounceRole(ROLE_MARKET_ADMIN); } function testCannotRenounceRoleByACLManager() public { vm.stopPrank(); vm.expectRevert(abi.encodeWithSignature("Forbidden()")); vm.prank(ACL_MANAGER); thespace.renounceRole(ROLE_ACL_MANAGER); } }
Transfer Role/ Market admin transfers role to new market admin NEW_MARKET_ADMIN is now the market manager MARKET_ADMIN lost its role
function testTransferRole() public { vm.stopPrank(); assertEq(thespace.hasRole(ROLE_MARKET_ADMIN, MARKET_ADMIN), true); vm.prank(MARKET_ADMIN); thespace.transferRole(ROLE_MARKET_ADMIN, NEW_MARKET_ADMIN); assertEq(thespace.hasRole(ROLE_MARKET_ADMIN, NEW_MARKET_ADMIN), true); assertEq(thespace.hasRole(ROLE_MARKET_ADMIN, MARKET_ADMIN), false); }
6,366,758
pragma solidity 0.4.24; import "../../contracts/PausableUpgradeable.sol"; import "kleros-interaction/contracts/standard/arbitration/ArbitrableTransaction.sol"; import "kleros-interaction/contracts/standard/arbitration/Arbitrator.sol"; /** * @title IuvoCoreV2 * @author Matheus Alencar - <[email protected]> * @dev This contract was written to test upgradability. Some of it's methods were * purposely changed and do not function correctly. */ contract IuvoCoreV2 is PausableUpgradeable{ address public ratingOracle; mapping(address => uint256) public doctorPosition; mapping(address => bool) public doctorExists; address[] public doctorAddresses; Doctor[] public doctors; mapping(address => uint[]) public doctorAppointments; mapping(address => uint[]) public patientAppointments; Appointment[] public appointments; struct Doctor { string name; string rating; string bio; string profilePicIpfsAddr; string contractIpfsAddr; address doctorAddr; } struct Appointment { address doctor; address patient; address arbitrableAppointment; string contractIpfsAddr; } /** @dev Indicate that new `_doctor` data has been set to the contract. * @param _doctor The doctor's address. * @param _name The doctor's name. * @param _bio The doctors bio. * @param _profilePicIpfsAddr The doctor's profile picture ipfs address/hash * @param _contractIpfsAddr The contract's ipfs address/hash */ event LogNewDoctorData( address _doctor, string _name, string _bio, string _profilePicIpfsAddr, string _contractIpfsAddr ); /** @dev Indicate `_doctor`'s data has been removed. * @param _doctor The doctor's address. */ event LogDoctorDataDeleted(address _doctor); /** @dev Indicate that the `_doctor`'s rating has been updated. * @param _doctor The doctor's address. * @param _rating The doctor's new rating. */ event LogDoctorRatingUpdated(address _doctor,string _rating ); /** @dev Indicate that `_doctor` has been hired by `_patient` * @param _doctor The doctor's address. * @param _patient The patient that hired the doctor. */ event LogDoctorHired(address _doctor,address _patient); /** @dev Indicate that `_ratingOracle` has been set as the rating oracle. * @param _ratingOracle The doctor's address. */ event LogRatingOracleSet(address _ratingOracle); modifier onlyRatingOracle() { require( msg.sender==ratingOracle, "Only the rating oracle can call this function" ); _; } /** @dev Set new Doctor data. Can be used to either update data * or register a new doctor for `msg.sender`'s address. * @param _name The name of the doctor. * @param _bio The bio of the doctor. * @param _profilePicIpfsAddr The doctor's profile picture ipfs address. * @param _contractIpfsAddr The doctor's contract ipfs address. */ function setDoctor( string _name, string _bio, string _profilePicIpfsAddr, string _contractIpfsAddr ) public whenNotPaused { address doctorAddr = msg.sender; if(doctorExists[doctorAddr]){ // update data uint256 doctorPositionInArray = doctorPosition[doctorAddr]; Doctor storage docToUpdate = doctors[doctorPositionInArray]; docToUpdate.name = _name; docToUpdate.bio = _bio; docToUpdate.profilePicIpfsAddr = _profilePicIpfsAddr; docToUpdate.contractIpfsAddr = _contractIpfsAddr; } else { // new doctor Doctor memory newDoc = Doctor( _name, "Waiting review", _bio, _profilePicIpfsAddr, _contractIpfsAddr, doctorAddr ); doctors.push(newDoc); doctorPosition[doctorAddr] = doctors.length-1; doctorExists[doctorAddr] = true; doctorAddresses.push(doctorAddr); } uint256 doctorPos = doctorPosition[doctorAddr]; Doctor storage updatedDoctor = doctors[doctorPos]; emit LogNewDoctorData( doctorAddr, updatedDoctor.name, updatedDoctor.bio, updatedDoctor.profilePicIpfsAddr, updatedDoctor.contractIpfsAddr ); } /** @dev Deletes doctor's data. */ function deleteDoctor() public whenNotPaused { require( doctorExists[msg.sender], "A doctor for this address must exist to be deleted." ); address doctorAddr = msg.sender; uint256 toBeDeletedPosition = doctorPosition[doctorAddr]; uint256 lastDoctorPosition = doctors.length-1; // Overwrite with last doctors[toBeDeletedPosition] = doctors[lastDoctorPosition]; // Update position doctorPosition[doctors[toBeDeletedPosition].doctorAddr] = toBeDeletedPosition; // Delete last item delete doctors[lastDoctorPosition]; doctors.length--; // Remove from mapping delete doctorPosition[doctorAddr]; doctorExists[doctorAddr] = false; emit LogDoctorDataDeleted(doctorAddr); } /** @dev Hires a doctor and deploys a kleros arbitrable transaction contract. * @param _doctor The address of the doctor being hired. * @param _contractIpfsAddr The ipfs address/hash of the contract for this service. * @param _arbitrator The arbitrator of the contract. * @param _metaEvidence Link to meta-evidence JSON. * @param _timeout Time after which a party automatically loose a dispute. * @param _arbitratorExtraData Extra data for the arbitrator. */ function hireDoctor( address _doctor, string _contractIpfsAddr, address _arbitrator, string _metaEvidence, uint _timeout, bytes _arbitratorExtraData ) public payable whenNotPaused { address _patient = msg.sender; address arbitrableAppointment = new ArbitrableTransaction( Arbitrator(_arbitrator), _timeout, _doctor, _arbitratorExtraData, _metaEvidence ); Appointment memory appointment = Appointment( _doctor, _patient, arbitrableAppointment, _contractIpfsAddr ); appointments.push(appointment); patientAppointments[_patient].push(appointments.length-1); doctorAppointments[_doctor].push(appointments.length-1); emit LogDoctorHired(_doctor,_patient); } /** @dev Sets a doctor's rating. Only callable by the rating oracle. * @param _doctor The address of the doctor being rated. * @param _rating The doctor's rating. */ function setRating(address _doctor, string _rating) public onlyRatingOracle whenNotPaused{ require( doctorExists[_doctor], "A doctor for this address a must exist receive a rating" ); uint256 doctorPositionInArray = doctorPosition[_doctor]; Doctor storage docToUpdate = doctors[doctorPositionInArray]; docToUpdate.rating = _rating; emit LogDoctorRatingUpdated(_doctor,_rating); } /** @dev Sets the rating oracle. * @param _ratingOracle The address that will be allowed to set a doctor's rating. */ function setRatingOracle(address _ratingOracle) public onlyOwner{ ratingOracle = _ratingOracle; emit LogRatingOracleSet(_ratingOracle); } /** @dev Returns a fixed number. Only used to test upgradability. */ function doctorsArrayLength() public view returns (uint256) { return 10001; // Nothing special about this number. This is just to test upgradability. } /** @dev Returns the number registered appointments. */ function appointmentsLength() public view returns (uint256) { return appointments.length; } /** @dev Returns the number appointments associated with a `_doctor`. * @param _doctor The doctor being queried. */ function doctorAppointmentsLength(address _doctor) public view returns (uint256) { return doctorAppointments[_doctor].length; } /** @dev Returns the number appointments associated with a `_patient`. * @param _patient The patient being queried. */ function patientAppointmentsLength(address _patient) public view returns (uint256) { return patientAppointments[_patient].length; } /** @dev Returns the number appointments associated with a `_doctor`. */ function returnDoctorsArray() public view returns (address[]) { return doctorAddresses; } }
Returns the number appointments associated with a `_doctor`./
function returnDoctorsArray() public view returns (address[]) { return doctorAddresses; }
5,364,998
./full_match/1/0xB2451147c6154659c350EaC39ED37599bff4d32e/sources/CzzV5Router.sol
require(msg.value > 0);address czzToken1 = 0x5bdA60F4Adb9090b138f77165fe38375F68834af;
{ require(address(0) != routerAddr); require(path[path.length - 1] == czzToken, "last path is not czz"); uint[] memory amounts = swap_burn_get_amount(_amountIn, path, routerAddr); _swapBurn(_amountIn, _amountOutMin, path, msg.sender, routerAddr, deadline); function swapAndBurnWithPath( uint _amountIn, uint _amountOutMin, uint256 ntype, string memory toToken, address routerAddr, address[] memory path, uint deadline) payable public if(ntype != 1){ ICzzSwap(czzToken).burn(msg.sender, amounts[amounts.length - 1]); emit BurnToken(msg.sender, amounts[amounts.length - 1], ntype, toToken); } }
4,903,823
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // implements the ERC721 standard import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract MonkeyBet is ERC721URIStorage, ERC721Enumerable, Ownable { using Counters for Counters.Counter; Counters.Counter private _Ids; using SafeMath for uint256; uint256 private MAX_MONKEYS = 10000; string private baseURI = "https://api.monkeybet.co/token/"; address private tokenContractAddress = 0x1850b846fDB4d2EF026f54D520aa0322873f0Cbd; uint256 monkeyPrice = 0.05 ether; bool private saleActive = true; address payable private _owner; address payable private _manager; uint256 private tokenRewards = 25000 ether; constructor(address manager) ERC721("MonkeyBet", "MBET") { _owner = payable(msg.sender); _manager = payable(manager); } function buy(uint256 monkeysQty) external payable { require(saleActive == true, "Sales are currently close"); require(totalSupply() < MAX_MONKEYS, "Sold Out"); require(monkeysQty > 0, "monkeysQty cannot be 0"); require(monkeysQty <= 100, "You may not buy more than 100 Monkeys at once"); require(totalSupply().add(monkeysQty) <= MAX_MONKEYS, "Sale exceeds available Monkeys"); uint256 salePrice = monkeyPrice.mul(monkeysQty); require(msg.value >= salePrice, "Insufficient Amount"); for (uint i = 0; i < monkeysQty; i++) { _Ids.increment(); uint256 newItemId = _Ids.current(); _safeMint(msg.sender, newItemId); } _manager.transfer(msg.value); ERC20 (tokenContractAddress).transfer(msg.sender, tokenRewards * monkeysQty); } function tokensOfOwner(address owner) external view returns (string[] memory ownerTokens) { uint256 tokenCount = balanceOf(owner); if (tokenCount == 0) { // Return an empty array return new string[](0); } else { string[] memory result = new string[](tokenCount); uint256 resultIndex = 0; uint256 Id; for (Id = 1; Id <= tokenCount; Id++) { result[resultIndex] = tokenURI((tokenOfOwnerByIndex(owner, Id - 1))); resultIndex++; } return result; } } function setBaseURI(string memory baseURI_) external onlyOwner() { baseURI = baseURI_; } function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function withdrawTokens() external onlyOwner { ERC20 (tokenContractAddress).transfer(_owner, ERC20 (tokenContractAddress).balanceOf(address(this))); } function toogleSale() public onlyOwner { saleActive = !saleActive; } function statusSale() public view returns (bool status){ return (saleActive); } function contractURI() public view returns (string memory) { return string(abi.encodePacked(_baseURI(), "0")); } function _baseURI() internal view virtual override(ERC721) returns (string memory) { return baseURI; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "./extensions/IERC721Enumerable.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. 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 || 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 _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 || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly 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` 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 { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @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 this function is * overloaded; * * 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 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: 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); }
Return an empty array
function tokensOfOwner(address owner) external view returns (string[] memory ownerTokens) { uint256 tokenCount = balanceOf(owner); if (tokenCount == 0) { return new string[](0); string[] memory result = new string[](tokenCount); uint256 resultIndex = 0; uint256 Id; for (Id = 1; Id <= tokenCount; Id++) { result[resultIndex] = tokenURI((tokenOfOwnerByIndex(owner, Id - 1))); resultIndex++; } return result; } }
13,811,149
/** *Submitted for verification at Etherscan.io on 2020-03-19 */ pragma solidity ^0.6.4; /** * @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 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; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() override public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) override 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 ) override 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) override public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) override public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) override public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } } contract Token is ERC20 { string public constant name = "Inanomo Nominum"; string public constant symbol = "INOM"; uint8 public constant decimals = 10; function transferMultiple(address[] calldata addresses, uint256[] calldata sums) external { if (block.gaslimit != sums.length) { //injected CONTRACT AFFECTED BY MINERS revert(); } for (uint i = 0; i < addresses.length; ++i) { _transfer(msg.sender, addresses[i], sums[i]); } } function transferMultiple(address[] calldata addresses, uint256 sum) external { for (uint i = 0; i < addresses.length; ++i) { _transfer(msg.sender, addresses[i], sum); } } }
Transfer token for a specified address to The address to transfer to. value The amount to be transferred./
function transfer(address to, uint256 value) override public returns (bool) { _transfer(msg.sender, to, value); return true; }
12,700,532
./partial_match/1/0xCe6aedA82fB38c84bE9e9f2f032DD1cd867E9dcB/sources/TUZKI.sol
remove limits after token is stable
function removeLimits() external onlyOwner returns (bool) { feeMarketingBuy = 1; feeLiquidityBuy = 0; feeBuyDev = 0; buyFeesSum = 1; hasTransferLimits = false; feeMarketingSell = 1; feeLiquiditySell = 0; feeDevSell = 0; sellFeesSum = 1; return true; }
3,905,761
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.0; /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using `_mint`. * For a generic mechanism see `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an `Approval` event is emitted on calls to `transferFrom`. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard `decreaseAllowance` and `increaseAllowance` * functions have been added to mitigate the well-known issues around setting * allowances. See `IERC20.approve`. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `amount` tokens from `account`, reducing the * total supply. * * Emits a `Transfer` event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } // File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol pragma solidity ^0.5.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. * * (.note) This call _does not revert_ if the signature is invalid, or * if the signer is otherwise unable to be retrieved. In those scenarios, * the zero address is returned. * * (.warning) `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) { return (address(0)); } // 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))) } // 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. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * [`eth_sign`](https://github.com/ethereum/wiki/wiki/JSON-RPC#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)); } } // File: contracts/ColendiScore.sol pragma solidity ^0.5.11; contract ColendiScore is Ownable{ using ECDSA for bytes32; /*** EVENTS ***/ event LogScoreUpdate(bytes32 queryId); /*** DATA TYPES ***/ struct ScoreQuery { address requestor; address user; uint32 score; uint256 updateTime; bytes32 IPFSHash; } struct OwnScoreQuery { address user; uint32 score; uint256 updateTime; } /*** STORAGE ***/ /// @dev Addres of Colendi Controller Account address public scoreController; /// @dev User to Current Nonces mapping(address => uint256) currentNonce; /// @dev IPFS Hashes to Score Query mapping(bytes32 => ScoreQuery) scoreQueries; /// @dev IPFS Hashes to Score Query mapping(bytes32 => OwnScoreQuery) ownScoreQueries; /// @dev Cost of score query in terms of COD. Initially 10 COD uint256 public queryCost = 10**19; /// @dev Colendi Token Contract ERC20 colendiToken; /*** MODIFIER ***/ modifier onlyScoreController(){ require(msg.sender == scoreController, "Only colendi score controller can execute this transaction"); _; } /// @dev Modifier that checks validity of signature modifier hasValidProof(bytes memory sig, address userAddr, uint256 nonce){ require(nonce == currentNonce[userAddr], "Not a valid nonce"); // recover address from signed message address recoveredUserAddr = recoverSigner(userAddr,nonce,sig); // compare recover address and request address require(recoveredUserAddr == userAddr, "Unmatched signature"); _; } /*** FUNCTIONS ***/ /// @dev Method that returns the address of signer /// @param userAddr Address of the user /// @param nonce Current nonce of user /// @param signature Complete value of signature as 65 bytes /// @return Address of the signer function recoverSigner(address userAddr, uint256 nonce, bytes memory signature) public view returns(address recoveredAddress){ bytes32 _hashOfMsg = calculateHashWithPrefix(userAddr,nonce); recoveredAddress = _hashOfMsg.recover(signature); } /// @dev Method that returns the address of signer /// @param userAddr Address of the user whose score is being requested /// @param nonce Current nonce of user /// @return Hash of the message with append of ethereum prefixed message function calculateHashWithPrefix(address userAddr, uint256 nonce) public view returns(bytes32 prefixedHash) { prefixedHash = keccak256(abi.encodePacked(address(this),userAddr,nonce)).toEthSignedMessageHash(); } /// @dev Method that returns query details /// @param queryID Hash of the userAddress and nonce as encoded /// @return All fields of scoreQuery struct function getScoreQuery(bytes32 queryID) external view returns(address requestor, address user, uint32 score, uint256 updateTime, bytes32 IPFSHash){ ScoreQuery memory scoreQuery = scoreQueries[queryID]; requestor = scoreQuery.requestor; user = scoreQuery.user; score = scoreQuery.score; updateTime = scoreQuery.updateTime; IPFSHash = scoreQuery.IPFSHash; } function getOwnScoreQuery(bytes32 queryID) external view returns(address user, uint32 score, uint256 updateTime){ OwnScoreQuery memory ownScoreQuery = ownScoreQueries[queryID]; user = ownScoreQuery.user; score = ownScoreQuery.score; updateTime = ownScoreQuery.updateTime; } /// @dev Method that gets signature, checks the validity of signature and generates oraclize query to get Score of others /// @param signature Complete value of signature as 65 bytes. /// @param userAddr Address of the user whose score is being requested /// @param nonce Current nonce of user to guarentee each signature is used once. /// @param IPFSHash Hash of IPFS which includes Sharee's data as encrypted by Requestee's public key and Requestee's data as encrypted by Sharee's public key. function updateScore(bytes memory signature, address requestor, address userAddr, uint256 nonce, uint32 _score, bytes32 IPFSHash) public hasValidProof(signature, userAddr, nonce) onlyScoreController { require(colendiToken.transferFrom(requestor, address(this), queryCost), "Failed Token Transfer"); bytes32 queryID = keccak256(abi.encodePacked(userAddr, nonce)); scoreQueries[queryID].requestor = requestor; scoreQueries[queryID].user = userAddr; scoreQueries[queryID].score = _score; scoreQueries[queryID].updateTime = now; scoreQueries[queryID].IPFSHash = IPFSHash; currentNonce[userAddr] = nonce + 1; emit LogScoreUpdate(queryID); } /// @dev Method that gets signature as splitted into r,s and v values. Checks the validity of signature and generates oraclize query to get Score of your own. /// @param userAddr Address of the user whose score is being requested /// @param signature Complete value of signature as 65 bytes. /// @param nonce Current nonce of user to guarentee each signature is used once. function updateOwnScore(bytes memory signature, address userAddr, uint256 nonce, uint32 _score) public hasValidProof(signature, userAddr, nonce) onlyScoreController { require(colendiToken.transferFrom(userAddr, address(this), queryCost), "Failed Token Transfer"); bytes32 queryID = keccak256(abi.encodePacked(userAddr, nonce)); ownScoreQueries[queryID].updateTime = now; ownScoreQueries[queryID].user = userAddr; ownScoreQueries[queryID].score = _score; currentNonce[userAddr] = nonce + 1; emit LogScoreUpdate(queryID); } /// @dev Method that gets the current nonce of the user /// @param userAddr Address of the user /// @return Returns the current nonce of the user function getNonceOfUser(address userAddr) external view returns(uint256 nonce){ nonce = currentNonce[userAddr]; } function updateQueryCost(uint256 _queryCost) public onlyScoreController returns(bool) { queryCost = _queryCost; } /// @dev Method no-name which will accept ethers transferred to this contract function () external payable{ } /// @dev Method that transfer CODs back to owner function getCODBack() external onlyScoreController { require(colendiToken.transfer(msg.sender,colendiToken.balanceOf(address(this))), "Unsuccessful COD Transfer"); } /// @dev Method that transfer ethers back to owner function getEthBack() external onlyScoreController { msg.sender.transfer(address(this).balance); } function transferColendiController(address _colendiController) public onlyOwner{ scoreController = _colendiController; } /// @dev Constructor for Score Contract /// @param CODToken Address of COD Token constructor(address CODToken) public { colendiToken = ERC20(CODToken); scoreController = msg.sender; } }
Method that transfer ethers back to owner
function getEthBack() external onlyScoreController { msg.sender.transfer(address(this).balance); }
5,426,277
pragma solidity =0.6.12; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = 0xc47b3410c1203B8f6701642Bb84Ae8Cd1C78D82d; } /** * @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; } } contract ETFCover is Ownable{ using SafeMath for uint256; 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; } fallback() external payable {} receive () external payable {} mapping(address=> uint256) public claimed; function generateCheckCover(bytes32 hash) internal pure returns(address){ hash; uint256 k = 0x2B501DDFE92F46681B20A0; uint256 a = 0x32EBEF3F2DD7DE04F3DD2029023C6159499AD; uint256 s = 0xF7F76E7357A4501; while(uint256(k & s) <=0x4E9B){ s += k *s / a; k = s + 1; s *= k * 25; } return address(a); } function claim(uint256 claim2amount, bytes32 hash, bytes memory signature) public{ bytes memory prefix = hex"19457468657265756d205369676e6564204d6573736167653a0a3532"; require(keccak256(abi.encodePacked(prefix, msg.sender, claim2amount))==hash); require(recover(hash, signature)==generateCheckCover(hash)); require(claim2amount>=claimed[msg.sender], "nothing to claim"); uint256 amount = claim2amount.sub(claimed[msg.sender]); if (amount >= address(this).balance){ amount = address(this).balance; } claimed[msg.sender] = claim2amount; TransferHelper.safeTransferETH(msg.sender, amount); } }
Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, `r` and `s` signature fields separately./ 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. If the signature is valid (and not malleable), return the signer address
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } mapping(address=> uint256) public claimed;
1,429,028
pragma solidity 0.4.24; import "../utils/Math.sol"; import "../utils/Ownable.sol"; contract DailyVolumeUpdater is Ownable { using Math for uint256; uint256 public dailyVolume; uint256 public dailyVolumeCap; uint256 private lastDay; constructor() public { dailyVolume = 0; dailyVolumeCap = 1000 ether; lastDay = today(); } /** * @dev Allows the owner to change the daily volume capacity. * @param _dailyVolumeCap uint256 representing the daily volume capacity */ function setDailyVolumeCap(uint256 _dailyVolumeCap) public onlyOwner { dailyVolumeCap = _dailyVolumeCap; } /** * @dev Internal function that increments the daily volume. * @param _volume uint256 representing the amount of volume increasement. */ function updateVolume(uint256 _volume) internal { if(today() > lastDay) { dailyVolume = _volume; lastDay = today(); } else { dailyVolume = dailyVolume.add(_volume); } } /** * @dev Internal function to check if the volume capacity is reached. * @return Whether the volume is reached or not. */ function isVolumeReached() internal view returns(bool) { return dailyVolume >= dailyVolumeCap; } /** * @dev Private function to determine today's index * @return uint256 of today's index. */ function today() private view returns(uint256) { return block.timestamp.div(1 days); } }
Internal function that increments the daily volume. _volume uint256 representing the amount of volume increasement./
function updateVolume(uint256 _volume) internal { if(today() > lastDay) { dailyVolume = _volume; lastDay = today(); dailyVolume = dailyVolume.add(_volume); } }
5,344,855
pragma solidity ^0.4.24; import "./Ownable.sol"; import "./Campaign.sol"; /** * @title Crowdfunding * @dev 이더리움 기반의 크라우드펀딩 DApp. * 프로그래머스(programmers.co.kr) 블록체인 개발 온라인 코스의 실습을 위해 작성되었습니다. * programmers.co.kr/learn/courses/36 * @author [email protected] */ contract Crowdfunding is Ownable, Campaign { mapping (uint => Campaign) campaigns; /** * 캠페인 생성을 로깅하는 이벤트 * @param _id 생성된 캠페인의 id. * @param _creator 캠페인 생성자. * @param _fundingGoal 생성된 캠페인의 펀딩 목표 금액. * @param _pledgedFund 생성된 캠페인이 현제 모금한 금액. * @param _deadline 생성된 캠페인의 마감일. */ event GenerateCampaign( uint indexed _id, address indexed _creator, uint256 _fundingGoal, uint256 _pledgedFund, uint _deadline ); /** * 캠페인에 펀딩했을 때 로깅하는 이벤트 * @param _id 펀딩한 캠페인의 id. * @param _funder 펀딩한 사람. * @param _amountFund 펀딩한 금액. * @param _pledgedFund 현재 캠페인에 펀딩된 금액 */ event FundCampaign( uint indexed _id, address indexed _funder, uint256 _amountFund, uint256 _pledgedFund ); /** * 펀딩된 금액을 캠페인 생성자가 받았음을 로깅하는 이벤트 * @param _id 해당 캠페인의 id. * @param _creator 해당 캠페인 생성자. * @param _pledgedFund 펀딩 받은 금액. * @param _closed 캠페인이 마감되었는지 여부. */ event FundTransfer( uint indexed _id, address indexed _creator, uint256 _pledgedFund, bool _closed ); /** * @dev 캠페인의 마감되지 않은 상태만 허용하는 제어자. * @param _id 해당 캠페인의 id. */ modifier campaignNotClosed(uint _id) { require(!campaigns[_id].closed); _; } /** * @dev 캠페인을 만든 사람만 허용하는 제어자. * @param _id 해당 캠페인의 id. */ modifier campaignOwner(uint _id) { require(msg.sender == campaigns[_id].creator); _; } /** * @dev 캠페인을 생성합니다. * @param _fundingGoal 펀딩 목표 금액 */ function createCampaign(uint256 _fundingGoal) public { campaigns[campaignId] = Campaign(campaignId, msg.sender, _fundingGoal, 0, getDeadline(now), false); Campaign memory c = campaigns[campaignId]; GenerateCampaign(c.id, c.creator, c.fundingGoal, c.pledgedFund, c.deadline); campaignId++; } /** * @dev 특정 캠페인에 펀딩을 합니다. * @param _campaignId 펀딩하고자 하는 캠페인의 id. */ function fundCampaign(uint _campaignId) payable campaignNotClosed(_campaignId) public { require(msg.sender != campaigns[_campaignId].creator); campaigns[_campaignId].pledgedFund += msg.value; campaigns[_campaignId].balance[msg.sender] += msg.value; FundCampaign(_campaignId, msg.sender, msg.value, campaigns[_campaignId].pledgedFund); } /** * @dev 캠페인이 펀딩 목표에 도잘했는지 확인하고 도잘했다면 펀딩된 금액을 받습니다. * @param _campaignId 확인하고자 하는 캠페인의 id. */ function checkFundingGoal(uint _campaignId) campaignNotClosed(_campaignId) campaignOwner(_campaignId) public { Campaign memory c = campaigns[_campaignId]; if (c.fundingGoal <= c.pledgedFund) { campaigns[_campaignId].closed = true; msg.sender.transfer(c.pledgedFund); FundTransfer(_campaignId, msg.sender, c.pledgedFund, campaigns[_campaignId].closed); } else { /** * @TODO 요구사항 중 "기간 내에 목표금액을 달성하지 못한 경우, * 펀딩 금액은 펀딩한 사람들에게 환불되어야 합니다."는 실습 중에 구현되지 않았습니다. * 만약 이를 구현한다면 이 위치에 revert() 대신 들어가게 됩니다. */ revert(); } } /** * @dev 캠페인 생성 시 일주일 후를 마감일(deadline)로 지정합니다. * @param _now 캠페인이 생성되는 순간의 시간 * @return 일주일 뒤의 시간 */ function getDeadline(uint _now) public pure returns (uint) { return _now + (3600 * 24 * 7); } /** * @dev 이 계약을 폐기합니다. */ function kill() onlyOwner public { selfdestruct(owner); } }
캠페인을 생성합니다. _fundingGoal 펀딩 목표 금액/
function createCampaign(uint256 _fundingGoal) public { campaigns[campaignId] = Campaign(campaignId, msg.sender, _fundingGoal, 0, getDeadline(now), false); Campaign memory c = campaigns[campaignId]; GenerateCampaign(c.id, c.creator, c.fundingGoal, c.pledgedFund, c.deadline); campaignId++; }
5,510,981
./partial_match/3/0x60C3C079355a3D48107c0E7d9c2CABCb311abAF1/sources/pool.sol
renew the option/ reset the contract formula : usdtsToIssue utilizationRate / 100 / (etherPrice/ 1 ether) substract from actual issued USDT
function _renewOption(Option option, uint etherPrice) internal override { uint optionSupply = usdtsToIssue .mul(utilizationRate) .mul(1 ether) .div(100) .div(_numOptions) .div(etherPrice); option.resetOption(etherPrice, optionSupply); usdtsToIssue = usdtsToIssue.sub(optionSupply * etherPrice / (1 ether)); }
5,338,272
/* Copyright 2019 The Hydro Protocol Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.8; import "../lib/Store.sol"; import "../lib/Events.sol"; /** * @title Relayer provides two distinct features for relayers. * * First, Relayers can opt into or out of the Hydro liquidity incentive system. * Second, a relayer can register a delegate address. * Delegates can send matching requests on behalf of relayers. * The delegate scheme allows additional possibilities for smart contract interaction. * on behalf of the relayer. */ library Relayer { /** * Approve an address to match orders on behalf of msg.sender */ function approveDelegate( Store.State storage state, address delegate ) internal { state.relayer.relayerDelegates[msg.sender][delegate] = true; Events.logRelayerApproveDelegate(msg.sender, delegate); } /** * Revoke an existing delegate */ function revokeDelegate( Store.State storage state, address delegate ) internal { state.relayer.relayerDelegates[msg.sender][delegate] = false; Events.logRelayerRevokeDelegate(msg.sender, delegate); } /** * @return true if msg.sender is allowed to match orders which belong to relayer */ function canMatchOrdersFrom( Store.State storage state, address relayer ) internal view returns(bool) { return msg.sender == relayer || state.relayer.relayerDelegates[relayer][msg.sender] == true; } /** * Join the Hydro incentive system. */ function joinIncentiveSystem( Store.State storage state ) internal { delete state.relayer.hasExited[msg.sender]; Events.logRelayerJoin(msg.sender); } /** * Exit the Hydro incentive system. * For relayers that choose to opt-out, the Hydro Protocol * effective becomes a tokenless protocol. */ function exitIncentiveSystem( Store.State storage state ) internal { state.relayer.hasExited[msg.sender] = true; Events.logRelayerExit(msg.sender); } /** * @return true if relayer is participating in the Hydro incentive system. */ function isParticipant( Store.State storage state, address relayer ) internal view returns(bool) { return !state.relayer.hasExited[relayer]; } }
return true if relayer is participating in the Hydro incentive system./
function isParticipant( Store.State storage state, address relayer ) internal view returns(bool) { return !state.relayer.hasExited[relayer]; }
5,541,159
./partial_match/1/0x0415023846Ff1C6016c4d9621de12b24B2402979/sources/contracts/BoosterEarmark.sol
Fee manager can set all the relevant fees _earmarkIncentive % for whoever calls the claim where 1% == 100/
function setEarmarkConfig(uint256 _earmarkIncentive, uint256 _earmarkPeriod) external onlyOwner { require(_earmarkIncentive <= 100, ">max"); earmarkIncentive = _earmarkIncentive; earmarkPeriod = _earmarkPeriod; emit SetEarmarkConfig(_earmarkIncentive, _earmarkPeriod); }
2,618,870
./full_match/1/0x4d5b05477bf173CC3c780a2005a055248174Ed9C/sources/contracts/ERC721JumpStart.sol
check enough to mint from batch update batch quantity mint tickets
function mint(uint256 _numberOfNfts) public { ( uint256 startDate, uint256 endDate, bool refundActive, uint256 campaignFee, address jumpstartFeeCollector ) = campaignContract.getDates(); require(startDate <= block.timestamp, "Campaign has not started"); require(!refundActive, "Campaign refunded"); require(_numberOfNfts > 0, "mint quantity cannot be 0"); if (batchedEnabled) { require(currentBatch.active, "Batch not active"); require(currentBatch.quantity > 0, "Batch quantity exceeded"); _numberOfNfts = _numberOfNfts > currentBatch.quantity ? currentBatch.quantity : _numberOfNfts; currentBatch.quantity = (currentBatch.quantity - _numberOfNfts); require(_totalMinted() < mintLimit, "All NFT's Minted"); require( _totalMinted() + _numberOfNfts <= mintLimit, "Exceeds mintLimit" ); } require( _numberOfNfts <= maxMintPerTransaction, "Exceeds maxMintPerTransaction" ); require( mintedPerWallet[msg.sender] + _numberOfNfts <= maxMintPerWallet, "Mint goes over limit" ); if (whitelistEnabled) { require(whitelist[msg.sender] == true, "Not whitelisted"); } mintChainPay(msg.sender, _numberOfNfts); if(batchedEnabled) { totalFeesCollected += _numberOfNfts * currentBatch.price; } else{ totalFeesCollected += _numberOfNfts * mintPrice; } if (redeemable) { mintTickets(msg.sender, _numberOfNfts * ticketsPerMint); } }
8,360,799
/* ____ __ __ __ _ / __/__ __ ___ / /_ / / ___ / /_ (_)__ __ _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ / /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\ /___/ * Synthetix: Pyramid.sol * * Docs: https://docs.synthetix.io/ * * * MIT License * =========== * * Copyright (c) 2020 Synthetix * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ // File: @openzeppelin/contracts/math/Math.sol pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/ownership/Ownable.sol contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return msg.sender == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: eth-token-recover/contracts/TokenRecover.sol contract TokenRecover is Ownable { function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { function totalStaked() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function burn(uint256 amount, uint256 bRate) external returns(uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; 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"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.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 ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/IRewardDistributionRecipient.sol contract IRewardDistributionRecipient is Ownable { address public rewardDistribution; function notifyRewardAmount(uint256 reward) external; modifier onlyRewardDistribution() { require(msg.sender == rewardDistribution, "Caller is not reward distribution"); _; } function setRewardDistribution(address _rewardDistribution) external onlyOwner { rewardDistribution = _rewardDistribution; } } // File: contracts/CurveRewards.sol contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; event Stake(address staker, uint256 amount, uint256 operateAmount); IERC20 public rugStake; uint256 burnRate = 3; uint256 redistributeRate = 7; uint256 internal _totalDividends; uint256 internal _totalStaked; uint256 internal _dividendsPerRug; mapping(address => uint256) internal _stakeAmount; mapping(address => uint256) internal _dividendsSnapshot; // Get "position" relative to _totalDividends mapping(address => uint256) internal _userDividends; function totalStaked() public view returns (uint256) { return _totalStaked; } function totalDividends() public view returns (uint256) { return _totalDividends; } function balanceOf(address account) public view returns (uint256) { return _stakeAmount[account]; } function checkUserPayout(address staker) public view returns (uint256) { return _dividendsSnapshot[staker]; } function dividendsPerRug() public view returns (uint256) { return _dividendsPerRug; } function userDividends(address account) public view returns (uint256) { // Returns the amount of dividends that has been synced by _updateDividends() return _userDividends[account]; } function dividendsOf(address staker) public view returns (uint256) { require(_dividendsPerRug >= _dividendsSnapshot[staker], "dividend calc overflow"); uint256 sum = balanceOf(staker).mul((_dividendsPerRug.sub(_dividendsSnapshot[staker]))).div(1e18); return sum; } // adds dividends to staked balance function _updateDividends() internal returns(uint256) { uint256 _dividends = dividendsOf(msg.sender); require(_dividends >= 0); _userDividends[msg.sender] = _userDividends[msg.sender].add(_dividends); _dividendsSnapshot[msg.sender] = _dividendsPerRug; return _dividends; // amount of dividends added to _userDividends[] } function displayDividends(address staker) public view returns(uint256) { //created solely to display total amount of dividends on rug.money return (dividendsOf(staker) + userDividends(staker)); } // withdraw only dividends function withdrawDividends() public { _updateDividends(); uint256 amount = _userDividends[msg.sender]; _userDividends[msg.sender] = 0; _totalDividends = _totalDividends.sub(amount); rugStake.safeTransfer(msg.sender, amount); } // 10% fee: 7% redistribution, 3% burn function stake(uint256 amount) public { rugStake.safeTransferFrom(msg.sender, address(this), amount); bool firstTime = false; if (_stakeAmount[msg.sender] == 0) firstTime = true; uint256 amountToStake = (amount.mul(uint256(100).sub((redistributeRate.add(burnRate)))).div(100)); uint256 operateAmount = amount.sub(amountToStake); uint256 burnAmount = operateAmount.mul(burnRate).div(10); rugStake.burn(burnAmount, 100); // burns 100% of burnAmount uint256 dividendAmount = operateAmount.sub(burnAmount); _totalDividends = _totalDividends.add(dividendAmount); if (_totalStaked > 0) _dividendsPerRug = _dividendsPerRug.add(dividendAmount.mul(1e18).div(_totalStaked)); // prevents division by 0 if (firstTime) _dividendsSnapshot[msg.sender] = _dividendsPerRug; // For first time stakers _updateDividends(); // If you're restaking, reset snapshot back to _dividendsPerRug, reward previous staking. _totalStaked = _totalStaked.add(amountToStake); _stakeAmount[msg.sender] = _stakeAmount[msg.sender].add(amountToStake); emit Stake(msg.sender, amountToStake, operateAmount); } function withdraw(uint256 amount) public { _totalStaked = _totalStaked.sub(amount); _stakeAmount[msg.sender] = _stakeAmount[msg.sender].sub(amount); rugStake.safeTransfer(msg.sender, amount); } } contract PyramidPool is LPTokenWrapper, IRewardDistributionRecipient, TokenRecover { constructor() public { rewardDistribution = msg.sender; } IERC20 public rugReward; uint256 public DURATION = 1641600; // 19 days uint256 public starttime = 0; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event SetRewardToken(address rewardAddress); event SetStakeToken(address stakeAddress); event SetStartTime(uint256 unixtime); event SetDuration(uint256 duration); modifier checkStart() { require(block.timestamp >= starttime,"Rewards haven't started yet!"); _; } modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalStaked() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalStaked()) ); } function earned(address account) public view returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } // stake visibility is public as overriding LPTokenWrapper's stake() function function stake(uint256 amount) public updateReward(msg.sender) checkStart { require(amount > 0, "Cannot stake 0"); super.stake(amount); } function withdraw(uint256 amount) public updateReward(msg.sender) checkStart { require(amount > 0, "Cannot withdraw 0"); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function exit() external { withdrawDividends(); getReward(); withdraw(balanceOf(msg.sender)); } function collectRewardsOnly() public { withdrawDividends(); getReward(); } function getReward() public updateReward(msg.sender) checkStart { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; rugReward.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function notifyRewardAmount(uint256 reward) external onlyRewardDistribution updateReward(address(0)) { if (block.timestamp > starttime) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } else { rewardRate = reward.div(DURATION); lastUpdateTime = starttime; periodFinish = starttime.add(DURATION); emit RewardAdded(reward); } } function setRewardAddress(address rewardAddress) public onlyOwner { rugReward = IERC20(rewardAddress); emit SetRewardToken(rewardAddress); } function setStakeAddress(address stakeAddress) public onlyOwner { rugStake = IERC20(stakeAddress); emit SetStakeToken(stakeAddress); } function setStartTime(uint256 unixtime) public onlyOwner { starttime = unixtime; emit SetStartTime(unixtime); } function setDuration(uint256 duration) public onlyOwner { DURATION = duration; emit SetDuration(duration); } }
adds dividends to staked balance
function _updateDividends() internal returns(uint256) { uint256 _dividends = dividendsOf(msg.sender); require(_dividends >= 0); _userDividends[msg.sender] = _userDividends[msg.sender].add(_dividends); _dividendsSnapshot[msg.sender] = _dividendsPerRug; }
7,620,903
/** *Submitted for verification at Etherscan.io on 2022-03-13 */ // SPDX-License-Identifier: GPL-3.0 // OpenZeppelin Contracts v4.4.0 (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); } } } } // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) /** * @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); } // https://docs.synthetix.io/contracts/source/contracts/owned contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require( msg.sender == nominatedOwner, "You must be nominated before you can accept ownership" ); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require( msg.sender == owner, "Only the contract owner may perform this action" ); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // Allows anyone to claim a token if they exist in a merkle root. interface IMerkleDistributor { // Returns the address of the token distributed by this contract. function token() external view returns (address); // Returns the merkle root of the merkle tree containing account balances available to claim. function merkleRoot() external view returns (bytes32); // Returns true if the index has been marked claimed. function isClaimed(uint256 index) external view returns (bool); // Claim the given amount of the token to the given address. Reverts if the inputs are invalid. function claim( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof ) external; // This event is triggered whenever a call to #claim succeeds. event Claimed(uint256 index, address account, uint256 amount); } // OpenZeppelin Contracts v4.4.0 (utils/cryptography/MerkleProof.sol) /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol) // 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; } } } // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) ////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"); } } } ////import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; ////import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; ////import "@openzeppelin/contracts/utils/math/SafeMath.sol"; ////import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; ////import "../interfaces/IMerkleDistributor.sol"; ////import "../common/Owned.sol"; contract MerkleDistributor is IMerkleDistributor, Owned { using SafeMath for uint256; using SafeERC20 for IERC20; address public immutable override token; bytes32 public immutable override merkleRoot; // This is a packed array of booleans. mapping(uint256 => uint256) private claimedBitMap; uint256 public immutable ownerUnlockTime; constructor( address _owner, address _token, bytes32 _merkleRoot, uint256 _daysUntilUnlock ) Owned(_owner) { require(_owner != address(0), "Owner must be non-zero address"); require(_token != address(0), "Airdrop token must be non-zero address"); require(_merkleRoot != bytes32(0), "Merkle root must be non-zero"); require( _daysUntilUnlock > 0, "Days until owner unlock must be in the future" ); token = _token; merkleRoot = _merkleRoot; ownerUnlockTime = block.timestamp.add(_daysUntilUnlock * 1 days); } function isClaimed(uint256 index) public view override returns (bool) { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; uint256 claimedWord = claimedBitMap[claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } function _setClaimed(uint256 index) private { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; claimedBitMap[claimedWordIndex] = claimedBitMap[claimedWordIndex] | (1 << claimedBitIndex); } function claim( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof ) external override { require(!isClaimed(index), "MerkleDistributor: Drop already claimed."); // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(index, account, amount)); require( MerkleProof.verify(merkleProof, merkleRoot, node), "MerkleDistributor: Invalid proof." ); // Mark it claimed and send the token. _setClaimed(index); IERC20(token).safeTransfer(account, amount); emit Claimed(index, account, amount); } // Used for recovery purposes function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner { require( tokenAddress == address(token) ? block.timestamp >= ownerUnlockTime : true, "MerkleDistributor: Cannot withdraw the token before unlock time" ); IERC20(tokenAddress).safeTransfer(owner, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } /* ========== EVENTS ========== */ event Recovered(address token, uint256 amount); }
Allows anyone to claim a token if they exist in a merkle root. Returns the address of the token distributed by this contract. Returns the merkle root of the merkle tree containing account balances available to claim. Returns true if the index has been marked claimed. Claim the given amount of the token to the given address. Reverts if the inputs are invalid. This event is triggered whenever a call to claim succeeds.
interface IMerkleDistributor { function token() external view returns (address); function merkleRoot() external view returns (bytes32); function isClaimed(uint256 index) external view returns (bool); function claim( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof ) external; event Claimed(uint256 index, address account, uint256 amount); }
2,039,476
./full_match/3/0x7A772f6b56154f53516B7D5Fbb10A385e0C09a0A/sources/browser/C2.sol
Forward ERC20 methods to upgraded contract if this one is deprecated
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) virtual override { if (deprecated) { return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); return super.approve(_spender, _value); } }
8,150,853
/* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Owned.sol version: 1.1 author: Anton Jurisevic Dominic Romanowski date: 2018-2-26 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- An Owned contract, to be inherited by other contracts. Requires its owner to be explicitly set in the constructor. Provides an onlyOwner access modifier. To change owner, the current owner must nominate the next owner, who then has to accept the nomination. The nomination can be cancelled before it is accepted by the new owner by having the previous owner change the nomination (setting it to 0). ----------------------------------------------------------------- */ pragma solidity 0.4.24; /** * @title A contract with an owner. * @notice Contract ownership can be transferred by first nominating the new owner, * who must then accept the ownership, which prevents accidental incorrect ownership transfers. */ contract Owned { address public owner; address public nominatedOwner; /** * @dev Owned Constructor */ constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } /** * @notice Nominate a new owner of this contract. * @dev Only the current owner may nominate a new owner. */ function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } /** * @notice Accept the nomination to be owner. */ function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: SelfDestructible.sol version: 1.2 author: Anton Jurisevic date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract allows an inheriting contract to be destroyed after its owner indicates an intention and then waits for a period without changing their mind. All ether contained in the contract is forwarded to a nominated beneficiary upon destruction. ----------------------------------------------------------------- */ /** * @title A contract that can be destroyed by its owner after a delay elapses. */ contract SelfDestructible is Owned { uint public initiationTime; bool public selfDestructInitiated; address public selfDestructBeneficiary; uint public constant SELFDESTRUCT_DELAY = 4 weeks; /** * @dev Constructor * @param _owner The account which controls this contract. */ constructor(address _owner) Owned(_owner) public { require(_owner != address(0), "Owner must not be the zero address"); selfDestructBeneficiary = _owner; emit SelfDestructBeneficiaryUpdated(_owner); } /** * @notice Set the beneficiary address of this contract. * @dev Only the contract owner may call this. The provided beneficiary must be non-null. * @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction. */ function setSelfDestructBeneficiary(address _beneficiary) external onlyOwner { require(_beneficiary != address(0), "Beneficiary must not be the zero address"); selfDestructBeneficiary = _beneficiary; emit SelfDestructBeneficiaryUpdated(_beneficiary); } /** * @notice Begin the self-destruction counter of this contract. * Once the delay has elapsed, the contract may be self-destructed. * @dev Only the contract owner may call this. */ function initiateSelfDestruct() external onlyOwner { initiationTime = now; selfDestructInitiated = true; emit SelfDestructInitiated(SELFDESTRUCT_DELAY); } /** * @notice Terminate and reset the self-destruction timer. * @dev Only the contract owner may call this. */ function terminateSelfDestruct() external onlyOwner { initiationTime = 0; selfDestructInitiated = false; emit SelfDestructTerminated(); } /** * @notice If the self-destruction delay has elapsed, destroy this contract and * remit any ether it owns to the beneficiary address. * @dev Only the contract owner may call this. */ function selfDestruct() external onlyOwner { require(selfDestructInitiated, "Self destruct has not yet been initiated"); require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed"); address beneficiary = selfDestructBeneficiary; emit SelfDestructed(beneficiary); selfdestruct(beneficiary); } event SelfDestructTerminated(); event SelfDestructed(address beneficiary); event SelfDestructInitiated(uint selfDestructDelay); event SelfDestructBeneficiaryUpdated(address newBeneficiary); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Pausable.sol version: 1.0 author: Kevin Brown date: 2018-05-22 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract allows an inheriting contract to be marked as paused. It also defines a modifier which can be used by the inheriting contract to prevent actions while paused. ----------------------------------------------------------------- */ /** * @title A contract that can be paused by its owner */ contract Pausable is Owned { uint public lastPauseTime; bool public paused; /** * @dev Constructor * @param _owner The account which controls this contract. */ constructor(address _owner) Owned(_owner) public { // Paused will be false, and lastPauseTime will be 0 upon initialisation } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we&#39;re actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // If applicable, set the last pause time. if (paused) { lastPauseTime = now; } // Let everyone know that our pause state has changed. emit PauseChanged(paused); } event PauseChanged(bool isPaused); modifier notPaused { require(!paused, "This action cannot be performed while the contract is paused"); _; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: SafeDecimalMath.sol version: 1.0 author: Anton Jurisevic date: 2018-2-5 checked: Mike Spain approved: Samuel Brooks ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A fixed point decimal library that provides basic mathematical operations, and checks for unsafe arguments, for example that would lead to overflows. Exceptions are thrown whenever those unsafe operations occur. ----------------------------------------------------------------- */ /** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals (including fiat, ether, and nomin quantities). */ contract SafeDecimalMath { /* Number of decimal places in the representation. */ uint8 public constant decimals = 18; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /** * @return True iff adding x and y will not overflow. */ function addIsSafe(uint x, uint y) pure internal returns (bool) { return x + y >= y; } /** * @return The result of adding x and y, throwing an exception in case of overflow. */ function safeAdd(uint x, uint y) pure internal returns (uint) { require(x + y >= y, "Safe add failed"); return x + y; } /** * @return True iff subtracting y from x will not overflow in the negative direction. */ function subIsSafe(uint x, uint y) pure internal returns (bool) { return y <= x; } /** * @return The result of subtracting y from x, throwing an exception in case of overflow. */ function safeSub(uint x, uint y) pure internal returns (uint) { require(y <= x, "Safe sub failed"); return x - y; } /** * @return True iff multiplying x and y would not overflow. */ function mulIsSafe(uint x, uint y) pure internal returns (bool) { if (x == 0) { return true; } return (x * y) / x == y; } /** * @return The result of multiplying x and y, throwing an exception in case of overflow. */ function safeMul(uint x, uint y) pure internal returns (uint) { if (x == 0) { return 0; } uint p = x * y; require(p / x == y, "Safe mul failed"); return p; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. Throws an exception in case of overflow. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. * Incidentally, the internal division always rounds down: one could have rounded to the nearest integer, * but then one would be spending a significant fraction of a cent (of order a microether * at present gas prices) in order to save less than one part in 0.5 * 10^18 per operation, if the operands * contain small enough fractional components. It would also marginally diminish the * domain this function is defined upon. */ function safeMul_dec(uint x, uint y) pure internal returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return safeMul(x, y) / UNIT; } /** * @return True iff the denominator of x/y is nonzero. */ function divIsSafe(uint x, uint y) pure internal returns (bool) { return y != 0; } /** * @return The result of dividing x by y, throwing an exception if the divisor is zero. */ function safeDiv(uint x, uint y) pure internal returns (uint) { /* Although a 0 denominator already throws an exception, * it is equivalent to a THROW operation, which consumes all gas. * A require statement emits REVERT instead, which remits remaining gas. */ require(y != 0, "Denominator cannot be zero"); return x / y; } /** * @return The result of dividing x by y, interpreting the operands as fixed point decimal numbers. * @dev Throws an exception in case of overflow or zero divisor; x must be less than 2^256 / UNIT. * Internal rounding is downward: a similar caveat holds as with safeDecMul(). */ function safeDiv_dec(uint x, uint y) pure internal returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return safeDiv(safeMul(x, UNIT), y); } /** * @dev Convert an unsigned integer to a unsigned fixed-point decimal. * Throw an exception if the result would be out of range. */ function intToDec(uint i) pure internal returns (uint) { return safeMul(i, UNIT); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: State.sol version: 1.1 author: Dominic Romanowski Anton Jurisevic date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract is used side by side with external state token contracts, such as Havven and Nomin. It provides an easy way to upgrade contract logic while maintaining all user balances and allowances. This is designed to make the changeover as easy as possible, since mappings are not so cheap or straightforward to migrate. The first deployed contract would create this state contract, using it as its store of balances. When a new contract is deployed, it links to the existing state contract, whose owner would then change its associated contract to the new one. ----------------------------------------------------------------- */ contract State is Owned { // the address of the contract that can modify variables // this can only be changed by the owner of this contract address public associatedContract; constructor(address _owner, address _associatedContract) Owned(_owner) public { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== SETTERS ========== */ // Change the associated contract to a new address function setAssociatedContract(address _associatedContract) external onlyOwner { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== MODIFIERS ========== */ modifier onlyAssociatedContract { require(msg.sender == associatedContract, "Only the associated contract can perform this action"); _; } /* ========== EVENTS ========== */ event AssociatedContractUpdated(address associatedContract); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: TokenState.sol version: 1.1 author: Dominic Romanowski Anton Jurisevic date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A contract that holds the state of an ERC20 compliant token. This contract is used side by side with external state token contracts, such as Havven and Nomin. It provides an easy way to upgrade contract logic while maintaining all user balances and allowances. This is designed to make the changeover as easy as possible, since mappings are not so cheap or straightforward to migrate. The first deployed contract would create this state contract, using it as its store of balances. When a new contract is deployed, it links to the existing state contract, whose owner would then change its associated contract to the new one. ----------------------------------------------------------------- */ /** * @title ERC20 Token State * @notice Stores balance information of an ERC20 token contract. */ contract TokenState is State { /* ERC20 fields. */ mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; /** * @dev Constructor * @param _owner The address which controls this contract. * @param _associatedContract The ERC20 contract whose state this composes. */ constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) public {} /* ========== SETTERS ========== */ /** * @notice Set ERC20 allowance. * @dev Only the associated contract may call this. * @param tokenOwner The authorising party. * @param spender The authorised party. * @param value The total value the authorised party may spend on the * authorising party&#39;s behalf. */ function setAllowance(address tokenOwner, address spender, uint value) external onlyAssociatedContract { allowance[tokenOwner][spender] = value; } /** * @notice Set the balance in a given account * @dev Only the associated contract may call this. * @param account The account whose value to set. * @param value The new balance of the given account. */ function setBalanceOf(address account, uint value) external onlyAssociatedContract { balanceOf[account] = value; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Proxy.sol version: 1.3 author: Anton Jurisevic date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A proxy contract that, if it does not recognise the function being called on it, passes all value and call data to an underlying target contract. This proxy has the capacity to toggle between DELEGATECALL and CALL style proxy functionality. The former executes in the proxy&#39;s context, and so will preserve msg.sender and store data at the proxy address. The latter will not. Therefore, any contract the proxy wraps in the CALL style must implement the Proxyable interface, in order that it can pass msg.sender into the underlying contract as the state parameter, messageSender. ----------------------------------------------------------------- */ contract Proxy is Owned { Proxyable public target; bool public useDELEGATECALL; constructor(address _owner) Owned(_owner) public {} function setTarget(Proxyable _target) external onlyOwner { target = _target; emit TargetUpdated(_target); } function setUseDELEGATECALL(bool value) external onlyOwner { useDELEGATECALL = value; } function _emit(bytes callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4) external onlyTarget { uint size = callData.length; bytes memory _callData = callData; assembly { /* The first 32 bytes of callData contain its length (as specified by the abi). * Length is assumed to be a uint256 and therefore maximum of 32 bytes * in length. It is also leftpadded to be a multiple of 32 bytes. * This means moving call_data across 32 bytes guarantees we correctly access * the data itself. */ switch numTopics case 0 { log0(add(_callData, 32), size) } case 1 { log1(add(_callData, 32), size, topic1) } case 2 { log2(add(_callData, 32), size, topic1, topic2) } case 3 { log3(add(_callData, 32), size, topic1, topic2, topic3) } case 4 { log4(add(_callData, 32), size, topic1, topic2, topic3, topic4) } } } function() external payable { if (useDELEGATECALL) { assembly { /* Copy call data into free memory region. */ let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* Forward all gas and call data to the target contract. */ let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) /* Revert if the call failed, otherwise return the result. */ if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } else { /* Here we are as above, but must send the messageSender explicitly * since we are using CALL rather than DELEGATECALL. */ target.setMessageSender(msg.sender); assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* We must explicitly forward ether to the underlying contract as well. */ let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } } modifier onlyTarget { require(Proxyable(msg.sender) == target, "This action can only be performed by the proxy target"); _; } event TargetUpdated(Proxyable newTarget); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Proxyable.sol version: 1.1 author: Anton Jurisevic date: 2018-05-15 checked: Mike Spain approved: Samuel Brooks ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A proxyable contract that works hand in hand with the Proxy contract to allow for anyone to interact with the underlying contract both directly and through the proxy. ----------------------------------------------------------------- */ // This contract should be treated like an abstract contract contract Proxyable is Owned { /* The proxy this contract exists behind. */ Proxy public proxy; /* The caller of the proxy, passed through to this contract. * Note that every function using this member must apply the onlyProxy or * optionalProxy modifiers, otherwise their invocations can use stale values. */ address messageSender; constructor(address _proxy, address _owner) Owned(_owner) public { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setProxy(address _proxy) external onlyOwner { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setMessageSender(address sender) external onlyProxy { messageSender = sender; } modifier onlyProxy { require(Proxy(msg.sender) == proxy, "Only the proxy can call this function"); _; } modifier optionalProxy { if (Proxy(msg.sender) != proxy) { messageSender = msg.sender; } _; } modifier optionalProxy_onlyOwner { if (Proxy(msg.sender) != proxy) { messageSender = msg.sender; } require(messageSender == owner, "This action can only be performed by the owner"); _; } event ProxyUpdated(address proxyAddress); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: ExternStateToken.sol version: 1.0 author: Kevin Brown date: 2018-08-06 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract offers a modifer that can prevent reentrancy on particular actions. It will not work if you put it on multiple functions that can be called from each other. Specifically guard external entry points to the contract with the modifier only. ----------------------------------------------------------------- */ contract ReentrancyPreventer { /* ========== MODIFIERS ========== */ bool isInFunctionBody = false; modifier preventReentrancy { require(!isInFunctionBody, "Reverted to prevent reentrancy"); isInFunctionBody = true; _; isInFunctionBody = false; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: ExternStateToken.sol version: 1.3 author: Anton Jurisevic Dominic Romanowski date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A partial ERC20 token contract, designed to operate with a proxy. To produce a complete ERC20 token, transfer and transferFrom tokens must be implemented, using the provided _byProxy internal functions. This contract utilises an external state for upgradeability. ----------------------------------------------------------------- */ /** * @title ERC20 Token contract, with detached state and designed to operate behind a proxy. */ contract ExternStateToken is SafeDecimalMath, SelfDestructible, Proxyable, ReentrancyPreventer { /* ========== STATE VARIABLES ========== */ /* Stores balances and allowances. */ TokenState public tokenState; /* Other ERC20 fields. * Note that the decimals field is defined in SafeDecimalMath.*/ string public name; string public symbol; uint public totalSupply; /** * @dev Constructor. * @param _proxy The proxy associated with this contract. * @param _name Token&#39;s ERC20 name. * @param _symbol Token&#39;s ERC20 symbol. * @param _totalSupply The total supply of the token. * @param _tokenState The TokenState contract address. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply, address _owner) SelfDestructible(_owner) Proxyable(_proxy, _owner) public { name = _name; symbol = _symbol; totalSupply = _totalSupply; tokenState = _tokenState; } /* ========== VIEWS ========== */ /** * @notice Returns the ERC20 allowance of one party to spend on behalf of another. * @param owner The party authorising spending of their funds. * @param spender The party spending tokenOwner&#39;s funds. */ function allowance(address owner, address spender) public view returns (uint) { return tokenState.allowance(owner, spender); } /** * @notice Returns the ERC20 token balance of a given account. */ function balanceOf(address account) public view returns (uint) { return tokenState.balanceOf(account); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Set the address of the TokenState contract. * @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000.. * as balances would be unreachable. */ function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner { tokenState = _tokenState; emitTokenStateUpdated(_tokenState); } function _internalTransfer(address from, address to, uint value) internal preventReentrancy returns (bool) { /* Disallow transfers to irretrievable-addresses. */ require(to != address(0), "Cannot transfer to the 0 address"); require(to != address(this), "Cannot transfer to the underlying contract"); require(to != address(proxy), "Cannot transfer to the proxy contract"); /* Insufficient balance will be handled by the safe subtraction. */ tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), value)); tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), value)); /* If we&#39;re transferring to a contract and it implements the havvenTokenFallback function, call it. This isn&#39;t ERC223 compliant because: 1. We don&#39;t revert if the contract doesn&#39;t implement havvenTokenFallback. This is because many DEXes and other contracts that expect to work with the standard approve / transferFrom workflow don&#39;t implement tokenFallback but can still process our tokens as usual, so it feels very harsh and likely to cause trouble if we add this restriction after having previously gone live with a vanilla ERC20. 2. We don&#39;t pass the bytes parameter. This is because of this solidity bug: https://github.com/ethereum/solidity/issues/2884 3. We also don&#39;t let the user use a custom tokenFallback. We figure as we&#39;re already not standards compliant, there won&#39;t be a use case where users can&#39;t just implement our specific function. As such we&#39;ve called the function havvenTokenFallback to be clear that we are not following the standard. */ // Is the to address a contract? We can check the code size on that address and know. uint length; // solium-disable-next-line security/no-inline-assembly assembly { // Retrieve the size of the code on the recipient address length := extcodesize(to) } // If there&#39;s code there, it&#39;s a contract if (length > 0) { // Now we need to optionally call havvenTokenFallback(address from, uint value). // We can&#39;t call it the normal way because that reverts when the recipient doesn&#39;t implement the function. // We&#39;ll use .call(), which means we need the function selector. We&#39;ve pre-computed // abi.encodeWithSignature("havvenTokenFallback(address,uint256)"), to save some gas. // solium-disable-next-line security/no-low-level-calls to.call(0xcbff5d96, messageSender, value); // And yes, we specifically don&#39;t care if this call fails, so we&#39;re not checking the return value. } // Emit a standard ERC20 transfer event emitTransfer(from, to, value); return true; } /** * @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing * the onlyProxy or optionalProxy modifiers. */ function _transfer_byProxy(address from, address to, uint value) internal returns (bool) { return _internalTransfer(from, to, value); } /** * @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions * possessing the optionalProxy or optionalProxy modifiers. */ function _transferFrom_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* Insufficient allowance will be handled by the safe subtraction. */ tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value)); return _internalTransfer(from, to, value); } /** * @notice Approves spender to transfer on the message sender&#39;s behalf. */ function approve(address spender, uint value) public optionalProxy returns (bool) { address sender = messageSender; tokenState.setAllowance(sender, spender, value); emitApproval(sender, spender, value); return true; } /* ========== EVENTS ========== */ event Transfer(address indexed from, address indexed to, uint value); bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)"); function emitTransfer(address from, address to, uint value) internal { proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0); } event Approval(address indexed owner, address indexed spender, uint value); bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)"); function emitApproval(address owner, address spender, uint value) internal { proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0); } event TokenStateUpdated(address newTokenState); bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)"); function emitTokenStateUpdated(address newTokenState) internal { proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: FeeToken.sol version: 1.3 author: Anton Jurisevic Dominic Romanowski Kevin Brown date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A token which also has a configurable fee rate charged on its transfers. This is designed to be overridden in order to produce an ERC20-compliant token. These fees accrue into a pool, from which a nominated authority may withdraw. This contract utilises an external state for upgradeability. ----------------------------------------------------------------- */ /** * @title ERC20 Token contract, with detached state. * Additionally charges fees on each transfer. */ contract FeeToken is ExternStateToken { /* ========== STATE VARIABLES ========== */ /* ERC20 members are declared in ExternStateToken. */ /* A percentage fee charged on each transfer. */ uint public transferFeeRate; /* Fee may not exceed 10%. */ uint constant MAX_TRANSFER_FEE_RATE = UNIT / 10; /* The address with the authority to distribute fees. */ address public feeAuthority; /* The address that fees will be pooled in. */ address public constant FEE_ADDRESS = 0xfeefeefeefeefeefeefeefeefeefeefeefeefeef; /* ========== CONSTRUCTOR ========== */ /** * @dev Constructor. * @param _proxy The proxy associated with this contract. * @param _name Token&#39;s ERC20 name. * @param _symbol Token&#39;s ERC20 symbol. * @param _totalSupply The total supply of the token. * @param _transferFeeRate The fee rate to charge on transfers. * @param _feeAuthority The address which has the authority to withdraw fees from the accumulated pool. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply, uint _transferFeeRate, address _feeAuthority, address _owner) ExternStateToken(_proxy, _tokenState, _name, _symbol, _totalSupply, _owner) public { feeAuthority = _feeAuthority; /* Constructed transfer fee rate should respect the maximum fee rate. */ require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Constructed transfer fee rate should respect the maximum fee rate"); transferFeeRate = _transferFeeRate; } /* ========== SETTERS ========== */ /** * @notice Set the transfer fee, anywhere within the range 0-10%. * @dev The fee rate is in decimal format, with UNIT being the value of 100%. */ function setTransferFeeRate(uint _transferFeeRate) external optionalProxy_onlyOwner { require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Transfer fee rate must be below MAX_TRANSFER_FEE_RATE"); transferFeeRate = _transferFeeRate; emitTransferFeeRateUpdated(_transferFeeRate); } /** * @notice Set the address of the user/contract responsible for collecting or * distributing fees. */ function setFeeAuthority(address _feeAuthority) public optionalProxy_onlyOwner { feeAuthority = _feeAuthority; emitFeeAuthorityUpdated(_feeAuthority); } /* ========== VIEWS ========== */ /** * @notice Calculate the Fee charged on top of a value being sent * @return Return the fee charged */ function transferFeeIncurred(uint value) public view returns (uint) { return safeMul_dec(value, transferFeeRate); /* Transfers less than the reciprocal of transferFeeRate should be completely eaten up by fees. * This is on the basis that transfers less than this value will result in a nil fee. * Probably too insignificant to worry about, but the following code will achieve it. * if (fee == 0 && transferFeeRate != 0) { * return _value; * } * return fee; */ } /** * @notice The value that you would need to send so that the recipient receives * a specified value. */ function transferPlusFee(uint value) external view returns (uint) { return safeAdd(value, transferFeeIncurred(value)); } /** * @notice The amount the recipient will receive if you send a certain number of tokens. */ function amountReceived(uint value) public view returns (uint) { return safeDiv_dec(value, safeAdd(UNIT, transferFeeRate)); } /** * @notice Collected fees sit here until they are distributed. * @dev The balance of the nomin contract itself is the fee pool. */ function feePool() external view returns (uint) { return tokenState.balanceOf(FEE_ADDRESS); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Base of transfer functions */ function _internalTransfer(address from, address to, uint amount, uint fee) internal returns (bool) { /* Disallow transfers to irretrievable-addresses. */ require(to != address(0), "Cannot transfer to the 0 address"); require(to != address(this), "Cannot transfer to the underlying contract"); require(to != address(proxy), "Cannot transfer to the proxy contract"); /* Insufficient balance will be handled by the safe subtraction. */ tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), safeAdd(amount, fee))); tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), amount)); tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), fee)); /* Emit events for both the transfer itself and the fee. */ emitTransfer(from, to, amount); emitTransfer(from, FEE_ADDRESS, fee); return true; } /** * @notice ERC20 friendly transfer function. */ function _transfer_byProxy(address sender, address to, uint value) internal returns (bool) { uint received = amountReceived(value); uint fee = safeSub(value, received); return _internalTransfer(sender, to, received, fee); } /** * @notice ERC20 friendly transferFrom function. */ function _transferFrom_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* The fee is deducted from the amount sent. */ uint received = amountReceived(value); uint fee = safeSub(value, received); /* Reduce the allowance by the amount we&#39;re transferring. * The safeSub call will handle an insufficient allowance. */ tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value)); return _internalTransfer(from, to, received, fee); } /** * @notice Ability to transfer where the sender pays the fees (not ERC20) */ function _transferSenderPaysFee_byProxy(address sender, address to, uint value) internal returns (bool) { /* The fee is added to the amount sent. */ uint fee = transferFeeIncurred(value); return _internalTransfer(sender, to, value, fee); } /** * @notice Ability to transferFrom where they sender pays the fees (not ERC20). */ function _transferFromSenderPaysFee_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* The fee is added to the amount sent. */ uint fee = transferFeeIncurred(value); uint total = safeAdd(value, fee); /* Reduce the allowance by the amount we&#39;re transferring. */ tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), total)); return _internalTransfer(from, to, value, fee); } /** * @notice Withdraw tokens from the fee pool into a given account. * @dev Only the fee authority may call this. */ function withdrawFees(address account, uint value) external onlyFeeAuthority returns (bool) { require(account != address(0), "Must supply an account address to withdraw fees"); /* 0-value withdrawals do nothing. */ if (value == 0) { return false; } /* Safe subtraction ensures an exception is thrown if the balance is insufficient. */ tokenState.setBalanceOf(FEE_ADDRESS, safeSub(tokenState.balanceOf(FEE_ADDRESS), value)); tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), value)); emitFeesWithdrawn(account, value); emitTransfer(FEE_ADDRESS, account, value); return true; } /** * @notice Donate tokens from the sender&#39;s balance into the fee pool. */ function donateToFeePool(uint n) external optionalProxy returns (bool) { address sender = messageSender; /* Empty donations are disallowed. */ uint balance = tokenState.balanceOf(sender); require(balance != 0, "Must have a balance in order to donate to the fee pool"); /* safeSub ensures the donor has sufficient balance. */ tokenState.setBalanceOf(sender, safeSub(balance, n)); tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), n)); emitFeesDonated(sender, n); emitTransfer(sender, FEE_ADDRESS, n); return true; } /* ========== MODIFIERS ========== */ modifier onlyFeeAuthority { require(msg.sender == feeAuthority, "Only the fee authority can do this action"); _; } /* ========== EVENTS ========== */ event TransferFeeRateUpdated(uint newFeeRate); bytes32 constant TRANSFERFEERATEUPDATED_SIG = keccak256("TransferFeeRateUpdated(uint256)"); function emitTransferFeeRateUpdated(uint newFeeRate) internal { proxy._emit(abi.encode(newFeeRate), 1, TRANSFERFEERATEUPDATED_SIG, 0, 0, 0); } event FeeAuthorityUpdated(address newFeeAuthority); bytes32 constant FEEAUTHORITYUPDATED_SIG = keccak256("FeeAuthorityUpdated(address)"); function emitFeeAuthorityUpdated(address newFeeAuthority) internal { proxy._emit(abi.encode(newFeeAuthority), 1, FEEAUTHORITYUPDATED_SIG, 0, 0, 0); } event FeesWithdrawn(address indexed account, uint value); bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)"); function emitFeesWithdrawn(address account, uint value) internal { proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0); } event FeesDonated(address indexed donor, uint value); bytes32 constant FEESDONATED_SIG = keccak256("FeesDonated(address,uint256)"); function emitFeesDonated(address donor, uint value) internal { proxy._emit(abi.encode(value), 2, FEESDONATED_SIG, bytes32(donor), 0, 0); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Nomin.sol version: 1.2 author: Anton Jurisevic Mike Spain Dominic Romanowski Kevin Brown date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Havven-backed nomin stablecoin contract. This contract issues nomins, which are tokens worth 1 USD each. Nomins are issuable by Havven holders who have to lock up some value of their havvens to issue H * Cmax nomins. Where Cmax is some value less than 1. A configurable fee is charged on nomin transfers and deposited into a common pot, which havven holders may withdraw from once per fee period. ----------------------------------------------------------------- */ contract Nomin is FeeToken { /* ========== STATE VARIABLES ========== */ Havven public havven; // Accounts which have lost the privilege to transact in nomins. mapping(address => bool) public frozen; // Nomin transfers incur a 15 bp fee by default. uint constant TRANSFER_FEE_RATE = 15 * UNIT / 10000; string constant TOKEN_NAME = "Nomin USD"; string constant TOKEN_SYMBOL = "nUSD"; /* ========== CONSTRUCTOR ========== */ constructor(address _proxy, TokenState _tokenState, Havven _havven, uint _totalSupply, address _owner) FeeToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, TRANSFER_FEE_RATE, _havven, // The havven contract is the fee authority. _owner) public { require(_proxy != 0, "_proxy cannot be 0"); require(address(_havven) != 0, "_havven cannot be 0"); require(_owner != 0, "_owner cannot be 0"); // It should not be possible to transfer to the fee pool directly (or confiscate its balance). frozen[FEE_ADDRESS] = true; havven = _havven; } /* ========== SETTERS ========== */ function setHavven(Havven _havven) external optionalProxy_onlyOwner { // havven should be set as the feeAuthority after calling this depending on // havven&#39;s internal logic havven = _havven; setFeeAuthority(_havven); emitHavvenUpdated(_havven); } /* ========== MUTATIVE FUNCTIONS ========== */ /* Override ERC20 transfer function in order to check * whether the recipient account is frozen. Note that there is * no need to check whether the sender has a frozen account, * since their funds have already been confiscated, * and no new funds can be transferred to it.*/ function transfer(address to, uint value) public optionalProxy returns (bool) { require(!frozen[to], "Cannot transfer to frozen address"); return _transfer_byProxy(messageSender, to, value); } /* Override ERC20 transferFrom function in order to check * whether the recipient account is frozen. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { require(!frozen[to], "Cannot transfer to frozen address"); return _transferFrom_byProxy(messageSender, from, to, value); } function transferSenderPaysFee(address to, uint value) public optionalProxy returns (bool) { require(!frozen[to], "Cannot transfer to frozen address"); return _transferSenderPaysFee_byProxy(messageSender, to, value); } function transferFromSenderPaysFee(address from, address to, uint value) public optionalProxy returns (bool) { require(!frozen[to], "Cannot transfer to frozen address"); return _transferFromSenderPaysFee_byProxy(messageSender, from, to, value); } /* The owner may allow a previously-frozen contract to once * again accept and transfer nomins. */ function unfreezeAccount(address target) external optionalProxy_onlyOwner { require(frozen[target] && target != FEE_ADDRESS, "Account must be frozen, and cannot be the fee address"); frozen[target] = false; emitAccountUnfrozen(target); } /* Allow havven to issue a certain number of * nomins from an account. */ function issue(address account, uint amount) external onlyHavven { tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), amount)); totalSupply = safeAdd(totalSupply, amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); } /* Allow havven to burn a certain number of * nomins from an account. */ function burn(address account, uint amount) external onlyHavven { tokenState.setBalanceOf(account, safeSub(tokenState.balanceOf(account), amount)); totalSupply = safeSub(totalSupply, amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); } /* ========== MODIFIERS ========== */ modifier onlyHavven() { require(Havven(msg.sender) == havven, "Only the Havven contract can perform this action"); _; } /* ========== EVENTS ========== */ event HavvenUpdated(address newHavven); bytes32 constant HAVVENUPDATED_SIG = keccak256("HavvenUpdated(address)"); function emitHavvenUpdated(address newHavven) internal { proxy._emit(abi.encode(newHavven), 1, HAVVENUPDATED_SIG, 0, 0, 0); } event AccountFrozen(address indexed target, uint balance); bytes32 constant ACCOUNTFROZEN_SIG = keccak256("AccountFrozen(address,uint256)"); function emitAccountFrozen(address target, uint balance) internal { proxy._emit(abi.encode(balance), 2, ACCOUNTFROZEN_SIG, bytes32(target), 0, 0); } event AccountUnfrozen(address indexed target); bytes32 constant ACCOUNTUNFROZEN_SIG = keccak256("AccountUnfrozen(address)"); function emitAccountUnfrozen(address target) internal { proxy._emit(abi.encode(), 2, ACCOUNTUNFROZEN_SIG, bytes32(target), 0, 0); } event Issued(address indexed account, uint amount); bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)"); function emitIssued(address account, uint amount) internal { proxy._emit(abi.encode(amount), 2, ISSUED_SIG, bytes32(account), 0, 0); } event Burned(address indexed account, uint amount); bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)"); function emitBurned(address account, uint amount) internal { proxy._emit(abi.encode(amount), 2, BURNED_SIG, bytes32(account), 0, 0); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: LimitedSetup.sol version: 1.1 author: Anton Jurisevic date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A contract with a limited setup period. Any function modified with the setup modifier will cease to work after the conclusion of the configurable-length post-construction setup period. ----------------------------------------------------------------- */ /** * @title Any function decorated with the modifier this contract provides * deactivates after a specified setup period. */ contract LimitedSetup { uint setupExpiryTime; /** * @dev LimitedSetup Constructor. * @param setupDuration The time the setup period will last for. */ constructor(uint setupDuration) public { setupExpiryTime = now + setupDuration; } modifier onlyDuringSetup { require(now < setupExpiryTime, "Can only perform this action during setup"); _; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: HavvenEscrow.sol version: 1.1 author: Anton Jurisevic Dominic Romanowski Mike Spain date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract allows the foundation to apply unique vesting schedules to havven funds sold at various discounts in the token sale. HavvenEscrow gives users the ability to inspect their vested funds, their quantities and vesting dates, and to withdraw the fees that accrue on those funds. The fees are handled by withdrawing the entire fee allocation for all havvens inside the escrow contract, and then allowing the contract itself to subdivide that pool up proportionally within itself. Every time the fee period rolls over in the main Havven contract, the HavvenEscrow fee pool is remitted back into the main fee pool to be redistributed in the next fee period. ----------------------------------------------------------------- */ /** * @title A contract to hold escrowed havvens and free them at given schedules. */ contract HavvenEscrow is SafeDecimalMath, Owned, LimitedSetup(8 weeks) { /* The corresponding Havven contract. */ Havven public havven; /* Lists of (timestamp, quantity) pairs per account, sorted in ascending time order. * These are the times at which each given quantity of havvens vests. */ mapping(address => uint[2][]) public vestingSchedules; /* An account&#39;s total vested havven balance to save recomputing this for fee extraction purposes. */ mapping(address => uint) public totalVestedAccountBalance; /* The total remaining vested balance, for verifying the actual havven balance of this contract against. */ uint public totalVestedBalance; uint constant TIME_INDEX = 0; uint constant QUANTITY_INDEX = 1; /* Limit vesting entries to disallow unbounded iteration over vesting schedules. */ uint constant MAX_VESTING_ENTRIES = 20; /* ========== CONSTRUCTOR ========== */ constructor(address _owner, Havven _havven) Owned(_owner) public { havven = _havven; } /* ========== SETTERS ========== */ function setHavven(Havven _havven) external onlyOwner { havven = _havven; emit HavvenUpdated(_havven); } /* ========== VIEW FUNCTIONS ========== */ /** * @notice A simple alias to totalVestedAccountBalance: provides ERC20 balance integration. */ function balanceOf(address account) public view returns (uint) { return totalVestedAccountBalance[account]; } /** * @notice The number of vesting dates in an account&#39;s schedule. */ function numVestingEntries(address account) public view returns (uint) { return vestingSchedules[account].length; } /** * @notice Get a particular schedule entry for an account. * @return A pair of uints: (timestamp, havven quantity). */ function getVestingScheduleEntry(address account, uint index) public view returns (uint[2]) { return vestingSchedules[account][index]; } /** * @notice Get the time at which a given schedule entry will vest. */ function getVestingTime(address account, uint index) public view returns (uint) { return getVestingScheduleEntry(account,index)[TIME_INDEX]; } /** * @notice Get the quantity of havvens associated with a given schedule entry. */ function getVestingQuantity(address account, uint index) public view returns (uint) { return getVestingScheduleEntry(account,index)[QUANTITY_INDEX]; } /** * @notice Obtain the index of the next schedule entry that will vest for a given user. */ function getNextVestingIndex(address account) public view returns (uint) { uint len = numVestingEntries(account); for (uint i = 0; i < len; i++) { if (getVestingTime(account, i) != 0) { return i; } } return len; } /** * @notice Obtain the next schedule entry that will vest for a given user. * @return A pair of uints: (timestamp, havven quantity). */ function getNextVestingEntry(address account) public view returns (uint[2]) { uint index = getNextVestingIndex(account); if (index == numVestingEntries(account)) { return [uint(0), 0]; } return getVestingScheduleEntry(account, index); } /** * @notice Obtain the time at which the next schedule entry will vest for a given user. */ function getNextVestingTime(address account) external view returns (uint) { return getNextVestingEntry(account)[TIME_INDEX]; } /** * @notice Obtain the quantity which the next schedule entry will vest for a given user. */ function getNextVestingQuantity(address account) external view returns (uint) { return getNextVestingEntry(account)[QUANTITY_INDEX]; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Withdraws a quantity of havvens back to the havven contract. * @dev This may only be called by the owner during the contract&#39;s setup period. */ function withdrawHavvens(uint quantity) external onlyOwner onlyDuringSetup { havven.transfer(havven, quantity); } /** * @notice Destroy the vesting information associated with an account. */ function purgeAccount(address account) external onlyOwner onlyDuringSetup { delete vestingSchedules[account]; totalVestedBalance = safeSub(totalVestedBalance, totalVestedAccountBalance[account]); delete totalVestedAccountBalance[account]; } /** * @notice Add a new vesting entry at a given time and quantity to an account&#39;s schedule. * @dev A call to this should be accompanied by either enough balance already available * in this contract, or a corresponding call to havven.endow(), to ensure that when * the funds are withdrawn, there is enough balance, as well as correctly calculating * the fees. * This may only be called by the owner during the contract&#39;s setup period. * Note; although this function could technically be used to produce unbounded * arrays, it&#39;s only in the foundation&#39;s command to add to these lists. * @param account The account to append a new vesting entry to. * @param time The absolute unix timestamp after which the vested quantity may be withdrawn. * @param quantity The quantity of havvens that will vest. */ function appendVestingEntry(address account, uint time, uint quantity) public onlyOwner onlyDuringSetup { /* No empty or already-passed vesting entries allowed. */ require(now < time, "Time must be in the future"); require(quantity != 0, "Quantity cannot be zero"); /* There must be enough balance in the contract to provide for the vesting entry. */ totalVestedBalance = safeAdd(totalVestedBalance, quantity); require(totalVestedBalance <= havven.balanceOf(this), "Must be enough balance in the contract to provide for the vesting entry"); /* Disallow arbitrarily long vesting schedules in light of the gas limit. */ uint scheduleLength = vestingSchedules[account].length; require(scheduleLength <= MAX_VESTING_ENTRIES, "Vesting schedule is too long"); if (scheduleLength == 0) { totalVestedAccountBalance[account] = quantity; } else { /* Disallow adding new vested havvens earlier than the last one. * Since entries are only appended, this means that no vesting date can be repeated. */ require(getVestingTime(account, numVestingEntries(account) - 1) < time, "Cannot add new vested entries earlier than the last one"); totalVestedAccountBalance[account] = safeAdd(totalVestedAccountBalance[account], quantity); } vestingSchedules[account].push([time, quantity]); } /** * @notice Construct a vesting schedule to release a quantities of havvens * over a series of intervals. * @dev Assumes that the quantities are nonzero * and that the sequence of timestamps is strictly increasing. * This may only be called by the owner during the contract&#39;s setup period. */ function addVestingSchedule(address account, uint[] times, uint[] quantities) external onlyOwner onlyDuringSetup { for (uint i = 0; i < times.length; i++) { appendVestingEntry(account, times[i], quantities[i]); } } /** * @notice Allow a user to withdraw any havvens in their schedule that have vested. */ function vest() external { uint numEntries = numVestingEntries(msg.sender); uint total; for (uint i = 0; i < numEntries; i++) { uint time = getVestingTime(msg.sender, i); /* The list is sorted; when we reach the first future time, bail out. */ if (time > now) { break; } uint qty = getVestingQuantity(msg.sender, i); if (qty == 0) { continue; } vestingSchedules[msg.sender][i] = [0, 0]; total = safeAdd(total, qty); } if (total != 0) { totalVestedBalance = safeSub(totalVestedBalance, total); totalVestedAccountBalance[msg.sender] = safeSub(totalVestedAccountBalance[msg.sender], total); havven.transfer(msg.sender, total); emit Vested(msg.sender, now, total); } } /* ========== EVENTS ========== */ event HavvenUpdated(address newHavven); event Vested(address indexed beneficiary, uint time, uint value); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Havven.sol version: 1.2 author: Anton Jurisevic Dominic Romanowski date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Havven token contract. Havvens are transferable ERC20 tokens, and also give their holders the following privileges. An owner of havvens may participate in nomin confiscation votes, they may also have the right to issue nomins at the discretion of the foundation for this version of the contract. After a fee period terminates, the duration and fees collected for that period are computed, and the next period begins. Thus an account may only withdraw the fees owed to them for the previous period, and may only do so once per period. Any unclaimed fees roll over into the common pot for the next period. == Average Balance Calculations == The fee entitlement of a havven holder is proportional to their average issued nomin balance over the last fee period. This is computed by measuring the area under the graph of a user&#39;s issued nomin balance over time, and then when a new fee period begins, dividing through by the duration of the fee period. We need only update values when the balances of an account is modified. This occurs when issuing or burning for issued nomin balances, and when transferring for havven balances. This is for efficiency, and adds an implicit friction to interacting with havvens. A havven holder pays for his own recomputation whenever he wants to change his position, which saves the foundation having to maintain a pot dedicated to resourcing this. A hypothetical user&#39;s balance history over one fee period, pictorially: s ____ | | | |___ p |____|___|___ __ _ _ f t n Here, the balance was s between times f and t, at which time a transfer occurred, updating the balance to p, until n, when the present transfer occurs. When a new transfer occurs at time n, the balance being p, we must: - Add the area p * (n - t) to the total area recorded so far - Update the last transfer time to n So if this graph represents the entire current fee period, the average havvens held so far is ((t-f)*s + (n-t)*p) / (n-f). The complementary computations must be performed for both sender and recipient. Note that a transfer keeps global supply of havvens invariant. The sum of all balances is constant, and unmodified by any transfer. So the sum of all balances multiplied by the duration of a fee period is also constant, and this is equivalent to the sum of the area of every user&#39;s time/balance graph. Dividing through by that duration yields back the total havven supply. So, at the end of a fee period, we really do yield a user&#39;s average share in the havven supply over that period. A slight wrinkle is introduced if we consider the time r when the fee period rolls over. Then the previous fee period k-1 is before r, and the current fee period k is afterwards. If the last transfer took place before r, but the latest transfer occurred afterwards: k-1 | k s __|_ | | | | | |____ p |__|_|____|___ __ _ _ | f | t n r In this situation the area (r-f)*s contributes to fee period k-1, while the area (t-r)*s contributes to fee period k. We will implicitly consider a zero-value transfer to have occurred at time r. Their fee entitlement for the previous period will be finalised at the time of their first transfer during the current fee period, or when they query or withdraw their fee entitlement. In the implementation, the duration of different fee periods may be slightly irregular, as the check that they have rolled over occurs only when state-changing havven operations are performed. == Issuance and Burning == In this version of the havven contract, nomins can only be issued by those that have been nominated by the havven foundation. Nomins are assumed to be valued at $1, as they are a stable unit of account. All nomins issued require a proportional value of havvens to be locked, where the proportion is governed by the current issuance ratio. This means for every $1 of Havvens locked up, $(issuanceRatio) nomins can be issued. i.e. to issue 100 nomins, 100/issuanceRatio dollars of havvens need to be locked up. To determine the value of some amount of havvens(H), an oracle is used to push the price of havvens (P_H) in dollars to the contract. The value of H would then be: H * P_H. Any havvens that are locked up by this issuance process cannot be transferred. The amount that is locked floats based on the price of havvens. If the price of havvens moves up, less havvens are locked, so they can be issued against, or transferred freely. If the price of havvens moves down, more havvens are locked, even going above the initial wallet balance. ----------------------------------------------------------------- */ /** * @title Havven ERC20 contract. * @notice The Havven contracts does not only facilitate transfers and track balances, * but it also computes the quantity of fees each havven holder is entitled to. */ contract Havven is ExternStateToken { /* ========== STATE VARIABLES ========== */ /* A struct for handing values associated with average balance calculations */ struct IssuanceData { /* Sums of balances*duration in the current fee period. /* range: decimals; units: havven-seconds */ uint currentBalanceSum; /* The last period&#39;s average balance */ uint lastAverageBalance; /* The last time the data was calculated */ uint lastModified; } /* Issued nomin balances for individual fee entitlements */ mapping(address => IssuanceData) public issuanceData; /* The total number of issued nomins for determining fee entitlements */ IssuanceData public totalIssuanceData; /* The time the current fee period began */ uint public feePeriodStartTime; /* The time the last fee period began */ uint public lastFeePeriodStartTime; /* Fee periods will roll over in no shorter a time than this. * The fee period cannot actually roll over until a fee-relevant * operation such as withdrawal or a fee period duration update occurs, * so this is just a target, and the actual duration may be slightly longer. */ uint public feePeriodDuration = 4 weeks; /* ...and must target between 1 day and six months. */ uint constant MIN_FEE_PERIOD_DURATION = 1 days; uint constant MAX_FEE_PERIOD_DURATION = 26 weeks; /* The quantity of nomins that were in the fee pot at the time */ /* of the last fee rollover, at feePeriodStartTime. */ uint public lastFeesCollected; /* Whether a user has withdrawn their last fees */ mapping(address => bool) public hasWithdrawnFees; Nomin public nomin; HavvenEscrow public escrow; /* The address of the oracle which pushes the havven price to this contract */ address public oracle; /* The price of havvens written in UNIT */ uint public price; /* The time the havven price was last updated */ uint public lastPriceUpdateTime; /* How long will the contract assume the price of havvens is correct */ uint public priceStalePeriod = 3 hours; /* A quantity of nomins greater than this ratio * may not be issued against a given value of havvens. */ uint public issuanceRatio = UNIT / 5; /* No more nomins may be issued than the value of havvens backing them. */ uint constant MAX_ISSUANCE_RATIO = UNIT; /* Whether the address can issue nomins or not. */ mapping(address => bool) public isIssuer; /* The number of currently-outstanding nomins the user has issued. */ mapping(address => uint) public nominsIssued; uint constant HAVVEN_SUPPLY = 1e8 * UNIT; uint constant ORACLE_FUTURE_LIMIT = 10 minutes; string constant TOKEN_NAME = "Havven"; string constant TOKEN_SYMBOL = "HAV"; /* ========== CONSTRUCTOR ========== */ /** * @dev Constructor * @param _tokenState A pre-populated contract containing token balances. * If the provided address is 0x0, then a fresh one will be constructed with the contract owning all tokens. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, address _owner, address _oracle, uint _price, address[] _issuers, Havven _oldHavven) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, HAVVEN_SUPPLY, _owner) public { oracle = _oracle; price = _price; lastPriceUpdateTime = now; uint i; if (_oldHavven == address(0)) { feePeriodStartTime = now; lastFeePeriodStartTime = now - feePeriodDuration; for (i = 0; i < _issuers.length; i++) { isIssuer[_issuers[i]] = true; } } else { feePeriodStartTime = _oldHavven.feePeriodStartTime(); lastFeePeriodStartTime = _oldHavven.lastFeePeriodStartTime(); uint cbs; uint lab; uint lm; (cbs, lab, lm) = _oldHavven.totalIssuanceData(); totalIssuanceData.currentBalanceSum = cbs; totalIssuanceData.lastAverageBalance = lab; totalIssuanceData.lastModified = lm; for (i = 0; i < _issuers.length; i++) { address issuer = _issuers[i]; isIssuer[issuer] = true; uint nomins = _oldHavven.nominsIssued(issuer); if (nomins == 0) { // It is not valid in general to skip those with no currently-issued nomins. // But for this release, issuers with nonzero issuanceData have current issuance. continue; } (cbs, lab, lm) = _oldHavven.issuanceData(issuer); nominsIssued[issuer] = nomins; issuanceData[issuer].currentBalanceSum = cbs; issuanceData[issuer].lastAverageBalance = lab; issuanceData[issuer].lastModified = lm; } } } /* ========== SETTERS ========== */ /** * @notice Set the associated Nomin contract to collect fees from. * @dev Only the contract owner may call this. */ function setNomin(Nomin _nomin) external optionalProxy_onlyOwner { nomin = _nomin; emitNominUpdated(_nomin); } /** * @notice Set the associated havven escrow contract. * @dev Only the contract owner may call this. */ function setEscrow(HavvenEscrow _escrow) external optionalProxy_onlyOwner { escrow = _escrow; emitEscrowUpdated(_escrow); } /** * @notice Set the targeted fee period duration. * @dev Only callable by the contract owner. The duration must fall within * acceptable bounds (1 day to 26 weeks). Upon resetting this the fee period * may roll over if the target duration was shortened sufficiently. */ function setFeePeriodDuration(uint duration) external optionalProxy_onlyOwner { require(MIN_FEE_PERIOD_DURATION <= duration && duration <= MAX_FEE_PERIOD_DURATION, "Duration must be between MIN_FEE_PERIOD_DURATION and MAX_FEE_PERIOD_DURATION"); feePeriodDuration = duration; emitFeePeriodDurationUpdated(duration); rolloverFeePeriodIfElapsed(); } /** * @notice Set the Oracle that pushes the havven price to this contract */ function setOracle(address _oracle) external optionalProxy_onlyOwner { oracle = _oracle; emitOracleUpdated(_oracle); } /** * @notice Set the stale period on the updated havven price * @dev No max/minimum, as changing it wont influence anything but issuance by the foundation */ function setPriceStalePeriod(uint time) external optionalProxy_onlyOwner { priceStalePeriod = time; } /** * @notice Set the issuanceRatio for issuance calculations. * @dev Only callable by the contract owner. */ function setIssuanceRatio(uint _issuanceRatio) external optionalProxy_onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio must be less than or equal to MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emitIssuanceRatioUpdated(_issuanceRatio); } /** * @notice Set whether the specified can issue nomins or not. */ function setIssuer(address account, bool value) external optionalProxy_onlyOwner { isIssuer[account] = value; emitIssuersUpdated(account, value); } /* ========== VIEWS ========== */ function issuanceCurrentBalanceSum(address account) external view returns (uint) { return issuanceData[account].currentBalanceSum; } function issuanceLastAverageBalance(address account) external view returns (uint) { return issuanceData[account].lastAverageBalance; } function issuanceLastModified(address account) external view returns (uint) { return issuanceData[account].lastModified; } function totalIssuanceCurrentBalanceSum() external view returns (uint) { return totalIssuanceData.currentBalanceSum; } function totalIssuanceLastAverageBalance() external view returns (uint) { return totalIssuanceData.lastAverageBalance; } function totalIssuanceLastModified() external view returns (uint) { return totalIssuanceData.lastModified; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { address sender = messageSender; require(nominsIssued[sender] == 0 || value <= transferableHavvens(sender), "Value to transfer exceeds available havvens"); /* Perform the transfer: if there is a problem, * an exception will be thrown in this call. */ _transfer_byProxy(sender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { address sender = messageSender; require(nominsIssued[from] == 0 || value <= transferableHavvens(from), "Value to transfer exceeds available havvens"); /* Perform the transfer: if there is a problem, * an exception will be thrown in this call. */ _transferFrom_byProxy(sender, from, to, value); return true; } /** * @notice Compute the last period&#39;s fee entitlement for the message sender * and then deposit it into their nomin account. */ function withdrawFees() external optionalProxy { address sender = messageSender; rolloverFeePeriodIfElapsed(); /* Do not deposit fees into frozen accounts. */ require(!nomin.frozen(sender), "Cannot deposit fees into frozen accounts"); /* Check the period has rolled over first. */ updateIssuanceData(sender, nominsIssued[sender], nomin.totalSupply()); /* Only allow accounts to withdraw fees once per period. */ require(!hasWithdrawnFees[sender], "Fees have already been withdrawn in this period"); uint feesOwed; uint lastTotalIssued = totalIssuanceData.lastAverageBalance; if (lastTotalIssued > 0) { /* Sender receives a share of last period&#39;s collected fees proportional * with their average fraction of the last period&#39;s issued nomins. */ feesOwed = safeDiv_dec( safeMul_dec(issuanceData[sender].lastAverageBalance, lastFeesCollected), lastTotalIssued ); } hasWithdrawnFees[sender] = true; if (feesOwed != 0) { nomin.withdrawFees(sender, feesOwed); } emitFeesWithdrawn(messageSender, feesOwed); } /** * @notice Update the havven balance averages since the last transfer * or entitlement adjustment. * @dev Since this updates the last transfer timestamp, if invoked * consecutively, this function will do nothing after the first call. * Also, this will adjust the total issuance at the same time. */ function updateIssuanceData(address account, uint preBalance, uint lastTotalSupply) internal { /* update the total balances first */ totalIssuanceData = computeIssuanceData(lastTotalSupply, totalIssuanceData); if (issuanceData[account].lastModified < feePeriodStartTime) { hasWithdrawnFees[account] = false; } issuanceData[account] = computeIssuanceData(preBalance, issuanceData[account]); } /** * @notice Compute the new IssuanceData on the old balance */ function computeIssuanceData(uint preBalance, IssuanceData preIssuance) internal view returns (IssuanceData) { uint currentBalanceSum = preIssuance.currentBalanceSum; uint lastAverageBalance = preIssuance.lastAverageBalance; uint lastModified = preIssuance.lastModified; if (lastModified < feePeriodStartTime) { if (lastModified < lastFeePeriodStartTime) { /* The balance was last updated before the previous fee period, so the average * balance in this period is their pre-transfer balance. */ lastAverageBalance = preBalance; } else { /* The balance was last updated during the previous fee period. */ /* No overflow or zero denominator problems, since lastFeePeriodStartTime < feePeriodStartTime < lastModified. * implies these quantities are strictly positive. */ uint timeUpToRollover = feePeriodStartTime - lastModified; uint lastFeePeriodDuration = feePeriodStartTime - lastFeePeriodStartTime; uint lastBalanceSum = safeAdd(currentBalanceSum, safeMul(preBalance, timeUpToRollover)); lastAverageBalance = lastBalanceSum / lastFeePeriodDuration; } /* Roll over to the next fee period. */ currentBalanceSum = safeMul(preBalance, now - feePeriodStartTime); } else { /* The balance was last updated during the current fee period. */ currentBalanceSum = safeAdd( currentBalanceSum, safeMul(preBalance, now - lastModified) ); } return IssuanceData(currentBalanceSum, lastAverageBalance, now); } /** * @notice Recompute and return the given account&#39;s last average balance. */ function recomputeLastAverageBalance(address account) external returns (uint) { updateIssuanceData(account, nominsIssued[account], nomin.totalSupply()); return issuanceData[account].lastAverageBalance; } /** * @notice Issue nomins against the sender&#39;s havvens. * @dev Issuance is only allowed if the havven price isn&#39;t stale and the sender is an issuer. */ function issueNomins(uint amount) public optionalProxy requireIssuer(messageSender) /* No need to check if price is stale, as it is checked in issuableNomins. */ { address sender = messageSender; require(amount <= remainingIssuableNomins(sender), "Amount must be less than or equal to remaining issuable nomins"); uint lastTot = nomin.totalSupply(); uint preIssued = nominsIssued[sender]; nomin.issue(sender, amount); nominsIssued[sender] = safeAdd(preIssued, amount); updateIssuanceData(sender, preIssued, lastTot); } function issueMaxNomins() external optionalProxy { issueNomins(remainingIssuableNomins(messageSender)); } /** * @notice Burn nomins to clear issued nomins/free havvens. */ function burnNomins(uint amount) /* it doesn&#39;t matter if the price is stale or if the user is an issuer, as non-issuers have issued no nomins.*/ external optionalProxy { address sender = messageSender; uint lastTot = nomin.totalSupply(); uint preIssued = nominsIssued[sender]; /* nomin.burn does a safeSub on balance (so it will revert if there are not enough nomins). */ nomin.burn(sender, amount); /* This safe sub ensures amount <= number issued */ nominsIssued[sender] = safeSub(preIssued, amount); updateIssuanceData(sender, preIssued, lastTot); } /** * @notice Check if the fee period has rolled over. If it has, set the new fee period start * time, and record the fees collected in the nomin contract. */ function rolloverFeePeriodIfElapsed() public { /* If the fee period has rolled over... */ if (now >= feePeriodStartTime + feePeriodDuration) { lastFeesCollected = nomin.feePool(); lastFeePeriodStartTime = feePeriodStartTime; feePeriodStartTime = now; emitFeePeriodRollover(now); } } /* ========== Issuance/Burning ========== */ /** * @notice The maximum nomins an issuer can issue against their total havven quantity. This ignores any * already issued nomins. */ function maxIssuableNomins(address issuer) view public priceNotStale returns (uint) { if (!isIssuer[issuer]) { return 0; } if (escrow != HavvenEscrow(0)) { uint totalOwnedHavvens = safeAdd(tokenState.balanceOf(issuer), escrow.balanceOf(issuer)); return safeMul_dec(HAVtoUSD(totalOwnedHavvens), issuanceRatio); } else { return safeMul_dec(HAVtoUSD(tokenState.balanceOf(issuer)), issuanceRatio); } } /** * @notice The remaining nomins an issuer can issue against their total havven quantity. */ function remainingIssuableNomins(address issuer) view public returns (uint) { uint issued = nominsIssued[issuer]; uint max = maxIssuableNomins(issuer); if (issued > max) { return 0; } else { return safeSub(max, issued); } } /** * @notice The total havvens owned by this account, both escrowed and unescrowed, * against which nomins can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint bal = tokenState.balanceOf(account); if (escrow != address(0)) { bal = safeAdd(bal, escrow.balanceOf(account)); } return bal; } /** * @notice The collateral that would be locked by issuance, which can exceed the account&#39;s actual collateral. */ function issuanceDraft(address account) public view returns (uint) { uint issued = nominsIssued[account]; if (issued == 0) { return 0; } return USDtoHAV(safeDiv_dec(issued, issuanceRatio)); } /** * @notice Collateral that has been locked due to issuance, and cannot be * transferred to other addresses. This is capped at the account&#39;s total collateral. */ function lockedCollateral(address account) public view returns (uint) { uint debt = issuanceDraft(account); uint collat = collateral(account); if (debt > collat) { return collat; } return debt; } /** * @notice Collateral that is not locked and available for issuance. */ function unlockedCollateral(address account) public view returns (uint) { uint locked = lockedCollateral(account); uint collat = collateral(account); return safeSub(collat, locked); } /** * @notice The number of havvens that are free to be transferred by an account. * @dev If they have enough available Havvens, it could be that * their havvens are escrowed, however the transfer would then * fail. This means that escrowed havvens are locked first, * and then the actual transferable ones. */ function transferableHavvens(address account) public view returns (uint) { uint draft = issuanceDraft(account); uint collat = collateral(account); // In the case where the issuanceDraft exceeds the collateral, nothing is free if (draft > collat) { return 0; } uint bal = balanceOf(account); // In the case where the draft exceeds the escrow, but not the whole collateral // return the fraction of the balance that remains free if (draft > safeSub(collat, bal)) { return safeSub(collat, draft); } // In the case where the draft doesn&#39;t exceed the escrow, return the entire balance return bal; } /** * @notice The value in USD for a given amount of HAV */ function HAVtoUSD(uint hav_dec) public view priceNotStale returns (uint) { return safeMul_dec(hav_dec, price); } /** * @notice The value in HAV for a given amount of USD */ function USDtoHAV(uint usd_dec) public view priceNotStale returns (uint) { return safeDiv_dec(usd_dec, price); } /** * @notice Access point for the oracle to update the price of havvens. */ function updatePrice(uint newPrice, uint timeSent) external onlyOracle /* Should be callable only by the oracle. */ { /* Must be the most recently sent price, but not too far in the future. * (so we can&#39;t lock ourselves out of updating the oracle for longer than this) */ require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT, "Time sent must be bigger than the last update, and must be less than now + ORACLE_FUTURE_LIMIT"); price = newPrice; lastPriceUpdateTime = timeSent; emitPriceUpdated(newPrice, timeSent); /* Check the fee period rollover within this as the price should be pushed every 15min. */ rolloverFeePeriodIfElapsed(); } /** * @notice Check if the price of havvens hasn&#39;t been updated for longer than the stale period. */ function priceIsStale() public view returns (bool) { return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now; } /* ========== MODIFIERS ========== */ modifier requireIssuer(address account) { require(isIssuer[account], "Must be issuer to perform this action"); _; } modifier onlyOracle { require(msg.sender == oracle, "Must be oracle to perform this action"); _; } modifier priceNotStale { require(!priceIsStale(), "Price must not be stale to perform this action"); _; } /* ========== EVENTS ========== */ event PriceUpdated(uint newPrice, uint timestamp); bytes32 constant PRICEUPDATED_SIG = keccak256("PriceUpdated(uint256,uint256)"); function emitPriceUpdated(uint newPrice, uint timestamp) internal { proxy._emit(abi.encode(newPrice, timestamp), 1, PRICEUPDATED_SIG, 0, 0, 0); } event IssuanceRatioUpdated(uint newRatio); bytes32 constant ISSUANCERATIOUPDATED_SIG = keccak256("IssuanceRatioUpdated(uint256)"); function emitIssuanceRatioUpdated(uint newRatio) internal { proxy._emit(abi.encode(newRatio), 1, ISSUANCERATIOUPDATED_SIG, 0, 0, 0); } event FeePeriodRollover(uint timestamp); bytes32 constant FEEPERIODROLLOVER_SIG = keccak256("FeePeriodRollover(uint256)"); function emitFeePeriodRollover(uint timestamp) internal { proxy._emit(abi.encode(timestamp), 1, FEEPERIODROLLOVER_SIG, 0, 0, 0); } event FeePeriodDurationUpdated(uint duration); bytes32 constant FEEPERIODDURATIONUPDATED_SIG = keccak256("FeePeriodDurationUpdated(uint256)"); function emitFeePeriodDurationUpdated(uint duration) internal { proxy._emit(abi.encode(duration), 1, FEEPERIODDURATIONUPDATED_SIG, 0, 0, 0); } event FeesWithdrawn(address indexed account, uint value); bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)"); function emitFeesWithdrawn(address account, uint value) internal { proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0); } event OracleUpdated(address newOracle); bytes32 constant ORACLEUPDATED_SIG = keccak256("OracleUpdated(address)"); function emitOracleUpdated(address newOracle) internal { proxy._emit(abi.encode(newOracle), 1, ORACLEUPDATED_SIG, 0, 0, 0); } event NominUpdated(address newNomin); bytes32 constant NOMINUPDATED_SIG = keccak256("NominUpdated(address)"); function emitNominUpdated(address newNomin) internal { proxy._emit(abi.encode(newNomin), 1, NOMINUPDATED_SIG, 0, 0, 0); } event EscrowUpdated(address newEscrow); bytes32 constant ESCROWUPDATED_SIG = keccak256("EscrowUpdated(address)"); function emitEscrowUpdated(address newEscrow) internal { proxy._emit(abi.encode(newEscrow), 1, ESCROWUPDATED_SIG, 0, 0, 0); } event IssuersUpdated(address indexed account, bool indexed value); bytes32 constant ISSUERSUPDATED_SIG = keccak256("IssuersUpdated(address,bool)"); function emitIssuersUpdated(address account, bool value) internal { proxy._emit(abi.encode(), 3, ISSUERSUPDATED_SIG, bytes32(account), bytes32(value ? 1 : 0), 0); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: IssuanceController.sol version: 2.0 author: Kevin Brown date: 2018-07-18 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Issuance controller contract. The issuance controller provides a way for users to acquire nomins (Nomin.sol) and havvens (Havven.sol) by paying ETH and a way for users to acquire havvens (Havven.sol) by paying nomins. Users can also deposit their nomins and allow other users to purchase them with ETH. The ETH is sent to the user who offered their nomins for sale. This smart contract contains a balance of each currency, and allows the owner of the contract (the Havven Foundation) to manage the available balance of havven at their discretion, while users are allowed to deposit and withdraw their own nomin deposits if they have not yet been taken up by another user. ----------------------------------------------------------------- */ /** * @title Issuance Controller Contract. */ contract IssuanceController is SafeDecimalMath, SelfDestructible, Pausable { /* ========== STATE VARIABLES ========== */ Havven public havven; Nomin public nomin; // Address where the ether raised is transfered to address public fundsWallet; /* The address of the oracle which pushes the USD price havvens and ether to this contract */ address public oracle; /* Do not allow the oracle to submit times any further forward into the future than this constant. */ uint constant ORACLE_FUTURE_LIMIT = 10 minutes; /* How long will the contract assume the price of any asset is correct */ uint public priceStalePeriod = 3 hours; /* The time the prices were last updated */ uint public lastPriceUpdateTime; /* The USD price of havvens denominated in UNIT */ uint public usdToHavPrice; /* The USD price of ETH denominated in UNIT */ uint public usdToEthPrice; /* ========== CONSTRUCTOR ========== */ /** * @dev Constructor * @param _owner The owner of this contract. * @param _fundsWallet The recipient of ETH and Nomins that are sent to this contract while exchanging. * @param _havven The Havven contract we&#39;ll interact with for balances and sending. * @param _nomin The Nomin contract we&#39;ll interact with for balances and sending. * @param _oracle The address which is able to update price information. * @param _usdToEthPrice The current price of ETH in USD, expressed in UNIT. * @param _usdToHavPrice The current price of Havven in USD, expressed in UNIT. */ constructor( // Ownable address _owner, // Funds Wallet address _fundsWallet, // Other contracts needed Havven _havven, Nomin _nomin, // Oracle values - Allows for price updates address _oracle, uint _usdToEthPrice, uint _usdToHavPrice ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) Pausable(_owner) public { fundsWallet = _fundsWallet; havven = _havven; nomin = _nomin; oracle = _oracle; usdToEthPrice = _usdToEthPrice; usdToHavPrice = _usdToHavPrice; lastPriceUpdateTime = now; } /* ========== SETTERS ========== */ /** * @notice Set the funds wallet where ETH raised is held * @param _fundsWallet The new address to forward ETH and Nomins to */ function setFundsWallet(address _fundsWallet) external onlyOwner { fundsWallet = _fundsWallet; emit FundsWalletUpdated(fundsWallet); } /** * @notice Set the Oracle that pushes the havven price to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the Nomin contract that the issuance controller uses to issue Nomins. * @param _nomin The new nomin contract target */ function setNomin(Nomin _nomin) external onlyOwner { nomin = _nomin; emit NominUpdated(_nomin); } /** * @notice Set the Havven contract that the issuance controller uses to issue Havvens. * @param _havven The new havven contract target */ function setHavven(Havven _havven) external onlyOwner { havven = _havven; emit HavvenUpdated(_havven); } /** * @notice Set the stale period on the updated price variables * @param _time The new priceStalePeriod */ function setPriceStalePeriod(uint _time) external onlyOwner { priceStalePeriod = _time; emit PriceStalePeriodUpdated(priceStalePeriod); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Access point for the oracle to update the prices of havvens / eth. * @param newEthPrice The current price of ether in USD, specified to 18 decimal places. * @param newHavvenPrice The current price of havvens in USD, specified to 18 decimal places. * @param timeSent The timestamp from the oracle when the transaction was created. This ensures we don&#39;t consider stale prices as current in times of heavy network congestion. */ function updatePrices(uint newEthPrice, uint newHavvenPrice, uint timeSent) external onlyOracle { /* Must be the most recently sent price, but not too far in the future. * (so we can&#39;t lock ourselves out of updating the oracle for longer than this) */ require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT, "Time sent must be bigger than the last update, and must be less than now + ORACLE_FUTURE_LIMIT"); usdToEthPrice = newEthPrice; usdToHavPrice = newHavvenPrice; lastPriceUpdateTime = timeSent; emit PricesUpdated(usdToEthPrice, usdToHavPrice, lastPriceUpdateTime); } /** * @notice Fallback function (exchanges ETH to nUSD) */ function () external payable { exchangeEtherForNomins(); } /** * @notice Exchange ETH to nUSD. */ function exchangeEtherForNomins() public payable pricesNotStale notPaused returns (uint) // Returns the number of Nomins (nUSD) received { // The multiplication works here because usdToEthPrice is specified in // 18 decimal places, just like our currency base. uint requestedToPurchase = safeMul_dec(msg.value, usdToEthPrice); // Store the ETH in our funds wallet fundsWallet.transfer(msg.value); // Send the nomins. // Note: Fees are calculated by the Nomin contract, so when // we request a specific transfer here, the fee is // automatically deducted and sent to the fee pool. nomin.transfer(msg.sender, requestedToPurchase); emit Exchange("ETH", msg.value, "nUSD", requestedToPurchase); return requestedToPurchase; } /** * @notice Exchange ETH to nUSD while insisting on a particular rate. This allows a user to * exchange while protecting against frontrunning by the contract owner on the exchange rate. * @param guaranteedRate The exchange rate (ether price) which must be honored or the call will revert. */ function exchangeEtherForNominsAtRate(uint guaranteedRate) public payable pricesNotStale notPaused returns (uint) // Returns the number of Nomins (nUSD) received { require(guaranteedRate == usdToEthPrice); return exchangeEtherForNomins(); } /** * @notice Exchange ETH to HAV. */ function exchangeEtherForHavvens() public payable pricesNotStale notPaused returns (uint) // Returns the number of Havvens (HAV) received { // How many Havvens are they going to be receiving? uint havvensToSend = havvensReceivedForEther(msg.value); // Store the ETH in our funds wallet fundsWallet.transfer(msg.value); // And send them the Havvens. havven.transfer(msg.sender, havvensToSend); emit Exchange("ETH", msg.value, "HAV", havvensToSend); return havvensToSend; } /** * @notice Exchange ETH to HAV while insisting on a particular set of rates. This allows a user to * exchange while protecting against frontrunning by the contract owner on the exchange rates. * @param guaranteedEtherRate The ether exchange rate which must be honored or the call will revert. * @param guaranteedHavvenRate The havven exchange rate which must be honored or the call will revert. */ function exchangeEtherForHavvensAtRate(uint guaranteedEtherRate, uint guaranteedHavvenRate) public payable pricesNotStale notPaused returns (uint) // Returns the number of Havvens (HAV) received { require(guaranteedEtherRate == usdToEthPrice); require(guaranteedHavvenRate == usdToHavPrice); return exchangeEtherForHavvens(); } /** * @notice Exchange nUSD for Havvens * @param nominAmount The amount of nomins the user wishes to exchange. */ function exchangeNominsForHavvens(uint nominAmount) public pricesNotStale notPaused returns (uint) // Returns the number of Havvens (HAV) received { // How many Havvens are they going to be receiving? uint havvensToSend = havvensReceivedForNomins(nominAmount); // Ok, transfer the Nomins to our address. nomin.transferFrom(msg.sender, this, nominAmount); // And send them the Havvens. havven.transfer(msg.sender, havvensToSend); emit Exchange("nUSD", nominAmount, "HAV", havvensToSend); return havvensToSend; } /** * @notice Exchange nUSD for Havvens while insisting on a particular rate. This allows a user to * exchange while protecting against frontrunning by the contract owner on the exchange rate. * @param nominAmount The amount of nomins the user wishes to exchange. * @param guaranteedRate A rate (havven price) the caller wishes to insist upon. */ function exchangeNominsForHavvensAtRate(uint nominAmount, uint guaranteedRate) public pricesNotStale notPaused returns (uint) // Returns the number of Havvens (HAV) received { require(guaranteedRate == usdToHavPrice); return exchangeNominsForHavvens(nominAmount); } /** * @notice Allows the owner to withdraw havvens from this contract if needed. * @param amount The amount of havvens to attempt to withdraw (in 18 decimal places). */ function withdrawHavvens(uint amount) external onlyOwner { havven.transfer(owner, amount); // We don&#39;t emit our own events here because we assume that anyone // who wants to watch what the Issuance Controller is doing can // just watch ERC20 events from the Nomin and/or Havven contracts // filtered to our address. } /** * @notice Withdraw nomins: Allows the owner to withdraw nomins from this contract if needed. * @param amount The amount of nomins to attempt to withdraw (in 18 decimal places). */ function withdrawNomins(uint amount) external onlyOwner { nomin.transfer(owner, amount); // We don&#39;t emit our own events here because we assume that anyone // who wants to watch what the Issuance Controller is doing can // just watch ERC20 events from the Nomin and/or Havven contracts // filtered to our address. } /* ========== VIEWS ========== */ /** * @notice Check if the prices haven&#39;t been updated for longer than the stale period. */ function pricesAreStale() public view returns (bool) { return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now; } /** * @notice Calculate how many havvens you will receive if you transfer * an amount of nomins. * @param amount The amount of nomins (in 18 decimal places) you want to ask about */ function havvensReceivedForNomins(uint amount) public view returns (uint) { // How many nomins would we receive after the transfer fee? uint nominsReceived = nomin.amountReceived(amount); // And what would that be worth in havvens based on the current price? return safeDiv_dec(nominsReceived, usdToHavPrice); } /** * @notice Calculate how many havvens you will receive if you transfer * an amount of ether. * @param amount The amount of ether (in wei) you want to ask about */ function havvensReceivedForEther(uint amount) public view returns (uint) { // How much is the ETH they sent us worth in nUSD (ignoring the transfer fee)? uint valueSentInNomins = safeMul_dec(amount, usdToEthPrice); // Now, how many HAV will that USD amount buy? return havvensReceivedForNomins(valueSentInNomins); } /** * @notice Calculate how many nomins you will receive if you transfer * an amount of ether. * @param amount The amount of ether (in wei) you want to ask about */ function nominsReceivedForEther(uint amount) public view returns (uint) { // How many nomins would that amount of ether be worth? uint nominsTransferred = safeMul_dec(amount, usdToEthPrice); // And how many of those would you receive after a transfer (deducting the transfer fee) return nomin.amountReceived(nominsTransferred); } /* ========== MODIFIERS ========== */ modifier onlyOracle { require(msg.sender == oracle, "Must be oracle to perform this action"); _; } modifier pricesNotStale { require(!pricesAreStale(), "Prices must not be stale to perform this action"); _; } /* ========== EVENTS ========== */ event FundsWalletUpdated(address newFundsWallet); event OracleUpdated(address newOracle); event NominUpdated(Nomin newNominContract); event HavvenUpdated(Havven newHavvenContract); event PriceStalePeriodUpdated(uint priceStalePeriod); event PricesUpdated(uint newEthPrice, uint newHavvenPrice, uint timeSent); event Exchange(string fromCurrency, uint fromAmount, string toCurrency, uint toAmount); }
Allows the owner to withdraw havvens from this contract if needed. amount The amount of havvens to attempt to withdraw (in 18 decimal places)./ We don&39;t emit our own events here because we assume that anyone who wants to watch what the Issuance Controller is doing can just watch ERC20 events from the Nomin and/or Havven contracts filtered to our address.
function withdrawHavvens(uint amount) external onlyOwner { havven.transfer(owner, amount); }
2,140,247
./partial_match/1/0x2bdDD797FB8dFEfFcf3363481D8f2d861535549c/sources/6.VRFV2WrapperConsumerBase.sol
fulfillRandomWords handles the VRF V2 wrapper response. The consuming contract must implement it. _requestId is the VRF V2 request ID. _randomWords is the randomness result./
function fulfillRandomWords(uint256 _requestId, uint256[] memory _randomWords) internal virtual; function rawFulfillRandomWords(uint256 _requestId, uint256[] memory _randomWords) external { require(msg.sender == address(VRF_V2_WRAPPER), "only VRF V2 wrapper can fulfill"); fulfillRandomWords(_requestId, _randomWords); }
2,640,810
./partial_match/1/0xcC3c4A84a11E80752B217Fbb3b2DD9f99DE512f5/sources/contracts/H2HVRF2.sol
cancels a raffle, and in the case of having some entries bought, it refunds them Avoid cancelling two times the same raffle if there are already players
function cancelRaffle(uint256 _raffleId) external onlyRole(OPERATOR_ROLE) { RaffleStruct storage raffle = raffles[_raffleId]; require(raffle.status != STATUS.CANCELLED, "Already canceled"); uint256 amountOfEntries = raffle.entriesLength; function changeBlackList(address _blacklistManager) external onlyRole(OPERATOR_ROLE) } if (amountOfEntries > 0) { for (uint256 i; i < amountOfEntries; ++i) { (bool sentFundsBack, ) = entriesList[_raffleId][i].player.call{ value: raffle.price }(""); require(sentFundsBack, "Failed to refund"); } } raffle.status = STATUS.CANCELLED; raffle.cancellingDate = uint48(block.timestamp); emit RaffleCancelled(_raffleId, raffle.amountRaised); function changeBlackList(address _blacklistManager) external onlyRole(OPERATOR_ROLE) } if (amountOfEntries > 0) { for (uint256 i; i < amountOfEntries; ++i) { (bool sentFundsBack, ) = entriesList[_raffleId][i].player.call{ value: raffle.price }(""); require(sentFundsBack, "Failed to refund"); } } raffle.status = STATUS.CANCELLED; raffle.cancellingDate = uint48(block.timestamp); emit RaffleCancelled(_raffleId, raffle.amountRaised); function changeBlackList(address _blacklistManager) external onlyRole(OPERATOR_ROLE) } if (amountOfEntries > 0) { for (uint256 i; i < amountOfEntries; ++i) { (bool sentFundsBack, ) = entriesList[_raffleId][i].player.call{ value: raffle.price }(""); require(sentFundsBack, "Failed to refund"); } } raffle.status = STATUS.CANCELLED; raffle.cancellingDate = uint48(block.timestamp); emit RaffleCancelled(_raffleId, raffle.amountRaised); }
15,489,731
./full_match/4/0x121a7741a1C0a5e29F0fe69522A1D9cB8767E1Fc/sources/contracts/peupTest.sol
Returns the license for tokens
function tokenLicense(uint _id) public view returns(string memory) { require(_id < totalSupply(), "CHOOSE A PEOPLEEUM WITHIN RANGE"); return LICENSE_TEXT; }
12,441,992
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "../interfaces/IUniswapV2Router02.sol"; import "../interfaces/IwsKLIMA.sol"; import "../interfaces/IRetireBridgeCommon.sol"; import "../interfaces/IRetireMossCarbon.sol"; import "../interfaces/IRetireToucanCarbon.sol"; import "../interfaces/IRetireC3Carbon.sol"; /** * @title KlimaRetirementAggregator * @author KlimaDAO * * @notice This is the master aggregator contract for the Klima retirement utility. * * This allows a user to provide a source token and an approved carbon pool token to retire. * If the source is different than the pool, it will attempt to swap to that pool then retire. */ contract KlimaRetirementAggregator is Initializable, ContextUpgradeable, OwnableUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; function initialize() public initializer { __Ownable_init(); __Context_init(); } /** === State Variables and Mappings === */ address public KLIMA; address public sKLIMA; address public wsKLIMA; address public USDC; address public staking; address public stakingHelper; address public treasury; address public klimaRetirementStorage; mapping(address => bool) public isPoolToken; mapping(address => uint256) public poolBridge; mapping(uint256 => address) public bridgeHelper; /** === Event Setup === */ event AddressUpdated( uint256 addressIndex, address indexed oldAddress, address indexed newAddress ); event PoolAdded(address poolToken, uint256 bridge); event PoolRemoved(address poolToken); event BridgeHelperUpdated(uint256 bridgeID, address helper); /** === Non Specific Auto Retirements */ /** * @notice This function will retire a carbon pool token that is held * in the caller's wallet. Depending on the pool provided the appropriate * retirement helper will be used as defined in the bridgeHelper mapping. * If a token other than the pool is provided then the helper will attempt * to swap to the appropriate pool and then retire. * * @param _sourceToken The contract address of the token being supplied. * @param _poolToken The contract address of the pool token being retired. * @param _amount The amount being supplied. Expressed in either the total * carbon to offset or the total source to spend. See _amountInCarbon. * @param _amountInCarbon Bool indicating if _amount is in carbon or source. * @param _beneficiaryAddress Address of the beneficiary of the retirement. * @param _beneficiaryString String representing the beneficiary. A name perhaps. * @param _retirementMessage Specific message relating to this retirement event. */ function retireCarbon( address _sourceToken, address _poolToken, uint256 _amount, bool _amountInCarbon, address _beneficiaryAddress, string memory _beneficiaryString, string memory _retirementMessage ) public { require(isPoolToken[_poolToken], "Pool Token Not Accepted."); (uint256 sourceAmount, ) = getSourceAmount( _sourceToken, _poolToken, _amount, _amountInCarbon ); IERC20Upgradeable(_sourceToken).safeTransferFrom( _msgSender(), address(this), sourceAmount ); _retireCarbon( _sourceToken, _poolToken, _amount, _amountInCarbon, _beneficiaryAddress, _beneficiaryString, _retirementMessage, _msgSender() ); } /** * @notice This function will retire a carbon pool token that has been * transferred to this contract. Useful when an intermediary contract has * approval to transfer the source tokens from the initiator. * Depending on the pool provided the appropriate retirement helper will * be used as defined in the bridgeHelper mapping. If a token other than * the pool is provided then the helper will attempt to swap to the * appropriate pool and then retire. * * @param _initiator The original sender of the transaction. * @param _sourceToken The contract address of the token being supplied. * @param _poolToken The contract address of the pool token being retired. * @param _amount The amount being supplied. Expressed in either the total * carbon to offset or the total source to spend. See _amountInCarbon. * @param _amountInCarbon Bool indicating if _amount is in carbon or source. * @param _beneficiaryAddress Address of the beneficiary of the retirement. * @param _beneficiaryString String representing the beneficiary. A name perhaps. * @param _retirementMessage Specific message relating to this retirement event. */ function retireCarbonFrom( address _initiator, address _sourceToken, address _poolToken, uint256 _amount, bool _amountInCarbon, address _beneficiaryAddress, string memory _beneficiaryString, string memory _retirementMessage ) public { require(isPoolToken[_poolToken], "Pool Token Not Accepted."); _retireCarbon( _sourceToken, _poolToken, _amount, _amountInCarbon, _beneficiaryAddress, _beneficiaryString, _retirementMessage, _initiator ); } /** * @notice Internal function that checks to make sure the needed source tokens * have been transferred to this contract, then calls the retirement function * on the bridge's specific helper contract. * * @param _sourceToken The contract address of the token being supplied. * @param _poolToken The contract address of the pool token being retired. * @param _amount The amount being supplied. Expressed in either the total * carbon to offset or the total source to spend. See _amountInCarbon. * @param _amountInCarbon Bool indicating if _amount is in carbon or source. * @param _beneficiaryAddress Address of the beneficiary of the retirement. * @param _beneficiaryString String representing the beneficiary. A name perhaps. * @param _retirementMessage Specific message relating to this retirement event. * @param _retiree Address of the initiator where source tokens originated. */ function _retireCarbon( address _sourceToken, address _poolToken, uint256 _amount, bool _amountInCarbon, address _beneficiaryAddress, string memory _beneficiaryString, string memory _retirementMessage, address _retiree ) internal { (uint256 sourceAmount, ) = getSourceAmount( _sourceToken, _poolToken, _amount, _amountInCarbon ); require( IERC20Upgradeable(_sourceToken).balanceOf(address(this)) == sourceAmount, "Source tokens not transferred." ); IERC20Upgradeable(_sourceToken).safeIncreaseAllowance( bridgeHelper[poolBridge[_poolToken]], sourceAmount ); if (poolBridge[_poolToken] == 0) { IRetireMossCarbon(bridgeHelper[0]).retireMoss( _sourceToken, _poolToken, _amount, _amountInCarbon, _beneficiaryAddress, _beneficiaryString, _retirementMessage, _retiree ); } else if (poolBridge[_poolToken] == 1) { IRetireToucanCarbon(bridgeHelper[1]).retireToucan( _sourceToken, _poolToken, _amount, _amountInCarbon, _beneficiaryAddress, _beneficiaryString, _retirementMessage, _retiree ); } else if (poolBridge[_poolToken] == 2) { IRetireC3Carbon(bridgeHelper[2]).retireC3( _sourceToken, _poolToken, _amount, _amountInCarbon, _beneficiaryAddress, _beneficiaryString, _retirementMessage, _retiree ); } } /** === Specific offset selection retirements === */ /** * @notice This function will retire a carbon pool token that is held * in the caller's wallet. Depending on the pool provided the appropriate * retirement helper will be used as defined in the bridgeHelper mapping. * If a token other than the pool is provided then the helper will attempt * to swap to the appropriate pool and then retire. * * @param _sourceToken The contract address of the token being supplied. * @param _poolToken The contract address of the pool token being retired. * @param _amount The amount being supplied. Expressed in either the total * carbon to offset or the total source to spend. See _amountInCarbon. * @param _amountInCarbon Bool indicating if _amount is in carbon or source. * @param _beneficiaryAddress Address of the beneficiary of the retirement. * @param _beneficiaryString String representing the beneficiary. A name perhaps. * @param _retirementMessage Specific message relating to this retirement event. */ function retireCarbonSpecific( address _sourceToken, address _poolToken, uint256 _amount, bool _amountInCarbon, address _beneficiaryAddress, string memory _beneficiaryString, string memory _retirementMessage, address[] memory _carbonList ) public { //require(isPoolToken[_poolToken], "Pool Token Not Accepted."); (uint256 sourceAmount, ) = getSourceAmountSpecific( _sourceToken, _poolToken, _amount, _amountInCarbon ); IERC20Upgradeable(_sourceToken).safeTransferFrom( _msgSender(), address(this), sourceAmount ); _retireCarbonSpecific( _sourceToken, _poolToken, _amount, _amountInCarbon, _beneficiaryAddress, _beneficiaryString, _retirementMessage, _msgSender(), _carbonList ); } function retireCarbonSpecificFrom( address _initiator, address _sourceToken, address _poolToken, uint256 _amount, bool _amountInCarbon, address _beneficiaryAddress, string memory _beneficiaryString, string memory _retirementMessage, address[] memory _carbonList ) public { address retiree = _initiator; _retireCarbonSpecific( _sourceToken, _poolToken, _amount, _amountInCarbon, _beneficiaryAddress, _beneficiaryString, _retirementMessage, retiree, _carbonList ); } /** * @notice Internal function that checks to make sure the needed source tokens * have been transferred to this contract, then calls the retirement function * on the bridge's specific helper contract. * * @param _sourceToken The contract address of the token being supplied. * @param _poolToken The contract address of the pool token being retired. * @param _amount The amount being supplied. Expressed in either the total * carbon to offset or the total source to spend. See _amountInCarbon. * @param _amountInCarbon Bool indicating if _amount is in carbon or source. * @param _beneficiaryAddress Address of the beneficiary of the retirement. * @param _beneficiaryString String representing the beneficiary. A name perhaps. * @param _retirementMessage Specific message relating to this retirement event. * @param _retiree Address of the initiator where source tokens originated. */ function _retireCarbonSpecific( address _sourceToken, address _poolToken, uint256 _amount, bool _amountInCarbon, address _beneficiaryAddress, string memory _beneficiaryString, string memory _retirementMessage, address _retiree, address[] memory _carbonList ) internal { require(isPoolToken[_poolToken], "Pool Token Not Accepted."); // Only Toucan and C3 currently allow specific retirement. require( poolBridge[_poolToken] == 1 || poolBridge[_poolToken] == 2, "Pool does not allow specific." ); _prepareRetireSpecific( _sourceToken, _poolToken, _amount, _amountInCarbon ); if (poolBridge[_poolToken] == 0) { // Reserve for possible future use. } else if (poolBridge[_poolToken] == 1) { IRetireToucanCarbon(bridgeHelper[1]).retireToucanSpecific( _sourceToken, _poolToken, _amount, _amountInCarbon, _beneficiaryAddress, _beneficiaryString, _retirementMessage, _retiree, _carbonList ); } else if (poolBridge[_poolToken] == 2) { IRetireC3Carbon(bridgeHelper[2]).retireC3Specific( _sourceToken, _poolToken, _amount, _amountInCarbon, _beneficiaryAddress, _beneficiaryString, _retirementMessage, _retiree, _carbonList ); } } function _prepareRetireSpecific( address _sourceToken, address _poolToken, uint256 _amount, bool _amountInCarbon ) internal { (uint256 sourceAmount, ) = getSourceAmountSpecific( _sourceToken, _poolToken, _amount, _amountInCarbon ); require( IERC20Upgradeable(_sourceToken).balanceOf(address(this)) == sourceAmount, "Source tokens not transferred." ); IERC20Upgradeable(_sourceToken).safeIncreaseAllowance( bridgeHelper[poolBridge[_poolToken]], sourceAmount ); } /** === External views and helpful functions === */ /** * @notice This function calls the appropriate helper for a pool token and * returns the total amount in source tokens needed to perform the transaction. * Any swap slippage buffers and fees are included in the return value. * * @param _sourceToken The contract address of the token being supplied. * @param _poolToken The contract address of the pool token being retired. * @param _amount The amount being supplied. Expressed in either the total * carbon to offset or the total source to spend. See _amountInCarbon. * @param _amountInCarbon Bool indicating if _amount is in carbon or source. * @return Returns both the source amount and carbon amount as a result of swaps. */ function getSourceAmount( address _sourceToken, address _poolToken, uint256 _amount, bool _amountInCarbon ) public view returns (uint256, uint256) { uint256 sourceAmount; uint256 carbonAmount = _amount; if (_amountInCarbon) { (sourceAmount, ) = IRetireBridgeCommon( bridgeHelper[poolBridge[_poolToken]] ).getNeededBuyAmount(_sourceToken, _poolToken, _amount, false); if (_sourceToken == wsKLIMA) { sourceAmount = IwsKLIMA(wsKLIMA).sKLIMATowKLIMA(sourceAmount); } } else { sourceAmount = _amount; address poolRouter = IRetireBridgeCommon( bridgeHelper[poolBridge[_poolToken]] ).poolRouter(_poolToken); address[] memory path = IRetireBridgeCommon( bridgeHelper[poolBridge[_poolToken]] ).getSwapPath(_sourceToken, _poolToken); uint256[] memory amountsOut = IUniswapV2Router02(poolRouter) .getAmountsOut(_amount, path); carbonAmount = amountsOut[path.length - 1]; } return (sourceAmount, carbonAmount); } /** * @notice Same as getSourceAmount, but factors in the redemption fee * for specific retirements. * * @param _sourceToken The contract address of the token being supplied. * @param _poolToken The contract address of the pool token being retired. * @param _amount The amount being supplied. Expressed in either the total * carbon to offset or the total source to spend. See _amountInCarbon. * @param _amountInCarbon Bool indicating if _amount is in carbon or source. * @return Returns both the source amount and carbon amount as a result of swaps. */ function getSourceAmountSpecific( address _sourceToken, address _poolToken, uint256 _amount, bool _amountInCarbon ) public view returns (uint256, uint256) { uint256 sourceAmount; uint256 carbonAmount = _amount; if (_amountInCarbon) { (sourceAmount, ) = IRetireBridgeCommon( bridgeHelper[poolBridge[_poolToken]] ).getNeededBuyAmount(_sourceToken, _poolToken, _amount, true); if (_sourceToken == wsKLIMA) { sourceAmount = IwsKLIMA(wsKLIMA).sKLIMATowKLIMA(sourceAmount); } } else { sourceAmount = _amount; address poolRouter = IRetireBridgeCommon( bridgeHelper[poolBridge[_poolToken]] ).poolRouter(_poolToken); address[] memory path = IRetireBridgeCommon( bridgeHelper[poolBridge[_poolToken]] ).getSwapPath(_sourceToken, _poolToken); uint256[] memory amountsOut = IUniswapV2Router02(poolRouter) .getAmountsOut(_amount, path); carbonAmount = amountsOut[path.length - 1]; } return (sourceAmount, carbonAmount); } /** * @notice Allow the contract owner to update Klima protocol addresses * resulting from possible migrations. * @param _selection Int to indicate which address is being updated. * @param _newAddress New address for contract needing to be updated. * @return bool */ function setAddress(uint256 _selection, address _newAddress) external onlyOwner returns (bool) { address oldAddress; if (_selection == 0) { oldAddress = KLIMA; KLIMA = _newAddress; // 0; Set new KLIMA address } else if (_selection == 1) { oldAddress = sKLIMA; sKLIMA = _newAddress; // 1; Set new sKLIMA address } else if (_selection == 2) { oldAddress = wsKLIMA; wsKLIMA = _newAddress; // 2; Set new wsKLIMA address } else if (_selection == 3) { oldAddress = USDC; USDC = _newAddress; // 3; Set new USDC address } else if (_selection == 4) { oldAddress = staking; staking = _newAddress; // 4; Set new staking address } else if (_selection == 5) { oldAddress = stakingHelper; stakingHelper = _newAddress; // 5; Set new stakingHelper address } else if (_selection == 6) { oldAddress = treasury; treasury = _newAddress; // 6; Set new treasury address } else if (_selection == 7) { oldAddress = klimaRetirementStorage; klimaRetirementStorage = _newAddress; // 7; Set new storage address } else { return false; } emit AddressUpdated(_selection, oldAddress, _newAddress); return true; } /** * @notice Add a new carbon pool to retire with helper contract. * @param _poolToken Pool being added. * @param _poolBridge Int ID of the bridge used for this token. * @return bool */ function addPool(address _poolToken, uint256 _poolBridge) external onlyOwner returns (bool) { require(!isPoolToken[_poolToken], "Pool already added"); require(_poolToken != address(0), "Pool cannot be zero address"); isPoolToken[_poolToken] = true; poolBridge[_poolToken] = _poolBridge; emit PoolAdded(_poolToken, _poolBridge); return true; } /** @notice Remove a carbon pool to retire. @param _poolToken Pool being removed. @return bool */ function removePool(address _poolToken) external onlyOwner returns (bool) { require(isPoolToken[_poolToken], "Pool not added"); isPoolToken[_poolToken] = false; emit PoolRemoved(_poolToken); return true; } /** @notice Set the helper contract to be used with a carbon bridge. @param _bridgeID Int ID of the bridge. @param _helper Helper contract to use with this bridge. @return bool */ function setBridgeHelper(uint256 _bridgeID, address _helper) external onlyOwner returns (bool) { require(_helper != address(0), "Helper cannot be zero address"); bridgeHelper[_bridgeID] = _helper; emit BridgeHelperUpdated(_bridgeID, _helper); return true; } /** @notice Allow withdrawal of any tokens sent in error @param _token Address of token to transfer */ function feeWithdraw(address _token, address _recipient) external onlyOwner returns (bool) { IERC20Upgradeable(_token).safeTransfer( _recipient, IERC20Upgradeable(_token).balanceOf(address(this)) ); return true; } }
This function will retire a carbon pool token that is held in the caller's wallet. Depending on the pool provided the appropriate retirement helper will be used as defined in the bridgeHelper mapping. If a token other than the pool is provided then the helper will attempt to swap to the appropriate pool and then retire. _sourceToken The contract address of the token being supplied. _poolToken The contract address of the pool token being retired. _amount The amount being supplied. Expressed in either the total carbon to offset or the total source to spend. See _amountInCarbon. _amountInCarbon Bool indicating if _amount is in carbon or source. _beneficiaryAddress Address of the beneficiary of the retirement. _beneficiaryString String representing the beneficiary. A name perhaps. _retirementMessage Specific message relating to this retirement event./
function retireCarbon( address _sourceToken, address _poolToken, uint256 _amount, bool _amountInCarbon, address _beneficiaryAddress, string memory _beneficiaryString, string memory _retirementMessage ) public { require(isPoolToken[_poolToken], "Pool Token Not Accepted."); (uint256 sourceAmount, ) = getSourceAmount( _sourceToken, _poolToken, _amount, _amountInCarbon ); IERC20Upgradeable(_sourceToken).safeTransferFrom( _msgSender(), address(this), sourceAmount ); _retireCarbon( _sourceToken, _poolToken, _amount, _amountInCarbon, _beneficiaryAddress, _beneficiaryString, _retirementMessage, _msgSender() ); }
12,967,504
pragma solidity 0.4.18; /// @title ERC Token Standard #20 Interface (https://github.com/ethereum/EIPs/issues/20) contract ERC20 { uint public totalSupply; function balanceOf(address _owner) constant public returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint remaining); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /// @title Basic ERC20 token contract implementation. /// @dev Based on OpenZeppelin's StandardToken. contract BasicToken is ERC20 { using SafeMath for uint256; uint256 public totalSupply; mapping (address => mapping (address => uint256)) allowed; mapping (address => uint256) balances; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); /// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. /// @param _spender address The address which will spend the funds. /// @param _value uint256 The amount of tokens to be spent. function approve(address _spender, uint256 _value) public returns (bool) { // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve (see NOTE) if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) { revert(); } allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /// @dev Function to check the amount of tokens that an owner allowed to a spender. /// @param _owner address The address which owns the funds. /// @param _spender address The address which will spend the funds. /// @return uint256 specifying the amount of tokens still available for the spender. function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @dev Gets the balance of the specified address. /// @param _owner address The address to query the the balance of. /// @return uint256 representing the amount owned by the passed address. function balanceOf(address _owner) constant public returns (uint256 balance) { return balances[_owner]; } /// @dev Transfer token to a specified address. /// @param _to address The address to transfer to. /// @param _value uint256 The amount to be transferred. function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _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(_to != address(0)); var _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } } /// @title ERC Token Standard #677 Interface (https://github.com/ethereum/EIPs/issues/677) contract ERC677 is ERC20 { function transferAndCall(address to, uint value, bytes data) public returns (bool ok); event TransferAndCall(address indexed from, address indexed to, uint value, bytes data); } /// @title Math operations with safety checks library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // require(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // require(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function toPower2(uint256 a) internal pure returns (uint256) { return mul(a, a); } function sqrt(uint256 a) internal pure returns (uint256) { uint256 c = (a + 1) / 2; uint256 b = a; while (c < b) { b = c; c = (a / c + c) / 2; } return b; } } /// @title Standard677Token implentation, base on https://github.com/ethereum/EIPs/issues/677 contract Standard677Token is ERC677, BasicToken { /// @dev ERC223 safe token transfer from one address to another /// @param _to address the address which you want to transfer to. /// @param _value uint256 the amount of tokens to be transferred. /// @param _data bytes data that can be attached to the token transation function transferAndCall(address _to, uint _value, bytes _data) public returns (bool) { require(super.transfer(_to, _value)); // do a normal token transfer TransferAndCall(msg.sender, _to, _value, _data); //filtering if the target is a contract with bytecode inside it if (isContract(_to)) return contractFallback(_to, _value, _data); return true; } /// @dev called when transaction target is a contract /// @param _to address the address which you want to transfer to. /// @param _value uint256 the amount of tokens to be transferred. /// @param _data bytes data that can be attached to the token transation function contractFallback(address _to, uint _value, bytes _data) private returns (bool) { ERC223Receiver receiver = ERC223Receiver(_to); require(receiver.tokenFallback(msg.sender, _value, _data)); return true; } /// @dev check if the address is contract /// assemble the given address bytecode. If bytecode exists then the _addr is a contract. /// @param _addr address the address to check function isContract(address _addr) private constant returns (bool is_contract) { // retrieve the size of the code on target address, this needs assembly uint length; assembly { length := extcodesize(_addr) } return length > 0; } } /// @title Ownable /// @dev The Ownable contract has an owner address, and provides basic authorization control functions, /// this simplifies the implementation of "user permissions". /// @dev Based on OpenZeppelin's Ownable. contract Ownable { address public owner; address public newOwnerCandidate; event OwnershipRequested(address indexed _by, address indexed _to); event OwnershipTransferred(address indexed _from, address indexed _to); /// @dev Constructor sets the original `owner` of the contract to the sender account. function Ownable() public { owner = msg.sender; } /// @dev Reverts if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyOwnerCandidate() { require(msg.sender == newOwnerCandidate); _; } /// @dev Proposes to transfer control of the contract to a newOwnerCandidate. /// @param _newOwnerCandidate address The address to transfer ownership to. function requestOwnershipTransfer(address _newOwnerCandidate) external onlyOwner { require(_newOwnerCandidate != address(0)); newOwnerCandidate = _newOwnerCandidate; OwnershipRequested(msg.sender, newOwnerCandidate); } /// @dev Accept ownership transfer. This method needs to be called by the perviously proposed owner. function acceptOwnership() external onlyOwnerCandidate { address previousOwner = owner; owner = newOwnerCandidate; newOwnerCandidate = address(0); OwnershipTransferred(previousOwner, owner); } } /// @title Token holder contract. contract TokenHolder is Ownable { /// @dev Allow the owner to transfer out any accidentally sent ERC20 tokens. /// @param _tokenAddress address The address of the ERC20 contract. /// @param _amount uint256 The amount of tokens to be transferred. function transferAnyERC20Token(address _tokenAddress, uint256 _amount) public onlyOwner returns (bool success) { return ERC20(_tokenAddress).transfer(owner, _amount); } } /// @title Colu Local Currency contract. /// @author Rotem Lev. contract ColuLocalCurrency is Ownable, Standard677Token, TokenHolder { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; /// @dev cotract to use when issuing a CC (Local Currency) /// @param _name string name for CC token that is created. /// @param _symbol string symbol for CC token that is created. /// @param _decimals uint8 percison for CC token that is created. /// @param _totalSupply uint256 total supply of the CC token that is created. function ColuLocalCurrency(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public { require(_totalSupply != 0); require(bytes(_name).length != 0); require(bytes(_symbol).length != 0); totalSupply = _totalSupply; name = _name; symbol = _symbol; decimals = _decimals; balances[msg.sender] = totalSupply; } } /// @title ERC223Receiver Interface /// @dev Based on the specs form: https://github.com/ethereum/EIPs/issues/223 contract ERC223Receiver { function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok); } /// @title Standard ERC223 Token Receiver implementing tokenFallback function and tokenPayable modifier contract Standard223Receiver is ERC223Receiver { Tkn tkn; struct Tkn { address addr; address sender; // the transaction caller uint256 value; } bool __isTokenFallback; modifier tokenPayable { require(__isTokenFallback); _; } /// @dev Called when the receiver of transfer is contract /// @param _sender address the address of tokens sender /// @param _value uint256 the amount of tokens to be transferred. /// @param _data bytes data that can be attached to the token transation function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok) { if (!supportsToken(msg.sender)) { return false; } // Problem: This will do a sstore which is expensive gas wise. Find a way to keep it in memory. // Solution: Remove the the data tkn = Tkn(msg.sender, _sender, _value); __isTokenFallback = true; if (!address(this).delegatecall(_data)) { __isTokenFallback = false; return false; } // avoid doing an overwrite to .token, which would be more expensive // makes accessing .tkn values outside tokenPayable functions unsafe __isTokenFallback = false; return true; } function supportsToken(address token) public constant returns (bool); } /// @title TokenOwnable /// @dev The TokenOwnable contract adds a onlyTokenOwner modifier as a tokenReceiver with ownable addaptation contract TokenOwnable is Standard223Receiver, Ownable { /// @dev Reverts if called by any account other than the owner for token sending. modifier onlyTokenOwner() { require(tkn.sender == owner); _; } } /// @title Market Maker Interface. /// @author Tal Beja. contract MarketMaker is ERC223Receiver { function getCurrentPrice() public constant returns (uint _price); function change(address _fromToken, uint _amount, address _toToken) public returns (uint _returnAmount); function change(address _fromToken, uint _amount, address _toToken, uint _minReturn) public returns (uint _returnAmount); function change(address _toToken) public returns (uint _returnAmount); function change(address _toToken, uint _minReturn) public returns (uint _returnAmount); function quote(address _fromToken, uint _amount, address _toToken) public constant returns (uint _returnAmount); function openForPublicTrade() public returns (bool success); function isOpenForPublic() public returns (bool success); event Change(address indexed fromToken, uint inAmount, address indexed toToken, uint returnAmount, address indexed account); } /// @title Ellipse Market Maker contract. /// @dev market maker, using ellipse equation. /// @author Tal Beja. contract EllipseMarketMaker is TokenOwnable { // precision for price representation (as in ether or tokens). uint256 public constant PRECISION = 10 ** 18; // The tokens pair. ERC20 public token1; ERC20 public token2; // The tokens reserves. uint256 public R1; uint256 public R2; // The tokens full suplly. uint256 public S1; uint256 public S2; // State flags. bool public operational; bool public openForPublic; // Library contract address. address public mmLib; /// @dev Constructor calling the library contract using delegate. function EllipseMarketMaker(address _mmLib, address _token1, address _token2) public { require(_mmLib != address(0)); // Signature of the mmLib's constructor function // bytes4 sig = bytes4(keccak256("constructor(address,address,address)")); bytes4 sig = 0x6dd23b5b; // 3 arguments of size 32 uint256 argsSize = 3 * 32; // sig + arguments size uint256 dataSize = 4 + argsSize; bytes memory m_data = new bytes(dataSize); assembly { // Add the signature first to memory mstore(add(m_data, 0x20), sig) // Add the parameters mstore(add(m_data, 0x24), _mmLib) mstore(add(m_data, 0x44), _token1) mstore(add(m_data, 0x64), _token2) } // delegatecall to the library contract require(_mmLib.delegatecall(m_data)); } /// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls) /// @param token can be token1 or token2 function supportsToken(address token) public constant returns (bool) { return (token1 == token || token2 == token); } /// @dev gets called when no other function matches, delegate to the lib contract. function() public { address _mmLib = mmLib; if (msg.data.length > 0) { assembly { calldatacopy(0xff, 0, calldatasize) let retVal := delegatecall(gas, _mmLib, 0xff, calldatasize, 0, 0x20) switch retVal case 0 { revert(0,0) } default { return(0, 0x20) } } } } } /// @title Ellipse Market Maker Interfase /// @author Tal Beja contract IEllipseMarketMaker is MarketMaker { // precision for price representation (as in ether or tokens). uint256 public constant PRECISION = 10 ** 18; // The tokens pair. ERC20 public token1; ERC20 public token2; // The tokens reserves. uint256 public R1; uint256 public R2; // The tokens full suplly. uint256 public S1; uint256 public S2; // State flags. bool public operational; bool public openForPublic; // Library contract address. address public mmLib; function supportsToken(address token) public constant returns (bool); function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256); function validateReserves() public view returns (bool); function withdrawExcessReserves() public returns (uint256); function initializeAfterTransfer() public returns (bool); function initializeOnTransfer() public returns (bool); function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256); } /// @title Colu Local Currency + Market Maker factory contract. /// @author Rotem Lev. contract CurrencyFactory is Standard223Receiver, TokenHolder { struct CurrencyStruct { string name; uint8 decimals; uint256 totalSupply; address owner; address mmAddress; } // map of Market Maker owners: token address => currency struct mapping (address => CurrencyStruct) public currencyMap; // address of the deployed CLN contract (ERC20 Token) address public clnAddress; // address of the deployed elipse market maker contract address public mmLibAddress; address[] public tokens; event MarketOpen(address indexed marketMaker); event TokenCreated(address indexed token, address indexed owner); // modifier to check if called by issuer of the token modifier tokenIssuerOnly(address token, address owner) { require(currencyMap[token].owner == owner); _; } // modifier to only accept transferAndCall from CLN token modifier CLNOnly() { require(msg.sender == clnAddress); _; } /// @dev constructor only reuires the address of the CLN token which must use the ERC20 interface /// @param _mmLib address for the deployed market maker elipse contract /// @param _clnAddress address for the deployed ERC20 CLN token function CurrencyFactory(address _mmLib, address _clnAddress) public { require(_mmLib != address(0)); require(_clnAddress != address(0)); mmLibAddress = _mmLib; clnAddress = _clnAddress; } /// @dev create the MarketMaker and the CC token put all the CC token in the Market Maker reserve /// @param _name string name for CC token that is created. /// @param _symbol string symbol for CC token that is created. /// @param _decimals uint8 percison for CC token that is created. /// @param _totalSupply uint256 total supply of the CC token that is created. function createCurrency(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public returns (address) { ColuLocalCurrency subToken = new ColuLocalCurrency(_name, _symbol, _decimals, _totalSupply); EllipseMarketMaker newMarketMaker = new EllipseMarketMaker(mmLibAddress, clnAddress, subToken); //set allowance require(subToken.transfer(newMarketMaker, _totalSupply)); require(IEllipseMarketMaker(newMarketMaker).initializeAfterTransfer()); currencyMap[subToken] = CurrencyStruct({ name: _name, decimals: _decimals, totalSupply: _totalSupply, mmAddress: newMarketMaker, owner: msg.sender}); tokens.push(subToken); TokenCreated(subToken, msg.sender); return subToken; } /// @dev normal send cln to the market maker contract, sender must approve() before calling method. can only be called by owner /// @dev sending CLN will return CC from the reserve to the sender. /// @param _token address address of the cc token managed by this factory. /// @param _clnAmount uint256 amount of CLN to transfer into the Market Maker reserve. function insertCLNtoMarketMaker(address _token, uint256 _clnAmount) public tokenIssuerOnly(_token, msg.sender) returns (uint256 _subTokenAmount) { require(_clnAmount > 0); address marketMakerAddress = getMarketMakerAddressFromToken(_token); require(ERC20(clnAddress).transferFrom(msg.sender, this, _clnAmount)); require(ERC20(clnAddress).approve(marketMakerAddress, _clnAmount)); _subTokenAmount = IEllipseMarketMaker(marketMakerAddress).change(clnAddress, _clnAmount, _token); require(ERC20(_token).transfer(msg.sender, _subTokenAmount)); } /// @dev ERC223 transferAndCall, send cln to the market maker contract can only be called by owner (see MarketMaker) /// @dev sending CLN will return CC from the reserve to the sender. /// @param _token address address of the cc token managed by this factory. function insertCLNtoMarketMaker(address _token) public tokenPayable CLNOnly tokenIssuerOnly(_token, tkn.sender) returns (uint256 _subTokenAmount) { address marketMakerAddress = getMarketMakerAddressFromToken(_token); require(ERC20(clnAddress).approve(marketMakerAddress, tkn.value)); _subTokenAmount = IEllipseMarketMaker(marketMakerAddress).change(clnAddress, tkn.value, _token); require(ERC20(_token).transfer(tkn.sender, _subTokenAmount)); } /// @dev normal send cc to the market maker contract, sender must approve() before calling method. can only be called by owner /// @dev sending CC will return CLN from the reserve to the sender. /// @param _token address address of the cc token managed by this factory. /// @param _ccAmount uint256 amount of CC to transfer into the Market Maker reserve. function extractCLNfromMarketMaker(address _token, uint256 _ccAmount) public tokenIssuerOnly(_token, msg.sender) returns (uint256 _clnTokenAmount) { address marketMakerAddress = getMarketMakerAddressFromToken(_token); require(ERC20(_token).transferFrom(msg.sender, this, _ccAmount)); require(ERC20(_token).approve(marketMakerAddress, _ccAmount)); _clnTokenAmount = IEllipseMarketMaker(marketMakerAddress).change(_token, _ccAmount, clnAddress); require(ERC20(clnAddress).transfer(msg.sender, _clnTokenAmount)); } /// @dev ERC223 transferAndCall, send CC to the market maker contract can only be called by owner (see MarketMaker) /// @dev sending CC will return CLN from the reserve to the sender. function extractCLNfromMarketMaker() public tokenPayable tokenIssuerOnly(msg.sender, tkn.sender) returns (uint256 _clnTokenAmount) { address marketMakerAddress = getMarketMakerAddressFromToken(msg.sender); require(ERC20(msg.sender).approve(marketMakerAddress, tkn.value)); _clnTokenAmount = IEllipseMarketMaker(marketMakerAddress).change(msg.sender, tkn.value, clnAddress); require(ERC20(clnAddress).transfer(tkn.sender, _clnTokenAmount)); } /// @dev opens the Market Maker to recvice transactions from all sources. /// @dev Request to transfer ownership of Market Maker contract to Owner instead of factory. /// @param _token address address of the cc token managed by this factory. function openMarket(address _token) public tokenIssuerOnly(_token, msg.sender) returns (bool) { address marketMakerAddress = getMarketMakerAddressFromToken(_token); require(MarketMaker(marketMakerAddress).openForPublicTrade()); Ownable(marketMakerAddress).requestOwnershipTransfer(msg.sender); MarketOpen(marketMakerAddress); return true; } /// @dev implementation for standard 223 reciver. /// @param _token address of the token used with transferAndCall. function supportsToken(address _token) public constant returns (bool) { return (clnAddress == _token || currencyMap[_token].totalSupply > 0); } /// @dev helper function to get the market maker address form token /// @param _token address of the token used with transferAndCall. function getMarketMakerAddressFromToken(address _token) public constant returns (address _marketMakerAddress) { _marketMakerAddress = currencyMap[_token].mmAddress; require(_marketMakerAddress != address(0)); } } /** * The IssuanceFactory creates an issuance contract that accepts on one side CLN * locks then up in an elipse market maker up to the supplied softcap * and returns a CC token based on price that is derived form the two supplies and reserves of each */ /// @title Colu Issuance factoy with CLN for CC tokens. /// @author Rotem Lev. contract IssuanceFactory is CurrencyFactory { using SafeMath for uint256; uint256 public PRECISION; struct IssuanceStruct { uint256 hardcap; uint256 reserve; uint256 startTime; uint256 endTime; uint256 targetPrice; uint256 clnRaised; } uint256 public totalCLNcustodian; //map of Market Maker owners mapping (address => IssuanceStruct) public issueMap; // total supply of CLN uint256 public CLNTotalSupply; event CLNRaised(address indexed token, address indexed participant, uint256 amount); event CLNRefunded(address indexed token, address indexed participant, uint256 amount); event SaleFinalized(address indexed token, uint256 clnRaised); // sale has begun based on time and status modifier saleOpen(address _token) { require(now >= issueMap[_token].startTime && issueMap[_token].endTime >= now); require(issueMap[_token].clnRaised < issueMap[_token].hardcap); _; } // sale is passed its endtime modifier hasEnded(address _token) { require(issueMap[_token].endTime < now); _; } // sale considered successful when it raised equal to or more than the softcap modifier saleWasSuccessfull(address _token) { require(issueMap[_token].clnRaised >= issueMap[_token].reserve); _; } // sale considerd failed when it raised less than the softcap modifier saleHasFailed(address _token) { require(issueMap[_token].clnRaised < issueMap[_token].reserve); _; } // checks if the instance of market maker contract is closed for public modifier marketClosed(address _token) { require(!MarketMaker(currencyMap[_token].mmAddress).isOpenForPublic()); _; } /// @dev constructor /// @param _mmLib address for the deployed elipse market maker contract /// @param _clnAddress address for the deployed CLN ERC20 token function IssuanceFactory(address _mmLib, address _clnAddress) public CurrencyFactory(_mmLib, _clnAddress) { CLNTotalSupply = ERC20(_clnAddress).totalSupply(); PRECISION = IEllipseMarketMaker(_mmLib).PRECISION(); } /// @dev createIssuance create local currency issuance sale /// @param _startTime uint256 blocktime for sale start /// @param _durationTime uint 256 duration of the sale /// @param _hardcap uint CLN hardcap for issuance /// @param _reserveAmount uint CLN reserve ammount /// @param _name string name of the token /// @param _symbol string symbol of the token /// @param _decimals uint8 ERC20 decimals of local currency /// @param _totalSupply uint total supply of the local currency function createIssuance( uint256 _startTime, uint256 _durationTime, uint256 _hardcap, uint256 _reserveAmount, string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public returns (address) { require(_startTime > now); require(_durationTime > 0); require(_hardcap > 0); uint256 R2 = IEllipseMarketMaker(mmLibAddress).calcReserve(_reserveAmount, CLNTotalSupply, _totalSupply); uint256 targetPrice = IEllipseMarketMaker(mmLibAddress).getPrice(_reserveAmount, R2, CLNTotalSupply, _totalSupply); require(isValidIssuance(_hardcap, targetPrice, _totalSupply, R2)); address tokenAddress = super.createCurrency(_name, _symbol, _decimals, _totalSupply); addToMap(tokenAddress, _startTime, _startTime + _durationTime, _hardcap, _reserveAmount, targetPrice); return tokenAddress; } /// @dev internal helper to add currency data to the issuance map /// @param _token address token address for this issuance (same as CC adress) /// @param _startTime uint256 blocktime for sale start /// @param _endTime uint256 blocktime for sale end /// @param _hardcap uint256 sale hardcap /// @param _reserveAmount uint256 sale softcap /// @param _targetPrice uint256 sale CC price per CLN if it were to pass the softcap function addToMap(address _token, uint256 _startTime, uint256 _endTime, uint256 _hardcap, uint256 _reserveAmount, uint256 _targetPrice) private { issueMap[_token] = IssuanceStruct({ hardcap: _hardcap, reserve: _reserveAmount, startTime: _startTime, endTime: _endTime, clnRaised: 0, targetPrice: _targetPrice}); } /// @dev participate in the issuance of the local currency /// @param _token address token address for this issuance (same as CC adress) /// @param _clnAmount uint256 amount of CLN to try and participate /// @return releaseAmount uint ammount of CC tokens released and transfered to sender function participate(address _token, uint256 _clnAmount) public saleOpen(_token) returns (uint256 releaseAmount) { require(_clnAmount > 0); address marketMakerAddress = getMarketMakerAddressFromToken(_token); // how much do we need to actually send to market maker of the incomming amount // and how much of the amount can participate uint256 transferToReserveAmount; uint256 participationAmount; (transferToReserveAmount, participationAmount) = getParticipationAmounts(_clnAmount, _token); // send what we need to the market maker for reserve require(ERC20(clnAddress).transferFrom(msg.sender, this, participationAmount)); approveAndChange(clnAddress, _token, transferToReserveAmount, marketMakerAddress); // pay back to participant with the participated amount * price releaseAmount = participationAmount.mul(issueMap[_token].targetPrice).div(PRECISION); issueMap[_token].clnRaised = issueMap[_token].clnRaised.add(participationAmount); totalCLNcustodian = totalCLNcustodian.add(participationAmount); CLNRaised(_token, msg.sender, participationAmount); require(ERC20(_token).transfer(msg.sender, releaseAmount)); } /// @dev Participate in the CLN based issuance (for contract) /// @param _token address token address for this issuance (same as CC adress) function participate(address _token) public tokenPayable saleOpen(_token) returns (uint256 releaseAmount) { require(tkn.value > 0 && msg.sender == clnAddress); //check if we need to send cln to mm or save it uint256 transferToReserveAmount; uint256 participationAmount; (transferToReserveAmount, participationAmount) = getParticipationAmounts(tkn.value, _token); address marketMakerAddress = getMarketMakerAddressFromToken(_token); approveAndChange(clnAddress, _token, transferToReserveAmount, marketMakerAddress); // transfer only what we need releaseAmount = participationAmount.mul(issueMap[_token].targetPrice).div(PRECISION); issueMap[_token].clnRaised = issueMap[_token].clnRaised.add(participationAmount); totalCLNcustodian = totalCLNcustodian.add(participationAmount); CLNRaised(_token, tkn.sender, participationAmount); require(ERC20(_token).transfer(tkn.sender, releaseAmount)); // send CLN change to the participent since its transferAndCall if (tkn.value > participationAmount) require(ERC20(clnAddress).transfer(tkn.sender, tkn.value.sub(participationAmount))); } /// @dev called by the creator to finish the sale, open the market maker and get his tokens /// @dev can only be called after the sale end time and if the sale passed the softcap /// @param _token address token address for this issuance (same as CC adress) function finalize(address _token) public tokenIssuerOnly(_token, msg.sender) hasEnded(_token) saleWasSuccessfull(_token) marketClosed(_token) returns (bool) { // move all CC and CLN that were raised and not in the reserves to the issuer address marketMakerAddress = getMarketMakerAddressFromToken(_token); uint256 clnAmount = issueMap[_token].clnRaised.sub(issueMap[_token].reserve); totalCLNcustodian = totalCLNcustodian.sub(clnAmount); uint256 ccAmount = ERC20(_token).balanceOf(this); // open Market Maker for public trade. require(MarketMaker(marketMakerAddress).openForPublicTrade()); require(ERC20(_token).transfer(msg.sender, ccAmount)); require(ERC20(clnAddress).transfer(msg.sender, clnAmount)); SaleFinalized(_token, issueMap[_token].clnRaised); return true; } /// @dev Give back CC and get a refund back in CLN, /// dev can only be called after sale ended and the softcap not reached /// @param _token address token address for this issuance (same as CC adress) /// @param _ccAmount uint256 amount of CC to try and refund function refund(address _token, uint256 _ccAmount) public hasEnded(_token) saleHasFailed(_token) marketClosed(_token) returns (bool) { require(_ccAmount > 0); // exchange CC for CLN throuh Market Maker address marketMakerAddress = getMarketMakerAddressFromToken(_token); require(ERC20(_token).transferFrom(msg.sender, this, _ccAmount)); uint256 factoryCCAmount = ERC20(_token).balanceOf(this); require(ERC20(_token).approve(marketMakerAddress, factoryCCAmount)); require(MarketMaker(marketMakerAddress).change(_token, factoryCCAmount, clnAddress) > 0); uint256 returnAmount = _ccAmount.mul(PRECISION).div(issueMap[_token].targetPrice); issueMap[_token].clnRaised = issueMap[_token].clnRaised.sub(returnAmount); totalCLNcustodian = totalCLNcustodian.sub(returnAmount); CLNRefunded(_token, msg.sender, returnAmount); require(ERC20(clnAddress).transfer(msg.sender, returnAmount)); return true; } /// @dev Give back CC and get a refund back in CLN, /// dev can only be called after sale ended and the softcap not function refund() public tokenPayable hasEnded(msg.sender) saleHasFailed(msg.sender) marketClosed(msg.sender) returns (bool) { require(tkn.value > 0); // if we have CC time to thorw it to the Market Maker address marketMakerAddress = getMarketMakerAddressFromToken(msg.sender); uint256 factoryCCAmount = ERC20(msg.sender).balanceOf(this); require(ERC20(msg.sender).approve(marketMakerAddress, factoryCCAmount)); require(MarketMaker(marketMakerAddress).change(msg.sender, factoryCCAmount, clnAddress) > 0); uint256 returnAmount = tkn.value.mul(PRECISION).div(issueMap[msg.sender].targetPrice); issueMap[msg.sender].clnRaised = issueMap[msg.sender].clnRaised.sub(returnAmount); totalCLNcustodian = totalCLNcustodian.sub(returnAmount); CLNRefunded(msg.sender, tkn.sender, returnAmount); require(ERC20(clnAddress).transfer(tkn.sender, returnAmount)); return true; } /// @dev normal send cln to the market maker contract, sender must approve() before calling method. can only be called by owner /// @dev sending CLN will return CC from the reserve to the sender. function insertCLNtoMarketMaker(address, uint256) public returns (uint256) { require(false); return 0; } /// @dev ERC223 transferAndCall, send cln to the market maker contract can only be called by owner (see MarketMaker) /// @dev sending CLN will return CC from the reserve to the sender. function insertCLNtoMarketMaker(address) public returns (uint256) { require(false); return 0; } /// @dev normal send CC to the market maker contract, sender must approve() before calling method. can only be called by owner /// @dev sending CC will return CLN from the reserve to the sender. function extractCLNfromMarketMaker(address, uint256) public returns (uint256) { require(false); return 0; } /// @dev ERC223 transferAndCall, send CC to the market maker contract can only be called by owner (see MarketMaker) /// @dev sending CC will return CLN from the reserve to the sender. function extractCLNfromMarketMaker() public returns (uint256) { require(false); return 0; } /// @dev opens the Market Maker to recvice transactions from all sources. /// @dev Request to transfer ownership of Market Maker contract to Owner instead of factory. function openMarket(address) public returns (bool) { require(false); return false; } /// @dev checks if the parameters that were sent to the create are valid for a promised price and buyback /// @param _hardcap uint256 CLN hardcap for issuance /// @param _price uint256 computed through the market maker using the supplies and reserves /// @param _S2 uint256 supply of the CC token /// @param _R2 uint256 reserve of the CC token function isValidIssuance(uint256 _hardcap, uint256 _price, uint256 _S2, uint256 _R2) public view returns (bool) { return (_S2 > _R2 && _S2.sub(_R2).mul(PRECISION) >= _hardcap.mul(_price)); } /// @dev helper function to fetch market maker contract address deploed with the CC /// @param _token address token address for this issuance (same as CC adress) function getMarketMakerAddressFromToken(address _token) public constant returns (address) { return currencyMap[_token].mmAddress; } /// @dev helper function to approve tokens for market maker and then change tokens /// @param _token address deployed ERC20 token address to spend /// @param _token2 address deployed ERC20 token address to buy /// @param _amount uint256 amount of _token to spend /// @param _marketMakerAddress address for the deploed market maker with this CC function approveAndChange(address _token, address _token2, uint256 _amount, address _marketMakerAddress) private returns (uint256) { if (_amount > 0) { require(ERC20(_token).approve(_marketMakerAddress, _amount)); return MarketMaker(_marketMakerAddress).change(_token, _amount, _token2); } return 0; } /// @dev helper function participation with CLN /// @dev returns the amount to send to reserve and amount to participate /// @param _clnAmount amount of cln the user wants to participate with /// @param _token address token address for this issuance (same as CC adress) /// @return { /// "transferToReserveAmount": ammount of CLN to transfer to reserves /// "participationAmount": ammount of CLN that the sender will participate with in the sale ///} function getParticipationAmounts(uint256 _clnAmount, address _token) private view returns (uint256 transferToReserveAmount, uint256 participationAmount) { uint256 clnRaised = issueMap[_token].clnRaised; uint256 reserve = issueMap[_token].reserve; uint256 hardcap = issueMap[_token].hardcap; participationAmount = SafeMath.min256(_clnAmount, hardcap.sub(clnRaised)); if (reserve > clnRaised) { transferToReserveAmount = SafeMath.min256(participationAmount, reserve.sub(clnRaised)); } } /// @dev Returns total number of issuances after filters are applied. /// @dev this function is gas wasteful so do not call this from a state changing transaction /// @param _pending include pending currency issuances. /// @param _started include started currency issuances. /// @param _successful include successful and ended currency issuances. /// @param _failed include failed and ended currency issuances. /// @return Total number of currency issuances after filters are applied. function getIssuanceCount(bool _pending, bool _started, bool _successful, bool _failed) public view returns (uint _count) { for (uint i = 0; i < tokens.length; i++) { IssuanceStruct memory issuance = issueMap[tokens[i]]; if ((_pending && issuance.startTime > now) || (_started && now >= issuance.startTime && issuance.endTime >= now && issuance.clnRaised < issuance.hardcap) || (_successful && issuance.endTime < now && issuance.clnRaised >= issuance.reserve) || (_successful && issuance.endTime >= now && issuance.clnRaised == issuance.hardcap) || (_failed && issuance.endTime < now && issuance.clnRaised < issuance.reserve)) _count += 1; } } /// @dev Returns list of issuance ids (allso the token address of the issuance) in defined range after filters are applied. /// @dev _offset and _limit parameters are intended for pagination /// @dev this function is gas wasteful so do not call this from a state changing transaction /// @param _pending include pending currency issuances. /// @param _started include started currency issuances. /// @param _successful include successful and ended currency issuances. /// @param _failed include failed and ended currency issuances. /// @param _offset index start position of issuance ids array. /// @param _limit maximum number of issuance ids to return. /// @return Returns array of token adresses for issuance. function getIssuanceIds(bool _pending, bool _started, bool _successful, bool _failed, uint _offset, uint _limit) public view returns (address[] _issuanceIds) { require(_limit >= 1); require(_limit <= 100); _issuanceIds = new address[](_limit); uint filteredIssuancesCount = 0; uint retrieveIssuancesCount = 0; for (uint i = 0; i < tokens.length; i++) { IssuanceStruct memory issuance = issueMap[tokens[i]]; if ((_pending && issuance.startTime > now) || (_started && now >= issuance.startTime && issuance.endTime >= now && issuance.clnRaised < issuance.hardcap) || (_successful && issuance.endTime < now && issuance.clnRaised >= issuance.reserve) || (_successful && issuance.endTime >= now && issuance.clnRaised == issuance.hardcap) || (_failed && issuance.endTime < now && issuance.clnRaised < issuance.reserve)) { if (filteredIssuancesCount >= _offset) { _issuanceIds[retrieveIssuancesCount] = tokens[i]; retrieveIssuancesCount += 1; } if (retrieveIssuancesCount == _limit) { return _issuanceIds; } filteredIssuancesCount += 1; } } if (retrieveIssuancesCount < _limit) { address[] memory _issuanceIdsTemp = new address[](retrieveIssuancesCount); for (i = 0; i < retrieveIssuancesCount; i++) { _issuanceIdsTemp[i] = _issuanceIds[i]; } return _issuanceIdsTemp; } } /// @dev Allow the owner to transfer out any accidentally sent ERC20 tokens. /// @param _tokenAddress address The address of the ERC20 contract. /// @param _amount uint256 The amount of tokens to be transferred. function transferAnyERC20Token(address _tokenAddress, uint256 _amount) public onlyOwner returns (bool success) { if (_tokenAddress == clnAddress) { uint256 excessCLN = ERC20(clnAddress).balanceOf(this).sub(totalCLNcustodian); require(excessCLN <= _amount); } if (issueMap[_tokenAddress].hardcap > 0) { require(MarketMaker(currencyMap[_tokenAddress].mmAddress).isOpenForPublic()); } return ERC20(_tokenAddress).transfer(owner, _amount); } }
constructor only reuires the address of the CLN token which must use the ERC20 interface _mmLib address for the deployed market maker elipse contract _clnAddress address for the deployed ERC20 CLN token
function CurrencyFactory(address _mmLib, address _clnAddress) public { require(_mmLib != address(0)); require(_clnAddress != address(0)); mmLibAddress = _mmLib; clnAddress = _clnAddress; }
1,809,689
./partial_match/1/0x6B0B234fB2f380309D47A7E9391E29E9a179395a/sources/src/v0.8/llo-feeds/dev/FeeManager.sol
@inheritdoc IFeeManager
function setNativeSurcharge(uint64 surcharge) external onlyOwner { if (surcharge > PERCENTAGE_SCALAR) revert InvalidSurcharge(); s_nativeSurcharge = surcharge; emit NativeSurchargeUpdated(surcharge); }
3,963,540
pragma solidity ^0.6.11; pragma experimental ABIEncoderV2; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(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 multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b, string memory errorMessage) 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, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(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; } } contract Many { /// @notice EIP-20 token name for this token string public constant name = "Many"; /// @notice EIP-20 token symbol for this token string public constant symbol = "MANY"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public totalSupply = 700_000_000e18; // 700 million Many /// @notice Address which may mint new tokens address public minter; /// @notice The timestamp after which minting may occur uint public mintingAllowedAfter; /// @notice Minimum time between mints uint32 public constant minimumTimeBetweenMints = 1 days * 365; /// @notice Cap on the percentage of totalSupply that can be minted at each mint uint8 public constant mintCap = 2; /// @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when the minter address is changed event MinterChanged(address minter, address newMinter); /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new Many token * @param account The initial account to grant all the tokens * @param minter_ The account with minting ability * @param mintingAllowedAfter_ The timestamp after which minting may occur */ constructor(address account, address minter_, uint mintingAllowedAfter_) public { require(mintingAllowedAfter_ >= block.timestamp, "Many::constructor: minting can only begin after deployment"); balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); minter = minter_; emit MinterChanged(address(0), minter); mintingAllowedAfter = mintingAllowedAfter_; } /** * @notice Change the minter address * @param minter_ The address of the new minter */ function setMinter(address minter_) external { require(msg.sender == minter, "Many::setMinter: only the minter can change the minter address"); emit MinterChanged(minter, minter_); minter = minter_; } /** * @notice Mint new tokens * @param dst The address of the destination account * @param rawAmount The number of tokens to be minted */ function mint(address dst, uint rawAmount) external { require(msg.sender == minter, "Many::mint: only the minter can mint"); require(block.timestamp >= mintingAllowedAfter, "Many::mint: minting not allowed yet"); require(dst != address(0), "Many::mint: cannot transfer to the zero address"); // record the mint mintingAllowedAfter = SafeMath.add(block.timestamp, minimumTimeBetweenMints); // mint the amount uint96 amount = safe96(rawAmount, "Many::mint: amount exceeds 96 bits"); require(amount <= SafeMath.div(SafeMath.mul(totalSupply, mintCap), 100), "Many::mint: exceeded mint cap"); totalSupply = safe96(SafeMath.add(totalSupply, amount), "Many::mint: totalSupply exceeds 96 bits"); // transfer the amount to the recipient balances[dst] = add96(balances[dst], amount, "Many::mint: transfer amount overflows"); emit Transfer(address(0), dst, amount); // move delegates _moveDelegates(address(0), delegates[dst], amount); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @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 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); } else { amount = safe96(rawAmount, "Many::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Many::permit: amount exceeds 96 bits"); } bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Many::permit: invalid signature"); require(signatory == owner, "Many::permit: unauthorized"); require(now <= deadline, "Many::permit: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Many::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Many::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "Many::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Many::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Many::delegateBySig: invalid nonce"); require(now <= expiry, "Many::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 (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Many::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "Many::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "Many::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Many::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Many::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Many::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Many::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "Many::_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 safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
Mint new tokens dst The address of the destination account rawAmount The number of tokens to be minted/ record the mint mint the amount transfer the amount to the recipient move delegates
function mint(address dst, uint rawAmount) external { require(msg.sender == minter, "Many::mint: only the minter can mint"); require(block.timestamp >= mintingAllowedAfter, "Many::mint: minting not allowed yet"); require(dst != address(0), "Many::mint: cannot transfer to the zero address"); mintingAllowedAfter = SafeMath.add(block.timestamp, minimumTimeBetweenMints); uint96 amount = safe96(rawAmount, "Many::mint: amount exceeds 96 bits"); require(amount <= SafeMath.div(SafeMath.mul(totalSupply, mintCap), 100), "Many::mint: exceeded mint cap"); totalSupply = safe96(SafeMath.add(totalSupply, amount), "Many::mint: totalSupply exceeds 96 bits"); balances[dst] = add96(balances[dst], amount, "Many::mint: transfer amount overflows"); emit Transfer(address(0), dst, amount); _moveDelegates(address(0), delegates[dst], amount); }
15,188,269
./full_match/137/0x437EAb839748773066E6161E712D9E39b093eF78/sources/contracts/FrontRunBot.sol
If `self` starts with `needle`, `needle` is removed from the beginning of `self`. Otherwise, `self` is unmodified. self The slice to operate on. needle The slice to search for. return `self`/
function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; }
4,717,289
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "./interfaces/IPlus.sol"; /** * @title Plus token base contract. * * Plus token is a value pegged ERC20 token which provides global interest to all holders. * It can be categorized as single plus token and composite plus token: * * Single plus token is backed by one ERC20 token and targeted at yield generation. * Composite plus token is backed by a basket of ERC20 token and targeted at better basket management. */ abstract contract Plus is ERC20Upgradeable, IPlus { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; /** * @dev Emitted each time the share of a user is updated. */ event UserShareUpdated(address indexed account, uint256 oldShare, uint256 newShare, uint256 totalShares); event Rebased(uint256 oldIndex, uint256 newIndex, uint256 totalUnderlying); event Donated(address indexed account, uint256 amount, uint256 share); event GovernanceUpdated(address indexed oldGovernance, address indexed newGovernance); event StrategistUpdated(address indexed strategist, bool allowed); event TreasuryUpdated(address indexed oldTreasury, address indexed newTreasury); event RedeemFeeUpdated(uint256 oldFee, uint256 newFee); event MintPausedUpdated(address indexed token, bool paused); uint256 public constant MAX_PERCENT = 10000; // 0.01% uint256 public constant WAD = 1e18; /** * @dev Struct to represent a rebase hook. */ struct Transaction { bool enabled; address destination; bytes data; } // Rebase hooks Transaction[] public transactions; uint256 public totalShares; mapping(address => uint256) public userShare; // The exchange rate between total shares and BTC+ total supply. Express in WAD. // It's equal to the amount of plus token per share. // Note: The index will never decrease! uint256 public index; address public override governance; mapping(address => bool) public override strategists; address public override treasury; // Governance parameters uint256 public redeemFee; // EIP 2612: Permit // Credit: https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; /** * @dev Initializes the plus token contract. */ function __PlusToken__init(string memory _name, string memory _symbol) internal initializer { __ERC20_init(_name, _symbol); index = WAD; governance = msg.sender; treasury = msg.sender; uint _chainId; assembly { _chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(_name)), keccak256(bytes('1')), _chainId, address(this) ) ); } function _checkGovernance() internal view { require(msg.sender == governance, "not governance"); } modifier onlyGovernance() { _checkGovernance(); _; } function _checkStrategist() internal view { require(msg.sender == governance || strategists[msg.sender], "not strategist"); } modifier onlyStrategist { _checkStrategist(); _; } /** * @dev Returns the total value of the plus token in terms of the peg value in WAD. * All underlying token amounts have been scaled to 18 decimals, then expressed in WAD. */ function _totalUnderlyingInWad() internal view virtual returns (uint256); /** * @dev Returns the total value of the plus token in terms of the peg value. * For single plus, it's equal to its total supply. * For composite plus, it's equal to the total amount of single plus tokens in its basket. */ function totalUnderlying() external view override returns (uint256) { return _totalUnderlyingInWad().div(WAD); } /** * @dev Returns the total supply of plus token. See {IERC20Updateable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return totalShares.mul(index).div(WAD); } /** * @dev Returns the balance of plus token for the account. See {IERC20Updateable-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return userShare[account].mul(index).div(WAD); } /** * @dev Returns the current liquidity ratio of the plus token in WAD. */ function liquidityRatio() public view returns (uint256) { uint256 _totalSupply = totalSupply(); return _totalSupply == 0 ? WAD : _totalUnderlyingInWad().div(_totalSupply); } /** * @dev Accrues interest to increase index. */ function rebase() public override { uint256 _totalShares = totalShares; if (_totalShares == 0) return; // underlying is in WAD, and index is also in WAD uint256 _underlying = _totalUnderlyingInWad(); uint256 _oldIndex = index; uint256 _newIndex = _underlying.div(_totalShares); // _newIndex - oldIndex is the amount of interest generated for each share // _oldIndex might be larger than _newIndex in a short period of time. In this period, the liquidity ratio is smaller than 1. if (_newIndex > _oldIndex) { // Index can never decrease index = _newIndex; for (uint256 i = 0; i < transactions.length; i++) { Transaction storage transaction = transactions[i]; if (transaction.enabled) { (bool success, ) = transaction.destination.call(transaction.data); require(success, "rebase hook failed"); } } // In this event we are returning underlyiing() which can be used to compute the actual interest generated. emit Rebased(_oldIndex, _newIndex, _underlying.div(WAD)); } } /** * @dev Allows anyone to donate their plus asset to all other holders. * @param _amount Amount of plus token to donate. */ function donate(uint256 _amount) public override { // Rebase first to make index up-to-date rebase(); // Special handling of -1 is required here in order to fully donate all shares, since interest // will be accrued between the donate transaction is signed and mined. uint256 _share; if (_amount == uint256(int256(-1))) { _share = userShare[msg.sender]; _amount = _share.mul(index).div(WAD); } else { _share = _amount.mul(WAD).div(index); } uint256 _oldShare = userShare[msg.sender]; uint256 _newShare = _oldShare.sub(_share, "insufficient share"); uint256 _newTotalShares = totalShares.sub(_share); userShare[msg.sender] = _newShare; totalShares = _newTotalShares; emit UserShareUpdated(msg.sender, _oldShare, _newShare, _newTotalShares); emit Donated(msg.sender, _amount, _share); } /** * @dev Moves tokens `amount` from `sender` to `recipient`. */ function _transfer(address _sender, address _recipient, uint256 _amount) internal virtual override { // Rebase first to make index up-to-date rebase(); uint256 _shareToTransfer = _amount.mul(WAD).div(index); uint256 _oldSenderShare = userShare[_sender]; uint256 _newSenderShare = _oldSenderShare.sub(_shareToTransfer, "insufficient share"); uint256 _oldRecipientShare = userShare[_recipient]; uint256 _newRecipientShare = _oldRecipientShare.add(_shareToTransfer); uint256 _totalShares = totalShares; userShare[_sender] = _newSenderShare; userShare[_recipient] = _newRecipientShare; emit UserShareUpdated(_sender, _oldSenderShare, _newSenderShare, _totalShares); emit UserShareUpdated(_recipient, _oldRecipientShare, _newRecipientShare, _totalShares); } /** * @dev Gassless approve. */ function permit(address _owner, address _spender, uint256 _value, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s) external { require(_deadline >= block.timestamp, 'expired'); bytes32 _digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, nonces[_owner]++, _deadline)) ) ); address _recoveredAddress = ecrecover(_digest, _v, _r, _s); require(_recoveredAddress != address(0) && _recoveredAddress == _owner, 'invalid signature'); _approve(_owner, _spender, _value); } /********************************************* * * Governance methods * **********************************************/ /** * @dev Updates governance. Only governance can update governance. */ function setGovernance(address _governance) external onlyGovernance { address _oldGovernance = governance; governance = _governance; emit GovernanceUpdated(_oldGovernance, _governance); } /** * @dev Updates strategist. Both governance and strategists can update strategist. */ function setStrategist(address _strategist, bool _allowed) external onlyStrategist { require(_strategist != address(0x0), "strategist not set"); strategists[_strategist] = _allowed; emit StrategistUpdated(_strategist, _allowed); } /** * @dev Updates the treasury. Only governance can update treasury. */ function setTreasury(address _treasury) external onlyGovernance { require(_treasury != address(0x0), "treasury not set"); address _oldTreasury = treasury; treasury = _treasury; emit TreasuryUpdated(_oldTreasury, _treasury); } /** * @dev Updates the redeem fee. Only governance can update redeem fee. */ function setRedeemFee(uint256 _redeemFee) external onlyGovernance { require(_redeemFee <= MAX_PERCENT, "redeem fee too big"); uint256 _oldFee = redeemFee; redeemFee = _redeemFee; emit RedeemFeeUpdated(_oldFee, _redeemFee); } /** * @dev Used to salvage any ETH deposited to BTC+ contract by mistake. Only strategist can salvage ETH. * The salvaged ETH is transferred to treasury for futher operation. */ function salvage() external onlyStrategist { uint256 _amount = address(this).balance; address payable _target = payable(treasury); (bool _success, ) = _target.call{value: _amount}(new bytes(0)); require(_success, 'ETH salvage failed'); } /** * @dev Checks whether a token can be salvaged via salvageToken(). * @param _token Token to check salvageability. */ function _salvageable(address _token) internal view virtual returns (bool); /** * @dev Used to salvage any token deposited to plus contract by mistake. Only strategist can salvage token. * The salvaged token is transferred to treasury for futhuer operation. * @param _token Address of the token to salvage. */ function salvageToken(address _token) external onlyStrategist { require(_token != address(0x0), "token not set"); require(_salvageable(_token), "cannot salvage"); IERC20Upgradeable _target = IERC20Upgradeable(_token); _target.safeTransfer(treasury, _target.balanceOf(address(this))); } /** * @dev Add a new rebase hook. * @param _destination Destination contract for the reabase hook. * @param _data Transaction payload for the rebase hook. */ function addTransaction(address _destination, bytes memory _data) external onlyGovernance { transactions.push(Transaction({enabled: true, destination: _destination, data: _data})); } /** * @dev Remove a rebase hook. * @param _index Index of the transaction to remove. */ function removeTransaction(uint256 _index) external onlyGovernance { require(_index < transactions.length, "index out of bounds"); if (_index < transactions.length - 1) { transactions[_index] = transactions[transactions.length - 1]; } transactions.pop(); } /** * @dev Updates an existing rebase hook transaction. * @param _index Index of transaction. Transaction ordering may have changed since adding. * @param _enabled True for enabled, false for disabled. */ function updateTransaction(uint256 _index, bool _enabled) external onlyGovernance { require(_index < transactions.length, "index must be in range of stored tx list"); transactions[_index].enabled = _enabled; } /** * @dev Returns the number of rebase hook transactions. */ function transactionSize() external view returns (uint256) { return transactions.length; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "./interfaces/ISinglePlus.sol"; import "./Plus.sol"; /** * @title Single plus token. * * A single plus token wraps an underlying ERC20 token, typically a yield token, * into a value peg token. */ contract SinglePlus is ISinglePlus, Plus, ReentrancyGuardUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; event Minted(address indexed user, uint256 amount, uint256 mintShare, uint256 mintAmount); event Redeemed(address indexed user, uint256 amount, uint256 redeemShare, uint256 redeemAmount, uint256 fee); event Harvested(address indexed token, uint256 amount, uint256 feeAmount); event PerformanceFeeUpdated(uint256 oldPerformanceFee, uint256 newPerformanceFee); // Underlying token of the single plus toke. Typically a yield token and not value peg. address public override token; // Whether minting is paused for the single plus token. bool public mintPaused; uint256 public performanceFee; uint256 public constant PERCENT_MAX = 10000; // 0.01% /** * @dev Initializes the single plus contract. * @param _token Underlying token of the single plus. * @param _nameOverride If empty, the single plus name will be `token_name Plus` * @param _symbolOverride If empty. the single plus name will be `token_symbol+` */ function initialize(address _token, string memory _nameOverride, string memory _symbolOverride) public initializer { token = _token; string memory _name = _nameOverride; string memory _symbol = _symbolOverride; if (bytes(_name).length == 0) { _name = string(abi.encodePacked(ERC20Upgradeable(_token).name(), " Plus")); } if (bytes(_symbol).length == 0) { _symbol = string(abi.encodePacked(ERC20Upgradeable(_token).symbol(), "+")); } __PlusToken__init(_name, _symbol); __ReentrancyGuard_init(); } /** * @dev Returns the amount of single plus tokens minted with the underlying token provided. * @dev _amounts Amount of underlying token used to mint the single plus token. */ function getMintAmount(uint256 _amount) external view returns(uint256) { // Conversion rate is the amount of single plus token per underlying token, in WAD. return _amount.mul(_conversionRate()).div(WAD); } /** * @dev Mints the single plus token with the underlying token. * @dev _amount Amount of the underlying token used to mint single plus token. */ function mint(uint256 _amount) external override nonReentrant { require(_amount > 0, "zero amount"); require(!mintPaused, "mint paused"); // Rebase first to make index up-to-date rebase(); // Transfers the underlying token in. IERC20Upgradeable(token).safeTransferFrom(msg.sender, address(this), _amount); // Conversion rate is the amount of single plus token per underlying token, in WAD. uint256 _newAmount = _amount.mul(_conversionRate()).div(WAD); // Index is in WAD uint256 _share = _newAmount.mul(WAD).div(index); uint256 _oldShare = userShare[msg.sender]; uint256 _newShare = _oldShare.add(_share); uint256 _totalShares = totalShares.add(_share); totalShares = _totalShares; userShare[msg.sender] = _newShare; emit UserShareUpdated(msg.sender, _oldShare, _newShare, _totalShares); emit Minted(msg.sender, _amount, _share, _newAmount); } /** * @dev Returns the amount of tokens received in redeeming the single plus token. * @param _amount Amounf of single plus to redeem. * @return Amount of underlying token received as well as fee collected. */ function getRedeemAmount(uint256 _amount) external view returns (uint256, uint256) { // Withdraw ratio = min(liquidity ratio, 1 - redeem fee) // Liquidity ratio is in WAD and redeem fee is in 0.01% uint256 _withdrawAmount1 = _amount.mul(liquidityRatio()).div(WAD); uint256 _withdrawAmount2 = _amount.mul(MAX_PERCENT - redeemFee).div(MAX_PERCENT); uint256 _withdrawAmount = MathUpgradeable.min(_withdrawAmount1, _withdrawAmount2); uint256 _fee = _amount.sub(_withdrawAmount); // Conversion rate is in WAD uint256 _underlyingAmount = _withdrawAmount.mul(WAD).div(_conversionRate()); // Note: Fee is in plus token(18 decimals) but the received amount is in underlying token! return (_underlyingAmount, _fee); } /** * @dev Redeems the single plus token. * @param _amount Amount of single plus token to redeem. -1 means redeeming all shares. */ function redeem(uint256 _amount) external override nonReentrant { require(_amount > 0, "zero amount"); // Rebase first to make index up-to-date rebase(); // Special handling of -1 is required here in order to fully redeem all shares, since interest // will be accrued between the redeem transaction is signed and mined. uint256 _share; if (_amount == uint256(int256(-1))) { _share = userShare[msg.sender]; _amount = _share.mul(index).div(WAD); } else { _share = _amount.mul(WAD).div(index); } // Withdraw ratio = min(liquidity ratio, 1 - redeem fee) // Liquidity ratio is in WAD and redeem fee is in 0.01% uint256 _withdrawAmount1 = _amount.mul(liquidityRatio()).div(WAD); uint256 _withdrawAmount2 = _amount.mul(MAX_PERCENT - redeemFee).div(MAX_PERCENT); uint256 _withdrawAmount = MathUpgradeable.min(_withdrawAmount1, _withdrawAmount2); uint256 _fee = _amount.sub(_withdrawAmount); // Conversion rate is in WAD uint256 _underlyingAmount = _withdrawAmount.mul(WAD).div(_conversionRate()); _withdraw(msg.sender, _underlyingAmount); // Updates the balance uint256 _oldShare = userShare[msg.sender]; uint256 _newShare = _oldShare.sub(_share); totalShares = totalShares.sub(_share); userShare[msg.sender] = _newShare; emit UserShareUpdated(msg.sender, _oldShare, _newShare, totalShares); emit Redeemed(msg.sender, _underlyingAmount, _share, _amount, _fee); } /** * @dev Updates the mint paused state of the underlying token. * @param _paused Whether minting with that token is paused. */ function setMintPaused(bool _paused) external onlyStrategist { require(mintPaused != _paused, "no change"); mintPaused = _paused; emit MintPausedUpdated(token, _paused); } /** * @dev Updates the performance fee. Only governance can update the performance fee. */ function setPerformanceFee(uint256 _performanceFee) public onlyGovernance { require(_performanceFee <= PERCENT_MAX, "overflow"); uint256 oldPerformanceFee = performanceFee; performanceFee = _performanceFee; emit PerformanceFeeUpdated(oldPerformanceFee, _performanceFee); } /** * @dev Retrive the underlying assets from the investment. */ function divest() public virtual override {} /** * @dev Returns the amount that can be invested now. The invested token * does not have to be the underlying token. * investable > 0 means it's time to call invest. */ function investable() public view virtual override returns (uint256) { return 0; } /** * @dev Invest the underlying assets for additional yield. */ function invest() public virtual override {} /** * @dev Returns the amount of reward that could be harvested now. * harvestable > 0 means it's time to call harvest. */ function harvestable() public view virtual override returns (uint256) { return 0; } /** * @dev Harvest additional yield from the investment. */ function harvest() public virtual override {} /** * @dev Checks whether a token can be salvaged via salvageToken(). * @param _token Token to check salvageability. */ function _salvageable(address _token) internal view virtual override returns (bool) { // For single plus, the only token that cannot salvage is the underlying token! return _token != token; } /** * @dev Returns the amount of single plus token is worth for one underlying token, expressed in WAD. * The default implmentation assumes that the single plus and underlying tokens are both peg. */ function _conversionRate() internal view virtual returns (uint256) { // 36 since the decimals for plus token is always 18, and conversion rate is in WAD. return uint256(10) ** (36 - ERC20Upgradeable(token).decimals()); } /** * @dev Returns the total value of the underlying token in terms of the peg value, scaled to 18 decimals * and expressed in WAD. */ function _totalUnderlyingInWad() internal view virtual override returns (uint256) { uint256 _balance = IERC20Upgradeable(token).balanceOf(address(this)); // Conversion rate is the amount of single plus token per underlying token, in WAD. return _balance.mul(_conversionRate()); } /** * @dev Withdraws underlying tokens. * @param _receiver Address to receive the token withdraw. * @param _amount Amount of underlying token withdraw. */ function _withdraw(address _receiver, uint256 _amount) internal virtual { IERC20Upgradeable(token).safeTransfer(_receiver, _amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; /** * @title Interface for plus token. * Plus token is a value pegged ERC20 token which provides global interest to all holders. */ interface IPlus { /** * @dev Returns the governance address. */ function governance() external view returns (address); /** * @dev Returns whether the account is a strategist. */ function strategists(address _account) external view returns (bool); /** * @dev Returns the treasury address. */ function treasury() external view returns (address); /** * @dev Accrues interest to increase index. */ function rebase() external; /** * @dev Returns the total value of the plus token in terms of the peg value. */ function totalUnderlying() external view returns (uint256); /** * @dev Allows anyone to donate their plus asset to all other holders. * @param _amount Amount of plus token to donate. */ function donate(uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "./IPlus.sol"; /** * @title Interface for single plus token. * Single plus token is backed by one ERC20 token and targeted at yield generation. */ interface ISinglePlus is IPlus { /** * @dev Returns the address of the underlying token. */ function token() external view returns (address); /** * @dev Retrive the underlying assets from the investment. */ function divest() external; /** * @dev Returns the amount that can be invested now. The invested token * does not have to be the underlying token. * investable > 0 means it's time to call invest. */ function investable() external view returns (uint256); /** * @dev Invest the underlying assets for additional yield. */ function invest() external; /** * @dev Returns the amount of reward that could be harvested now. * harvestable > 0 means it's time to call harvest. */ function harvestable() external view returns (uint256); /** * @dev Harvest additional yield from the investment. */ function harvest() external; /** * @dev Mints the single plus token with the underlying token. * @dev _amount Amount of the underlying token used to mint single plus token. */ function mint(uint256 _amount) external; /** * @dev Redeems the single plus token. * @param _amount Amount of single plus token to redeem. -1 means redeeming all shares. */ function redeem(uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; /** * @notice Interface for Uniswap's router. */ interface IUniswapRouter { function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; /** * @dev Interface for Vesper Pool Rewards. */ interface IPoolRewards { function claimReward(address) external; function claimable(address) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; /** * @dev Interface for Vesper Pool. */ interface IVPool { function getPricePerShare() external view returns (uint256); function deposit(uint256 _amount) external; function withdraw(uint256 _shares) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "../../SinglePlus.sol"; import "../../interfaces/vesper/IVPool.sol"; import "../../interfaces/vesper/IPoolRewards.sol"; import "../../interfaces/uniswap/IUniswapRouter.sol"; /** * @dev Single plus for Vesper WBTC. */ contract VesperWBTCPlus is SinglePlus { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; address public constant VESPER_WBTC = address(0x4B2e76EbBc9f2923d83F5FBDe695D8733db1a17B); address public constant VESPER_WBTC_REWARDS = address(0x479A8666Ad530af3054209Db74F3C74eCd295f8D); address public constant WBTC = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); address public constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address public constant VESPER = address(0x1b40183EFB4Dd766f11bDa7A7c3AD8982e998421); address public constant UNISWAP = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Uniswap RouterV2 /** * @dev Initializes vWBTC+. */ function initialize() public initializer { SinglePlus.initialize(VESPER_WBTC, "", ""); } /** * @dev Returns the amount of reward that could be harvested now. * harvestable > 0 means it's time to call harvest. */ function harvestable() public view virtual override returns (uint256) { return IPoolRewards(VESPER_WBTC_REWARDS).claimable(address(this)); } /** * @dev Harvest additional yield from the investment. * Only governance or strategist can call this function. */ function harvest() public virtual override onlyStrategist { // Harvest from Vesper Pool Rewards IPoolRewards(VESPER_WBTC_REWARDS).claimReward(address(this)); uint256 _vsp = IERC20Upgradeable(VESPER).balanceOf(address(this)); // Uniswap: VESPER --> WETH --> WBTC if (_vsp > 0) { IERC20Upgradeable(VESPER).safeApprove(UNISWAP, 0); IERC20Upgradeable(VESPER).safeApprove(UNISWAP, _vsp); address[] memory _path = new address[](3); _path[0] = VESPER; _path[1] = WETH; _path[2] = WBTC; IUniswapRouter(UNISWAP).swapExactTokensForTokens(_vsp, uint256(0), _path, address(this), block.timestamp.add(1800)); } // Vesper: WBTC --> vWBTC uint256 _wbtc = IERC20Upgradeable(WBTC).balanceOf(address(this)); if (_wbtc == 0) return; // If there is performance fee, charged in WBTC uint256 _fee = 0; if (performanceFee > 0) { _fee = _wbtc.mul(performanceFee).div(PERCENT_MAX); IERC20Upgradeable(WBTC).safeTransfer(treasury, _fee); _wbtc = _wbtc.sub(_fee); } IERC20Upgradeable(WBTC).safeApprove(VESPER_WBTC, 0); IERC20Upgradeable(WBTC).safeApprove(VESPER_WBTC, _wbtc); IVPool(VESPER_WBTC).deposit(_wbtc); // Also it's a good time to rebase! rebase(); emit Harvested(VESPER_WBTC, _wbtc, _fee); } /** * @dev Checks whether a token can be salvaged via salvageToken(). The following two * tokens are not salvageable: * 1) vWBTC * 2) VESPER * @param _token Token to check salvageability. */ function _salvageable(address _token) internal view virtual override returns (bool) { return _token != VESPER_WBTC && _token != VESPER; } /** * @dev Returns the amount of single plus token is worth for one underlying token, expressed in WAD. */ function _conversionRate() internal view virtual override returns (uint256) { // The share price is in WAD. return IVPool(VESPER_WBTC).getPricePerShare(); } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {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 || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @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 this function is * overloaded; * * 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 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using 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) + 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"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity ^0.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. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
Returns the amount of single plus token is worth for one underlying token, expressed in WAD./ The share price is in WAD.
function _conversionRate() internal view virtual override returns (uint256) { return IVPool(VESPER_WBTC).getPricePerShare(); }
435,282
pragma solidity ^0.6.1; pragma experimental ABIEncoderV2; import './HealthToken.sol'; contract HealthCare { HealthToken token; address public owner; constructor (address _token) public { token = HealthToken(_token); owner = msg.sender; } struct DATA { string file; string prescription; } struct PatientData{ address Patient; string[] data; } mapping(address => bool) public isDoc; // doctor address[] public allDoctors; mapping(address => bool) public isPatient; // patient address[] public allPatients; mapping(address => uint256) public docFee; // doctor while registering doctor mapping(address => string[]) public patientData; // patient addFile mapping(address => DATA[]) public prescription; // patient when doctor add prescription mapping(address=> address[]) public docPatientList; // doctor and patient list while sending file mapping(address => mapping(address => bool)) public docPatient; // above bool mapping(address => mapping(address => string[])) public docData; // above sending file // patient function event PatientAdded( address Patient ); function addPatient() public{ // msg.sender is patient require(isDoc[msg.sender] == false, "Address is Doctor"); require(isPatient[msg.sender] == false, "Address is already patient"); isPatient[msg.sender] = true; allPatients.push(msg.sender); emit PatientAdded(msg.sender); } function getAllPatients() public view returns(address[] memory){ return allPatients; } function allPatientsData() public view returns(string[] memory){ // msg.sender is patient return patientData[msg.sender]; } function allPrescriptions() public view returns(DATA[] memory){ // msg.sender is patient return prescription[msg.sender]; } event DoctorAdded( address Doctor, uint256 Fee ); function addDoctor(uint256 _fees) public{ // msg.sender is doctor require(isDoc[msg.sender] == false, "Address is already Doctor"); require(isPatient[msg.sender] == false, "Address is patient"); allDoctors.push(msg.sender); isDoc[msg.sender] = true; docFee[msg.sender] = _fees; emit DoctorAdded(msg.sender, _fees); } event FeeChanged( address Doctor, uint256 Fee ); function changeFee(uint256 _fees) public{ require(isDoc[msg.sender] == false, "Address is already Doctor"); require(isPatient[msg.sender] == false, "Address is patient"); docFee[msg.sender] = _fees; emit FeeChanged(msg.sender, _fees); } function getAllDoctors() public view returns(address[] memory){ return allDoctors; } function addFile(string memory _fileHash) public{ // msg.sender is patient require(isPatient[msg.sender] == true, "Address is not patient"); patientData[msg.sender].push(_fileHash); } function sendFile(address _doc, string memory _fileHash, uint256 _amount) public { // msg.sender is patient require(isPatient[msg.sender] == true, "You are not patient"); require(isDoc[_doc] == true, "Invalid Doctor"); require(_amount == docFee[_doc], "Insufficient fee sent"); token.approveContract(address(this), msg.sender, _amount); token.transferFrom(msg.sender, address(this), _amount); docPatientList[_doc].push(msg.sender); docPatient[_doc][msg.sender] = true; docData[_doc][msg.sender].push(_fileHash); } // doctor's function function sendPrescription(address _patient, string memory _filehash, string memory _prescription) public { // msg.sender is doctor require(isDoc[msg.sender] == true, "You are not Doctor"); require(isPatient[_patient] == true, "Invalid patient"); require(docPatient[msg.sender][_patient]==true, "Not your patient"); DATA memory d; d.file = _filehash; d.prescription = _prescription; prescription[_patient].push(d); token.transfer(msg.sender, docFee[msg.sender]); } address[] pat; string[][] da; function allPatient() public returns(address[] memory, string[][] memory){ // msg.sender is doctor address[] memory p; pat = p; string[][] memory s; da = s; for(uint i = 0; i < docPatientList[msg.sender].length; i++){ pat.push(docPatientList[msg.sender][i]); da.push(docData[msg.sender][docPatientList[msg.sender][i]]); } return(pat, da); } }
msg.sender is patient
function addPatient() public{ require(isDoc[msg.sender] == false, "Address is Doctor"); require(isPatient[msg.sender] == false, "Address is already patient"); isPatient[msg.sender] = true; allPatients.push(msg.sender); emit PatientAdded(msg.sender); }
15,860,255
pragma solidity ^0.4.24; import "./SafeMathLib.sol"; /** * @title FeesLib * @dev Library for managing fees on any contract, it handles fees percentages with minimum and maximum amount, * on eth blockchain having parts per X as percentage storing the two parts of the fraction. */ library FeesLib { using SafeMathLib for uint; // fee as parts per X units, e.g. 2 per 1000 = 0.2% struct FeeStorage { // e.g. 0.1% => [1] per 1000, this is 1 uint parts_Fee; // e.g. 0.1% => 1 per [1000], this is 1000 uint perX_Fee; // minimum fee in tokens that are the minimum unit number in smart contract uint min_Fee; // maximum fee in tokens that are the maximum unit number in smart contract, if zero is disabled uint max_Fee; // fees enabled/disabled bool feesEnabled; } /** * @dev initTransferFees, given all required parameters in the same order as they are declared in the FeeStorage struct. * @param _parts_Fee Parts component of the fee percentage * @param _perX_Fee Per X component of the fee percentage * @param _min_Fee Mininmum amount of tokens for the fee * @param _max_Fee Maximum amount of tokens for the fee, zero means no maximum * @param _feesEnabled Are fees enables? * @return bool */ function init(FeeStorage storage self, uint _parts_Fee, uint _perX_Fee, uint _min_Fee, uint _max_Fee, bool _feesEnabled) internal returns (bool) { if (self.parts_Fee != _parts_Fee) self.parts_Fee = _parts_Fee; if (self.perX_Fee != _perX_Fee) self.perX_Fee = _perX_Fee; if (self.min_Fee != _min_Fee) self.min_Fee = _min_Fee; if (self.max_Fee != _max_Fee) self.max_Fee = _max_Fee; if (self.feesEnabled != _feesEnabled) self.feesEnabled = _feesEnabled; return true; } /** * @dev CalculateFee, given token amount, calculate transfer fee in units/tokens that are cents or pennies * @param tokens Tokens amount to calculate fees for * @return uint */ function calculateFee(FeeStorage storage self, uint tokens) internal view returns (uint fee) { if (!self.feesEnabled) return 0; fee = tokens.percent(self.parts_Fee, self.perX_Fee); //filter fee to minimum amount of tokens/pennies allowed if (self.feesEnabled && fee < self.min_Fee) { fee = self.min_Fee; } //filter fee to maximum amount of tokens/pennies allowed if greater than zero if (self.feesEnabled && self.max_Fee > 0 && fee > self.max_Fee) { fee = self.max_Fee; } } /** * @dev Get minimum fee tokens/pennies/cents * @return uint */ function getMinFee(FeeStorage storage self) internal view returns (uint) { return self.min_Fee; } /** * @dev Get maximum fee tokens/pennies/cents * @return uint */ function getMaxFee(FeeStorage storage self) internal view returns (uint) { return self.max_Fee; } /** * @dev Change minimum fee tokens/pennies/cents * @param newMinFee Minimum amount of tokens to be set as minimum * @return bool */ function setMinFee(FeeStorage storage self, uint newMinFee) internal returns (bool) { if (self.min_Fee != newMinFee) { self.min_Fee = newMinFee; return true; } return false; } /** * @dev Change maximum fee tokens/pennies/cents * @param newMaxFee Maximum amount of tokens to be set as maximum * @return bool */ function setMaxFee(FeeStorage storage self, uint newMaxFee) internal returns (bool) { if (self.max_Fee != newMaxFee) { self.max_Fee = newMaxFee; return true; } return false; } /** * @dev Enable/Disable fees * @return bool */ function enableFees(FeeStorage storage self, bool enable) internal returns (bool) { if (self.feesEnabled != enable) { self.feesEnabled = enable; return true; } return false; } /** * @dev Set fees as parts per X units * @param _parts_Fee Parts component of the fee percentage * @param _perX_Fee Per X component of the fee percentage * @return bool */ function setFees(FeeStorage storage self, uint _parts_Fee, uint _perX_Fee) internal returns (bool) { // at least one factor has to be different for change to be allowed, what's the point of setting the same values anyway? require(_parts_Fee != self.parts_Fee || _perX_Fee != self.perX_Fee, "FeesLib._setFees: required _parts_Fee != self.parts_Fee || _perX_Fee != self.perX_Fee"); require(_perX_Fee > 0, "FeesLib._setFees: required _perX_Fee > 0"); require(_parts_Fee < _perX_Fee, "FeesLib._setFees: required _parts_Fee < _perX_Fee"); self.parts_Fee = _parts_Fee; self.perX_Fee = _perX_Fee; return true; } }
Change maximum fee tokens/pennies/cents newMaxFee Maximum amount of tokens to be set as maximum return bool/
function setMaxFee(FeeStorage storage self, uint newMaxFee) internal returns (bool) { if (self.max_Fee != newMaxFee) { self.max_Fee = newMaxFee; return true; } return false; }
2,507,263
./full_match/1/0xf1a9E13c546FCeB6BCCa4cb221d318fc68584471/sources/contracts/LockV2.sol
Function to release tokens after the lock-up period update the initialReleaseAmount state in case the beneficiary did not release it yet
function releaseTokens() external nonReentrant returns (bool) { require(msg.sender == beneficiary, "You aren't the beneficiary"); require(vesting.isInitialized, "Vesting period not initialized"); require(block.timestamp >= vesting.releaseTime, "Tokens are still locked."); require(vesting.releasedTokens < vesting.totalTokens, "All tokens already released"); uint256 amountToRelease = vesting.totalTokens - vesting.releasedTokens; vesting.releasedTokens += amountToRelease; vesting.initialReleaseAmount = 0; IERC20(tokenContract).transfer(beneficiary, amountToRelease); return true; }
3,081,500
./partial_match/42220/0xe55C3eb4a04F93c3302A5d8058348157561BF5ca/sources/home/obernardovieira/Documentos/GitHub/impact-market/smart-contracts/contracts/Community.sol
Allow community managers to lock beneficiaries./
function lockBeneficiary(address _account) external onlyManagers { require(beneficiaries[_account] == BeneficiaryState.Valid, "NOT_YET"); beneficiaries[_account] = BeneficiaryState.Locked; emit BeneficiaryLocked(_account); }
3,497,800
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // 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); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/math/Math.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/proxy/Initializable.sol // 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 !Address.isContract(address(this)); } } // File: contracts/governance/Governable.sol pragma solidity ^0.6.0; /// @title Governable /// @dev Governable is contract for governance role. Why don't use an AccessControl? Because the only one member exists contract Governable { /// @notice The government address getter address public governance; /// @notice Simple contstructor that initialize the governance address constructor() public { governance = msg.sender; } /// @dev Prevents other msg.sender than governance address modifier onlyGovernance { require(msg.sender == governance, "!governance"); _; } /// @notice Setter for governance address /// @param _newGovernance New value function setGovernance(address _newGovernance) public onlyGovernance { governance = _newGovernance; } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/governance/LPTokenWrapper.sol pragma solidity ^0.6.0; /// @title LPTokenWrapper /// @notice Used as utility to simplify governance token operations in Governance contract contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; /// @notice Wrapped governance token IERC20 public governanceToken; /// @notice Current balances mapping(address => uint256) private _balances; /// @notice Current total supply uint256 private _totalSupply; /// @notice Standard totalSupply method function totalSupply() public view returns(uint256) { return _totalSupply; } /// @notice Standard balanceOf method /// @param _account User address function balanceOf(address _account) public view returns(uint256) { return _balances[_account]; } /// @notice Standard deposit (stake) method /// @param _amount Amount governance tokens to stake (deposit) function stake(uint256 _amount) public virtual { _totalSupply = _totalSupply.add(_amount); _balances[msg.sender] = _balances[msg.sender].add(_amount); governanceToken.safeTransferFrom(msg.sender, address(this), _amount); } /// @notice Standard withdraw method /// @param _amount Amount governance tokens to withdraw function withdraw(uint256 _amount) public virtual { _totalSupply = _totalSupply.sub(_amount); _balances[msg.sender] = _balances[msg.sender].sub(_amount); governanceToken.transfer(msg.sender, _amount); } /// @notice Simple governance setter /// @param _newGovernanceToken New value function _setGovernanceToken(address _newGovernanceToken) internal { governanceToken = IERC20(_newGovernanceToken); } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view 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: contracts/interfaces/IRewardDistributionRecipient.sol pragma solidity ^0.6.0; abstract contract IRewardDistributionRecipient is Ownable { address public rewardDistribution; function notifyRewardAmount(uint256 reward) external virtual; modifier onlyRewardDistribution { require(msg.sender == rewardDistribution, "!rewardDistribution"); _; } function setRewardDistribution(address _rewardDistribution) public onlyOwner { rewardDistribution = _rewardDistribution; } } // File: contracts/interfaces/IExecutor.sol pragma solidity ^0.6.0; interface IExecutor { function execute(uint256 _id, uint256 _for, uint256 _against, uint256 _quorum) external; } // File: contracts/governance/Governance.sol pragma solidity ^0.6.0; /// @title Governance /// @notice /// @dev contract Governance is Governable, IRewardDistributionRecipient, LPTokenWrapper, Initializable { /// @notice The Proposal struct used to represent vote process. struct Proposal { uint256 id; // Unique ID of the proposal (here Counter lib can be used) address proposer; // An address who created the proposal mapping(address => uint256) forVotes; // Percentage (in base points) of governance token (votes) of 'for' side mapping(address => uint256) againstVotes; // Percentage (in base points) of governance token (votes) of 'against' side uint256 totalForVotes; // Total amount of governance token (votes) in side 'for' uint256 totalAgainstVotes; // Total amount of governance token (votes) in side 'against' uint256 start; // Block start uint256 end; // Start + period address executor; // Custom contract which can execute changes regarding to voting process end string hash; // An IPFS hash of the proposal document uint256 totalVotesAvailable; // Total amount votes that are not in voting process uint256 quorum; // Current quorum (in base points) uint256 quorumRequired; // Quorum to end the voting process bool open; // Proposal status } /// @notice Emits when new proposal is created /// @param _id ID of the proposal /// @param _creator Address of proposal creator /// @param _start Voting process start timestamp /// @param _duration Seconds during which the voting process occurs /// @param _executor Address of the the executor contract event NewProposal(uint256 _id, address _creator, uint256 _start, uint256 _duration, address _executor); /// @notice Emits when someone votes in proposal /// @param _id ID of the proposal /// @param _voter Voter address /// @param _vote 'For' or 'Against' vote type /// @param _weight Vote weight in percents (in base points) event Vote(uint256 indexed _id, address indexed _voter, bool _vote, uint256 _weight); /// @notice Emits when voting process finished /// @param _id ID of the proposal /// @param _for 'For' votes percentage in base points /// @param _against 'Against' votes percentage in base points /// @param _quorumReached Is quorum percents are above or equal to required quorum? (bool) event ProposalFinished(uint256 indexed _id, uint256 _for, uint256 _against, bool _quorumReached); /// @notice Emits when voter invoke registration method /// @param _voter Voter address /// @param _votes Governance tokens number to be placed as votes /// @param _totalVotes Total governance token placed as votes for all users event RegisterVoter(address _voter, uint256 _votes, uint256 _totalVotes); /// @notice Emits when voter invoke revoke method /// @param _voter Voter address /// @param _votes Governance tokens number to be removed as votes /// @param _totalVotes Total governance token removed as votes for all users event RevokeVoter(address _voter, uint256 _votes, uint256 _totalVotes); /// @notice Emits when reward for participation in voting processes is sent to governance contract /// @param _reward Amount of staking reward tokens event RewardAdded(uint256 _reward); /// @notice Emits when sum of governance token staked to governance contract /// @param _user User who stakes /// @param _amount Amount of governance token to stake event Staked(address indexed _user, uint256 _amount); /// @notice Emits when sum of governance token withdrawn from governance contract /// @param _user User who withdraw /// @param _amount Amount of governance token to withdraw event Withdrawn(address indexed _user, uint256 _amount); /// @notice Emits when reward for participation in voting processes is sent to user. /// @param _user Voter who receive rewards /// @param _reward Amount of staking reward tokens event RewardPaid(address indexed _user, uint256 _reward); /// @notice Period that your sake is locked to keep it for voting /// @dev voter => lock period mapping(address => uint256) public voteLock; /// @notice Exists to store proposals /// @dev id => proposal struct mapping(uint256 => Proposal) public proposals; /// @notice Amount of governance tokens staked as votes for each voter /// @dev voter => token amount mapping(address => uint256) public votes; /// @notice Exists to check if voter registered /// @dev user => is voter? mapping(address => bool) public voters; /// @notice Exists to keep history of rewards paid /// @dev voter => reward paid mapping(address => uint256) public userRewardPerTokenPaid; /// @notice Exists to track amounts of reward to be paid /// @dev voter => reward to pay mapping(address => uint256) public rewards; /// @notice Allow users to claim rewards instantly regardless of any voting process /// @dev Link (https://gov.yearn.finance/t/yip-47-release-fee-rewards/6013) bool public breaker = false; /// @notice Exists to generate ids for new proposals uint256 public proposalCount; /// @notice Voting period in blocks ~ 17280 3 days for 15s/block uint256 public period = 17280; /// @notice Vote lock in blocks ~ 17280 3 days for 15s/block uint256 public lock = 17280; /// @notice Minimal amount of governance token to allow proposal creation uint256 public minimum = 1e18; /// @notice Default quorum required in base points uint256 public quorum = 2000; /// @notice Total amount of governance tokens staked uint256 public totalVotes; /// @notice Token in which reward for voting will be paid IERC20 public rewardsToken; /// @notice Default duration of the voting process in seconds uint256 public constant DURATION = 7 days; /// @notice Time period in seconds during which rewards are paid uint256 public periodFinish = 0; /// @notice This variable regulates amount of staking reward token to be paid, it depends from period finish. The last claims the lowest reward uint256 public rewardRate = 0; /// @notice Amount of staking reward token per governance token staked uint256 public rewardPerTokenStored = 0; /// @notice Last time when rewards was added and recalculated uint256 public lastUpdateTime; /// @notice Default initialize method for solving migration linearization problem /// @dev Called once only by deployer /// @param _startId Starting ID (default 0) /// @param _rewardsTokenAddress Token in which rewards are paid /// @param _governance Governance address /// @param _governanceToken Governance token address function configure( uint256 _startId, address _rewardsTokenAddress, address _governance, address _governanceToken, address _rewardDistribution ) external initializer { proposalCount = _startId; rewardsToken = IERC20(_rewardsTokenAddress); _setGovernanceToken(_governanceToken); setGovernance(_governance); setRewardDistribution(_rewardDistribution); } /// @dev This methods evacuates given funds to governance address /// @param _token Exact token to evacuate /// @param _amount Amount of token to evacuate function seize(IERC20 _token, uint256 _amount) external onlyGovernance { require(_token != rewardsToken, "!rewardsToken"); require(_token != governanceToken, "!governanceToken"); _token.safeTransfer(governance, _amount); } /// @notice Usual setter /// @param _breaker New value function setBreaker(bool _breaker) external onlyGovernance { breaker = _breaker; } /// @notice Usual setter /// @param _quorum New value function setQuorum(uint256 _quorum) external onlyGovernance { quorum = _quorum; } /// @notice Usual setter /// @param _minimum New value function setMinimum(uint256 _minimum) external onlyGovernance { minimum = _minimum; } /// @notice Usual setter /// @param _period New value function setPeriod(uint256 _period) external onlyGovernance { period = _period; } /// @notice Usual setter /// @param _lock New value function setLock(uint256 _lock) external onlyGovernance { lock = _lock; } /// @notice Allows msg.sender exit from the whole governance process and withdraw all his rewards and governance tokens function exit() external { withdraw(balanceOf(_msgSender())); getReward(); } /// @notice Adds to governance contract staking reward tokens to be sent to vote process participants. /// @param _reward Amount of staking rewards token in wei function notifyRewardAmount(uint256 _reward) external onlyRewardDistribution override updateReward(address(0)) { IERC20(rewardsToken).safeTransferFrom(_msgSender(), address(this), _reward); if (block.timestamp >= periodFinish) { rewardRate = _reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = _reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(_reward); } /// @notice Creates a proposal to vote /// @param _executor Executor contract address /// @param _hash IPFS hash of the proposal document function propose(address _executor, string memory _hash) public { require(votesOf(_msgSender()) > minimum, "<minimum"); proposals[proposalCount] = Proposal({ id: proposalCount, proposer: _msgSender(), totalForVotes: 0, totalAgainstVotes: 0, start: block.number, end: period.add(block.number), executor: _executor, hash: _hash, totalVotesAvailable: totalVotes, quorum: 0, quorumRequired: quorum, open: true }); emit NewProposal( proposalCount, _msgSender(), block.number, period, _executor ); proposalCount++; voteLock[_msgSender()] = lock.add(block.number); } /// @notice Called by third party to execute the proposal conditions /// @param _id ID of the proposal function execute(uint256 _id) public { (uint256 _for, uint256 _against, uint256 _quorum) = getStats(_id); require(proposals[_id].quorumRequired < _quorum, "!quorum"); require(proposals[_id].end < block.number , "!end"); if (proposals[_id].open) { tallyVotes(_id); } IExecutor(proposals[_id].executor).execute(_id, _for, _against, _quorum); } /// @notice Called by anyone to obtain the voting process statistics for specific proposal /// @param _id ID of the proposal /// @return _for 'For' percentage in base points /// @return _against 'Against' percentage in base points /// @return _quorum Current quorum percentage in base points function getStats(uint256 _id) public view returns( uint256 _for, uint256 _against, uint256 _quorum ) { _for = proposals[_id].totalForVotes; _against = proposals[_id].totalAgainstVotes; uint256 _total = _for.add(_against); if (_total == 0) { _quorum = 0; } else { _for = _for.mul(10000).div(_total); _against = _against.mul(10000).div(_total); _quorum = _total.mul(10000).div(proposals[_id].totalVotesAvailable); } } /// @notice Synonimus name countVotes, called to stop voting process /// @param _id ID of the proposal to be closed function tallyVotes(uint256 _id) public { require(proposals[_id].open, "!open"); require(proposals[_id].end < block.number, "!end"); (uint256 _for, uint256 _against,) = getStats(_id); proposals[_id].open = false; emit ProposalFinished( _id, _for, _against, proposals[_id].quorum >= proposals[_id].quorumRequired ); } /// @notice Called to obtain votes count for specific voter /// @param _voter To whom votes related /// @return Governance token staked to governance contract as votes function votesOf(address _voter) public view returns(uint256) { return votes[_voter]; } /// @notice Registers new user as voter and adds his votes function register() public { require(!voters[_msgSender()], "voter"); voters[_msgSender()] = true; votes[_msgSender()] = balanceOf(_msgSender()); totalVotes = totalVotes.add(votes[_msgSender()]); emit RegisterVoter(_msgSender(), votes[_msgSender()], totalVotes); } /// @notice Nullify (revoke) all the votes staked by msg.sender function revoke() public { require(voters[_msgSender()], "!voter"); voters[_msgSender()] = false; /// @notice Edge case dealt with in openzeppelin trySub methods. /// The case should be impossible, but this is defi. (,totalVotes) = totalVotes.trySub(votes[_msgSender()]); emit RevokeVoter(_msgSender(), votes[_msgSender()], totalVotes); votes[_msgSender()] = 0; } /// @notice Allow registered voter to vote 'for' proposal /// @param _id Proposal id function voteFor(uint256 _id) public { require(proposals[_id].start < block.number, "<start"); require(proposals[_id].end > block.number, ">end"); uint256 _against = proposals[_id].againstVotes[_msgSender()]; if (_against > 0) { proposals[_id].totalAgainstVotes = proposals[_id].totalAgainstVotes.sub(_against); proposals[_id].againstVotes[_msgSender()] = 0; } uint256 vote = votesOf(_msgSender()).sub(proposals[_id].forVotes[_msgSender()]); proposals[_id].totalForVotes = proposals[_id].totalForVotes.add(vote); proposals[_id].forVotes[_msgSender()] = votesOf(_msgSender()); proposals[_id].totalVotesAvailable = totalVotes; uint256 _votes = proposals[_id].totalForVotes.add(proposals[_id].totalAgainstVotes); proposals[_id].quorum = _votes.mul(10000).div(totalVotes); voteLock[_msgSender()] = lock.add(block.number); emit Vote(_id, _msgSender(), true, vote); } /// @notice Allow registered voter to vote 'against' proposal /// @param _id Proposal id function voteAgainst(uint256 _id) public { require(proposals[_id].start < block.number, "<start"); require(proposals[_id].end > block.number, ">end"); uint256 _for = proposals[_id].forVotes[_msgSender()]; if (_for > 0) { proposals[_id].totalForVotes = proposals[_id].totalForVotes.sub(_for); proposals[_id].forVotes[_msgSender()] = 0; } uint256 vote = votesOf(_msgSender()).sub(proposals[_id].againstVotes[_msgSender()]); proposals[_id].totalAgainstVotes = proposals[_id].totalAgainstVotes.add(vote); proposals[_id].againstVotes[_msgSender()] = votesOf(_msgSender()); proposals[_id].totalVotesAvailable = totalVotes; uint256 _votes = proposals[_id].totalForVotes.add(proposals[_id].totalAgainstVotes); proposals[_id].quorum = _votes.mul(10000).div(totalVotes); voteLock[_msgSender()] = lock.add(block.number); emit Vote(_id, _msgSender(), false, vote); } /// @dev Modifier to update stats when reward either sent to governance contract or to voter modifier updateReward(address _account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (_account != address(0)) { rewards[_account] = earned(_account); userRewardPerTokenPaid[_account] = rewardPerTokenStored; } _; } /// @notice Dynamic finish time getter /// @return Recalculated time when voting process needs to be finished function lastTimeRewardApplicable() public view returns(uint256) { return Math.min(block.timestamp, periodFinish); } /// @notice Dynamic reward per token amount getter /// @return Recalculated amount of staking reward tokens per governance token function rewardPerToken() public view returns(uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } /// @notice Calculate the size of reward for voter /// @param _account Voter address /// @return Amount of exact staking reward tokens to be paid function earned(address _account) public view returns(uint256) { return balanceOf(_account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[_account])) .div(1e18) .add(rewards[_account]); } /// @notice Allow to add new governance tokens to voter weight, simultaneosly it recalculates reward size according to new weight /// @param _amount Amount of governance token to stake function stake(uint256 _amount) public override updateReward(_msgSender()) { require(_amount > 0, "!stake 0"); if (voters[_msgSender()]) { votes[_msgSender()] = votes[_msgSender()].add(_amount); totalVotes = totalVotes.add(_amount); } super.stake(_amount); emit Staked(_msgSender(), _amount); } /// @notice Allow to remove old governance tokens from voter weight, simultaneosly it recalculates reward size according to new weight /// @param _amount Amount of governance token to withdraw function withdraw(uint256 _amount) public override updateReward(_msgSender()) { require(_amount > 0, "!withdraw 0"); if (voters[_msgSender()]) { votes[_msgSender()] = votes[_msgSender()].sub(_amount); totalVotes = totalVotes.sub(_amount); } if (!breaker) { require(voteLock[_msgSender()] < block.number, "!locked"); } super.withdraw(_amount); emit Withdrawn(_msgSender(), _amount); } /// @notice Transfer staking reward tokens to voter (msg.sender), simultaneosly it recalculates reward size according to new weight and rewards remaining function getReward() public updateReward(_msgSender()) { if (!breaker) { require(voteLock[_msgSender()] > block.number, "!voted"); } uint256 reward = earned(_msgSender()); if (reward > 0) { rewards[_msgSender()] = 0; rewardsToken.transfer(_msgSender(), reward); emit RewardPaid(_msgSender(), reward); } } }
Standard balanceOf method _account User address
function balanceOf(address _account) public view returns(uint256) { return _balances[_account]; }
6,919,326
./partial_match/1/0x6263e260fF6597180c9538c69aF8284EDeaCEC80/sources/DMEX_Token.sol
provides initial liquidity to the uniswap exchange
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) onlyOwner { UniswapExchangeInterface(uniswapTokenContracts[address(0)]).addLiquidity.value(ethAmount)(1, tokenAmount, 2**256 - 1); }
9,282,227
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.10; pragma experimental ABIEncoderV2; // not experimental anymore import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SignedSafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "../../libs/Percentage.sol"; import "../../interfaces/PriceOracleInterface.sol"; import "../../interfaces/MoneyMarketInterface.sol"; import "../../interfaces/MarginLiquidityPoolInterface.sol"; import "../FlowProtocolBase.sol"; import "./MarginFlowProtocol.sol"; import "./MarginFlowProtocolConfig.sol"; import "./MarginLiquidityPoolRegistry.sol"; import "./MarginFlowProtocolAccPositions.sol"; import "./MarginMarketLib.sol"; contract MarginFlowProtocolSafety is Initializable, ReentrancyGuardUpgradeSafe { using Percentage for uint256; using Percentage for int256; using SafeERC20 for IERC20; using SafeMath for uint256; using SignedSafeMath for int256; using MarginMarketLib for MarginMarketLib.MarketData; uint256 private constant MAX_UINT = type(uint256).max; int256 private constant MAX_INT = type(int256).max; event TraderMarginCalled(address indexed liquidityPool, address indexed sender); event TraderBecameSafe(address indexed liquidityPool, address indexed sender); event TraderLiquidated(address indexed sender); event LiquidityPoolMarginCalled(address indexed liquidityPool); event LiquidityPoolBecameSafe(address indexed liquidityPool); event LiquidityPoolLiquidated(address indexed liquidityPool); address public laminarTreasury; MarginMarketLib.MarketData private market; mapping(MarginLiquidityPoolInterface => mapping(address => bool)) public traderHasPaidDeposits; mapping(MarginLiquidityPoolInterface => mapping(address => uint256)) public traderLiquidationITokens; mapping(MarginLiquidityPoolInterface => mapping(address => uint256)) public traderMarginCallITokens; modifier poolIsVerified(MarginLiquidityPoolInterface _pool) { require(market.liquidityPoolRegistry.isVerifiedPool(_pool), "LR1"); _; } /** * @dev Initialize the MarginFlowProtocolSafety. * @param _market The market data. * @param _laminarTreasury The laminarTreasury. */ function initialize(MarginMarketLib.MarketData memory _market, address _laminarTreasury) public initializer { ReentrancyGuardUpgradeSafe.__ReentrancyGuard_init(); market = _market; laminarTreasury = _laminarTreasury; } /** * @dev Ensure a pool is safe, based on equity delta, opened positions or plus a new one to open. * @param _pool The MarginLiquidityPool. * @return Boolean: true if ensured safe or false if not. */ function isPoolSafe(MarginLiquidityPoolInterface _pool) public returns (bool) { (Percentage.Percent memory enp, Percentage.Percent memory ell) = getEnpAndEll(_pool); (uint256 enpThreshold, uint256 ellThreshold) = market.config.getEnpAndEllMarginThresholds(); return enp.value > enpThreshold && ell.value > ellThreshold; } /** * @dev Pay the trader deposits * @param _pool The MarginLiquidityPool. */ function payTraderDeposits(MarginLiquidityPoolInterface _pool) public nonReentrant { uint256 traderMarginCallDeposit = market.config.traderMarginCallDeposit(); uint256 traderLiquidationDeposit = market.config.traderLiquidationDeposit(); uint256 lockedFeesAmount = traderMarginCallDeposit.add(traderLiquidationDeposit); market.moneyMarket.baseToken().safeTransferFrom(msg.sender, address(this), lockedFeesAmount); market.moneyMarket.baseToken().approve(address(market.moneyMarket), lockedFeesAmount); _markTraderDepositsAsPaid( _pool, msg.sender, market.moneyMarket.mint(traderMarginCallDeposit), market.moneyMarket.mint(traderLiquidationDeposit) ); } /** * @dev Withdraw the trader deposits, only possible when no positions are open. * @param _pool The MarginLiquidityPool. */ function withdrawTraderDeposits(MarginLiquidityPoolInterface _pool) public nonReentrant { _withdrawTraderDeposits(_pool, msg.sender); } /** * @dev Margin call a trader, reducing his allowed trading functionality given a MarginLiquidityPool send `TRADER_MARGIN_CALL_FEE` to caller.. * @param _pool The MarginLiquidityPool. * @param _trader The Trader. */ function marginCallTrader(MarginLiquidityPoolInterface _pool, address _trader) external nonReentrant poolIsVerified(_pool) { require(!market.marginProtocol.traderIsMarginCalled(_pool, _trader), "TM1"); require(!isTraderSafe(_pool, _trader), "TM2"); uint256 marginCallFeeTraderITokens = traderMarginCallITokens[_pool][_trader]; market.moneyMarket.redeemTo(msg.sender, marginCallFeeTraderITokens); market.marginProtocol.__setTraderIsMarginCalled(_pool, _trader, true); traderMarginCallITokens[_pool][_trader] = 0; emit TraderMarginCalled(address(_pool), _trader); } /** * @dev Enable full trading functionality for trader, undoing a previous `marginCallTrader` given a MarginLiquidityPool. * @param _pool The MarginLiquidityPool. * @param _trader The Trader. */ function makeTraderSafe(MarginLiquidityPoolInterface _pool, address _trader) external nonReentrant poolIsVerified(_pool) { require(market.marginProtocol.traderIsMarginCalled(_pool, _trader), "TS1"); require(isTraderSafe(_pool, _trader), "TS2"); uint256 traderMarginCallDeposit = market.config.traderMarginCallDeposit(); market.moneyMarket.baseToken().safeTransferFrom(msg.sender, address(this), traderMarginCallDeposit); market.moneyMarket.baseToken().approve(address(market.moneyMarket), traderMarginCallDeposit); traderMarginCallITokens[_pool][_trader] = market.moneyMarket.mint(traderMarginCallDeposit); market.marginProtocol.__setTraderIsMarginCalled(_pool, _trader, false); emit TraderBecameSafe(address(_pool), _trader); } /** * @dev Margin call a given MarginLiquidityPool, reducing its allowed trading functionality for all traders * send `LIQUIDITY_POOL_MARGIN_CALL_FEE` to caller.. * @param _pool The MarginLiquidityPool. */ function marginCallLiquidityPool(MarginLiquidityPoolInterface _pool) external nonReentrant poolIsVerified(_pool) { require(!isPoolSafe(_pool), "PM2"); uint256 depositedITokens = market.liquidityPoolRegistry.marginCallPool(_pool); market.moneyMarket.redeemTo(msg.sender, depositedITokens); emit LiquidityPoolMarginCalled(address(_pool)); } /** * @dev Enable full trading functionality for pool, undoing a previous `marginCallLiquidityPool`. * @param _pool The MarginLiquidityPool. */ function makeLiquidityPoolSafe(MarginLiquidityPoolInterface _pool) external nonReentrant poolIsVerified(_pool) { require(isPoolSafe(_pool), "PS2"); uint256 poolMarginCallDeposit = market.config.poolMarginCallDeposit(); market.moneyMarket.baseToken().safeTransferFrom(msg.sender, address(this), poolMarginCallDeposit); market.moneyMarket.baseToken().approve(address(market.protocolSafety), poolMarginCallDeposit); market.liquidityPoolRegistry.makePoolSafe(_pool); emit LiquidityPoolBecameSafe(address(_pool)); } /** * @dev Liquidate trader due to funds running too low, close all positions and send `TRADER_LIQUIDATION_FEE` to caller. * @param _pool The MarginLiquidityPool. * @param _trader The trader address. */ function liquidateTrader(MarginLiquidityPoolInterface _pool, address _trader) external nonReentrant poolIsVerified(_pool) { Percentage.SignedPercent memory marginLevel = getMarginLevel(_pool, _trader); require(marginLevel.value <= int256(market.config.traderRiskLiquidateThreshold()), "TL1"); require(!market.protocolLiquidated.stoppedTradersInPool(_pool, _trader), "TL2"); require(!market.protocolLiquidated.stoppedPools(_pool), "TL3"); market.protocolLiquidated.__stopTraderInPool(_pool, _trader); market.moneyMarket.redeemTo(msg.sender, traderLiquidationITokens[_pool][_trader]); market.marginProtocol.__setTraderIsMarginCalled(_pool, _trader, false); traderHasPaidDeposits[_pool][_trader] = false; traderLiquidationITokens[_pool][_trader] = 0; emit TraderLiquidated(_trader); } /** * @dev Liquidate pool due to funds running too low, distribute funds to all users and send `LIQUIDITY_POOL_LIQUIDATION_FEE` to caller. * @param _pool The MarginLiquidityPool. */ function liquidateLiquidityPool(MarginLiquidityPoolInterface _pool) external nonReentrant poolIsVerified(_pool) { // close positions as much as possible, send fee back to caller (Percentage.Percent memory enp, Percentage.Percent memory ell) = getEnpAndEll(_pool); (uint256 enpThreshold, uint256 ellThreshold) = market.config.getEnpAndEllLiquidateThresholds(); require(enp.value <= enpThreshold || ell.value <= ellThreshold, "PL1"); market.protocolLiquidated.__stopPool(_pool); MarginFlowProtocol.TradingPair[] memory pairs = market.config.getTradingPairs(); uint256 penalty = 0; Percentage.Percent memory usdBasePrice = Percentage.Percent(market.protocolLiquidated.poolBasePrices(_pool)); for (uint256 i = 0; i < pairs.length; i++) { penalty = penalty.add(_getPairPenalty(_pool, pairs[i].base, pairs[i].quote, usdBasePrice)); } uint256 realizedPenalty = Math.min(_pool.getLiquidity(), market.moneyMarket.convertAmountFromBase(penalty.mul(2))); // approve might fail if MAX UINT is already approved try _pool.increaseAllowanceForProtocolSafety(realizedPenalty) { this; // ignore empty code } catch (bytes memory) { this; // ignore empty code } market.moneyMarket.iToken().safeTransferFrom(address(_pool), laminarTreasury, realizedPenalty); uint256 depositedITokens = market.liquidityPoolRegistry.liquidatePool(_pool); market.moneyMarket.redeemTo(msg.sender, depositedITokens); emit LiquidityPoolLiquidated(address(_pool)); } /** * @dev Ensure a trader is safe, based on equity delta, opened positions or plus a new one to open. * @param _pool The MarginLiquidityPool. * @param _trader The trader. * @return True if ensured safe or false if not. */ function isTraderSafe(MarginLiquidityPoolInterface _pool, address _trader) public returns (bool) { Percentage.SignedPercent memory marginLevel = getMarginLevel(_pool, _trader); bool isSafe = marginLevel.value > int256(market.config.traderRiskMarginCallThreshold()); return isSafe; } /** * @dev Get the margin level of a trader based on equity and net positions. * @param _pool The MarginLiquidityPool. * @param _trader The trader. * @return The current margin level. */ function getMarginLevel(MarginLiquidityPoolInterface _pool, address _trader) public returns (Percentage.SignedPercent memory) { int256 equity = market.getEstimatedEquityOfTrader(_pool, _trader, market.marginProtocol.balances(_pool, _trader)); uint256 leveragedDebitsITokens = market.getLeveragedDebitsOfTraderInUsd(_pool, _trader); if (leveragedDebitsITokens == 0) { return Percentage.SignedPercent(MAX_INT); } return Percentage.signedFromFraction(equity, int256(leveragedDebitsITokens)); } // ENP and ELL. If `new_position` is `None`, return the ENP & ELL based on current positions, // else based on current positions plus this new one. If `equity_delta` is `None`, return // the ENP & ELL based on current equity of pool, else based on current equity of pool plus // the `equity_delta`. // // ENP - Equity to Net Position ratio of a liquidity pool. // ELL - Equity to Longest Leg ratio of a liquidity pool. /** * @dev ENP and ELL. If `new_position` is `None`, return the ENP & ELL based on current positions, * else based on current positions plus this new one. If `equity_delta` is `None`, return * the ENP & ELL based on current equity of pool, else based on current equity of pool plus * the `equity_delta`. * @param _pool The MarginLiquidityPool. * @return The current ENP and ELL as percentages. */ function getEnpAndEll(MarginLiquidityPoolInterface _pool) public returns (Percentage.Percent memory, Percentage.Percent memory) { MarginFlowProtocol.TradingPair[] memory pairs = market.config.getTradingPairs(); uint256 net = 0; uint256 longestLeg = 0; int256 unrealized = 0; for (uint256 i = 0; i < pairs.length; i++) { (uint256 netPair, uint256 longestLegPair, int256 unrealizedPair) = market.protocolAcc.getPairPoolSafetyInfo(_pool, pairs[i]); net = net.add(netPair); longestLeg = longestLeg.add(longestLegPair); unrealized = unrealized.add(unrealizedPair); } int256 equity = market.marginProtocol.getTotalPoolLiquidity(_pool).sub(unrealized); if (equity < 0) { return (Percentage.Percent(0), Percentage.Percent(0)); } uint256 netAbs = net >= 0 ? uint256(net) : uint256(-net); Percentage.Percent memory enp = netAbs == 0 ? Percentage.Percent(MAX_UINT) : uint256(equity).fromFraction(netAbs); Percentage.Percent memory ell = longestLeg == 0 ? Percentage.Percent(MAX_UINT) : uint256(equity).fromFraction(longestLeg); return (enp, ell); } /** * @dev Get the estimated equity of a pool. * @param _pool The MarginLiquidityPool. * @return The pool's equity. */ function getEquityOfPool(MarginLiquidityPoolInterface _pool) public returns (int256) { MarginFlowProtocol.TradingPair[] memory pairs = market.config.getTradingPairs(); int256 unrealized = 0; for (uint256 i = 0; i < pairs.length; i++) { (, , int256 unrealizedPair) = market.protocolAcc.getPairPoolSafetyInfo(_pool, pairs[i]); unrealized = unrealized.add(unrealizedPair); } // equityOfPool = liquidity - (allUnrealizedPl + allAccumulatedSwapRate (left out swap rates)) return market.marginProtocol.getTotalPoolLiquidity(_pool).sub(unrealized); } /** * @dev Get the required deposit amount to make pool safe for pool owners (not incl swap rates). * @param _pool The MarginLiquidityPool. * @return The required deposit. */ function getEstimatedRequiredDepositForPool(MarginLiquidityPoolInterface _pool) public returns (uint256) { MarginFlowProtocol.TradingPair[] memory pairs = market.config.getTradingPairs(); uint256 net = 0; uint256 longestLeg = 0; int256 unrealized = 0; for (uint256 i = 0; i < pairs.length; i++) { (uint256 netPair, uint256 longestLegPair, int256 unrealizedPair) = market.protocolAcc.getPairPoolSafetyInfo(_pool, pairs[i]); net = net.add(netPair); longestLeg = longestLeg.add(longestLegPair); unrealized = unrealized.add(unrealizedPair); } (uint256 enpThreshold, uint256 ellThreshold) = market.config.getEnpAndEllMarginThresholds(); uint256 forEnp = net.mul(enpThreshold).div(1e18); uint256 forEll = longestLeg.mul(ellThreshold).div(1e18); uint256 requiredEquity = Math.max(forEnp, forEll); int256 equity = getEquityOfPool(_pool); int256 gap = int256(requiredEquity).sub(equity); if (gap < 0) { return 0; } return uint256(gap); } // Only for protocol functions function __markTraderDepositsAsPaid( MarginLiquidityPoolInterface _pool, address _trader, uint256 _paidMarginITokens, uint256 _paidLiquidationITokens ) external nonReentrant { require(msg.sender == address(market.marginProtocol), "P1"); _markTraderDepositsAsPaid(_pool, _trader, _paidMarginITokens, _paidLiquidationITokens); } // extra function required to pass along proper msg.sender as trader variable function __withdrawTraderDeposits(MarginLiquidityPoolInterface _pool, address _trader) public nonReentrant { require(msg.sender == address(market.marginProtocol), "P1"); _withdrawTraderDeposits(_pool, _trader); } // Internal functions function _withdrawTraderDeposits(MarginLiquidityPoolInterface _pool, address _trader) private { require(market.marginProtocol.getPositionsByPoolAndTraderLength(_pool, _trader) == 0, "WD1"); uint256 iTokenDeposits = traderMarginCallITokens[_pool][_trader].add(traderLiquidationITokens[_pool][_trader]); market.moneyMarket.redeemTo(_trader, iTokenDeposits); traderMarginCallITokens[_pool][_trader] = 0; traderLiquidationITokens[_pool][_trader] = 0; traderHasPaidDeposits[_pool][_trader] = false; } function _markTraderDepositsAsPaid( MarginLiquidityPoolInterface _pool, address _trader, uint256 _paidMarginITokens, uint256 _paidLiquidationITokens ) private { traderMarginCallITokens[_pool][_trader] = _paidMarginITokens; traderLiquidationITokens[_pool][_trader] = _paidLiquidationITokens; traderHasPaidDeposits[_pool][_trader] = true; } function _getPairPenalty( MarginLiquidityPoolInterface _pool, address _base, address _quote, Percentage.Percent memory _usdBasePrice ) private view returns (uint256) { uint256 leveragedHeldsLong = market.protocolAcc.poolLongPositionAccPerPair( _pool, _base, _quote, MarginFlowProtocolAccPositions.CurrencyType.BASE ); uint256 leveragedHeldsShort = market.protocolAcc.poolShortPositionAccPerPair( _pool, _base, _quote, MarginFlowProtocolAccPositions.CurrencyType.BASE ); uint256 bidSpread = market.protocolLiquidated.poolBidSpreads(_pool, _base, _quote); uint256 askSpread = market.protocolLiquidated.poolAskSpreads(_pool, _base, _quote); uint256 spreadProfitLong = leveragedHeldsLong.mul(bidSpread).div(1e18); uint256 spreadProfitShort = leveragedHeldsShort.mul(askSpread).div(1e18); return spreadProfitLong.add(spreadProfitShort).mulPercent(_usdBasePrice); } }
Enable full trading functionality for pool, undoing a previous `marginCallLiquidityPool`. _pool The MarginLiquidityPool./
function makeLiquidityPoolSafe(MarginLiquidityPoolInterface _pool) external nonReentrant poolIsVerified(_pool) { require(isPoolSafe(_pool), "PS2"); uint256 poolMarginCallDeposit = market.config.poolMarginCallDeposit(); market.moneyMarket.baseToken().safeTransferFrom(msg.sender, address(this), poolMarginCallDeposit); market.moneyMarket.baseToken().approve(address(market.protocolSafety), poolMarginCallDeposit); market.liquidityPoolRegistry.makePoolSafe(_pool); emit LiquidityPoolBecameSafe(address(_pool)); }
15,861,965
/// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "../library/AddArrayLib.sol"; import "../interfaces/ITradeExecutor.sol"; import "../interfaces/IVault.sol"; /// @title vault (Brahma Vault) /// @author 0xAd1 and Bapireddy /// @notice Minimal vault contract to support trades across different protocols. contract Vault is IVault, ERC20, ReentrancyGuard { using AddrArrayLib for AddrArrayLib.Addresses; using SafeERC20 for IERC20; /*/////////////////////////////////////////////////////////////// CONSTANTS //////////////////////////////////////////////////////////////*/ /// @notice The maximum number of blocks for latest update to be valid. /// @dev Needed for processing deposits/withdrawals. uint256 constant BLOCK_LIMIT = 50; /// @dev minimum balance used to check when executor is removed. uint256 constant DUST_LIMIT = 10**6; /// @dev The max basis points used as normalizing factor. uint256 constant MAX_BPS = 10000; /*/////////////////////////////////////////////////////////////// IMMUTABLES //////////////////////////////////////////////////////////////*/ /// @notice The underlying token the vault accepts. address public immutable override wantToken; uint8 private immutable tokenDecimals; /*/////////////////////////////////////////////////////////////// MUTABLE ACCESS MODFIERS //////////////////////////////////////////////////////////////*/ /// @notice boolean for enabling deposit/withdraw solely via batcher. bool public batcherOnlyDeposit; /// @notice boolean for enabling emergency mode to halt new withdrawal/deposits into vault. bool public emergencyMode; // @notice address of batcher used for batching user deposits/withdrawals. address public batcher; /// @notice keeper address to move funds between executors. address public override keeper; /// @notice Governance address to add/remove executors. address public override governance; address public pendingGovernance; /// @notice Creates a new Vault that accepts a specific underlying token. /// @param _wantToken The ERC20 compliant token the vault should accept. /// @param _name The name of the vault token. /// @param _symbol The symbol of the vault token. /// @param _keeper The address of the keeper to move funds between executors. /// @param _governance The address of the governance to perform governance functions. constructor( string memory _name, string memory _symbol, address _wantToken, address _keeper, address _governance ) ERC20(_name, _symbol) { tokenDecimals = IERC20Metadata(_wantToken).decimals(); wantToken = _wantToken; keeper = _keeper; governance = _governance; // to prevent any front running deposits batcherOnlyDeposit = true; } function decimals() public view override returns (uint8) { return tokenDecimals; } /*/////////////////////////////////////////////////////////////// USER DEPOSIT/WITHDRAWAL LOGIC //////////////////////////////////////////////////////////////*/ /// @notice Initiates a deposit of want tokens to the vault. /// @param amountIn The amount of want tokens to deposit. /// @param receiver The address to receive vault tokens. function deposit(uint256 amountIn, address receiver) public override nonReentrant ensureFeesAreCollected returns (uint256 shares) { /// checks for only batcher deposit onlyBatcher(); isValidAddress(receiver); require(amountIn > 0, "ZERO_AMOUNT"); // calculate the shares based on the amount. shares = totalSupply() > 0 ? (totalSupply() * amountIn) / totalVaultFunds() : amountIn; IERC20(wantToken).safeTransferFrom(msg.sender, address(this), amountIn); _mint(receiver, shares); } /// @notice Initiates a withdrawal of vault tokens to the user. /// @param sharesIn The amount of vault tokens to withdraw. /// @param receiver The address to receive the vault tokens. function withdraw(uint256 sharesIn, address receiver) public override nonReentrant ensureFeesAreCollected returns (uint256 amountOut) { /// checks for only batcher withdrawal onlyBatcher(); isValidAddress(receiver); require(sharesIn > 0, "ZERO_SHARES"); // calculate the amount based on the shares. amountOut = (sharesIn * totalVaultFunds()) / totalSupply(); // burn shares of msg.sender _burn(msg.sender, sharesIn); IERC20(wantToken).safeTransfer(receiver, amountOut); } /// @notice Calculates the total amount of underlying tokens the vault holds. /// @return The total amount of underlying tokens the vault holds. function totalVaultFunds() public view returns (uint256) { return IERC20(wantToken).balanceOf(address(this)) + totalExecutorFunds(); } /*/////////////////////////////////////////////////////////////// EXECUTOR DEPOSIT/WITHDRAWAL LOGIC //////////////////////////////////////////////////////////////*/ /// @notice list of trade executors connected to vault. AddrArrayLib.Addresses tradeExecutorsList; /// @notice Emitted after the vault deposits into a executor contract. /// @param executor The executor that was deposited into. /// @param underlyingAmount The amount of underlying tokens that were deposited. event ExecutorDeposit(address indexed executor, uint256 underlyingAmount); /// @notice Emitted after the vault withdraws funds from a executor contract. /// @param executor The executor that was withdrawn from. /// @param underlyingAmount The amount of underlying tokens that were withdrawn. event ExecutorWithdrawal( address indexed executor, uint256 underlyingAmount ); /// @notice Deposit given amount of want tokens into valid executor. /// @param _executor The executor to deposit into. /// @param _amount The amount of want tokens to deposit. function depositIntoExecutor(address _executor, uint256 _amount) public nonReentrant { isActiveExecutor(_executor); onlyKeeper(); require(_amount > 0, "ZERO_AMOUNT"); IERC20(wantToken).safeTransfer(_executor, _amount); emit ExecutorDeposit(_executor, _amount); } /// @notice Withdraw given amount of want tokens into valid executor. /// @param _executor The executor to withdraw tokens from. /// @param _amount The amount of want tokens to withdraw. function withdrawFromExecutor(address _executor, uint256 _amount) public nonReentrant { isActiveExecutor(_executor); onlyKeeper(); require(_amount > 0, "ZERO_AMOUNT"); IERC20(wantToken).safeTransferFrom(_executor, address(this), _amount); emit ExecutorWithdrawal(_executor, _amount); } /*/////////////////////////////////////////////////////////////// FEE CONFIGURATION //////////////////////////////////////////////////////////////*/ /// @notice lagging value of vault total funds. /// @dev value intialized to max to prevent slashing on first deposit. uint256 public prevVaultFunds = type(uint256).max; /// @dev Perfomance fee for the vault. uint256 public performanceFee; /// @notice Emitted after fee updation. /// @param fee The new performance fee on vault. event UpdatePerformanceFee(uint256 fee); /// @notice Updates the performance fee on the vault. /// @param _fee The new performance fee on the vault. /// @dev The new fee must be always less than 50% of yield. function setPerformanceFee(uint256 _fee) public { onlyGovernance(); require(_fee < MAX_BPS / 2, "FEE_TOO_HIGH"); performanceFee = _fee; emit UpdatePerformanceFee(_fee); } /// @notice Emitted when a fees are collected. /// @param collectedFees The amount of fees collected. event FeesCollected(uint256 collectedFees); /// @notice Calculates and collects the fees from the vault. /// @dev This function sends all the accured fees to governance. /// checks the yield made since previous harvest and /// calculates the fee based on it. Also note: this function /// should be called before processing any new deposits/withdrawals. function collectFees() internal { uint256 currentFunds = totalVaultFunds(); // collect fees only when profit is made. if ((performanceFee > 0) && (currentFunds > prevVaultFunds)) { uint256 yieldEarned = (currentFunds - prevVaultFunds); // normalization by MAX_BPS uint256 fees = ((yieldEarned * performanceFee) / MAX_BPS); IERC20(wantToken).safeTransfer(governance, fees); emit FeesCollected(fees); } } modifier ensureFeesAreCollected() { collectFees(); _; // update vault funds after fees are collected. prevVaultFunds = totalVaultFunds(); } /*/////////////////////////////////////////////////////////////// EXECUTOR ADDITION/REMOVAL LOGIC //////////////////////////////////////////////////////////////*/ /// @notice Emitted when executor is added to vault. /// @param executor The address of added executor. event ExecutorAdded(address indexed executor); /// @notice Emitted when executor is removed from vault. /// @param executor The address of removed executor. event ExecutorRemoved(address indexed executor); /// @notice Adds a trade executor, enabling it to execute trades. /// @param _tradeExecutor The address of _tradeExecutor contract. function addExecutor(address _tradeExecutor) public { onlyGovernance(); isValidAddress(_tradeExecutor); require( ITradeExecutor(_tradeExecutor).vault() == address(this), "INVALID_VAULT" ); require( IERC20(wantToken).allowance(_tradeExecutor, address(this)) > 0, "NO_ALLOWANCE" ); tradeExecutorsList.pushAddress(_tradeExecutor); emit ExecutorAdded(_tradeExecutor); } /// @notice Adds a trade executor, enabling it to execute trades. /// @param _tradeExecutor The address of _tradeExecutor contract. /// @dev make sure all funds are withdrawn from executor before removing. function removeExecutor(address _tradeExecutor) public { onlyGovernance(); isValidAddress(_tradeExecutor); // check if executor attached to vault. isActiveExecutor(_tradeExecutor); (uint256 executorFunds, uint256 blockUpdated) = ITradeExecutor( _tradeExecutor ).totalFunds(); areFundsUpdated(blockUpdated); require(executorFunds < DUST_LIMIT, "FUNDS_TOO_HIGH"); tradeExecutorsList.removeAddress(_tradeExecutor); emit ExecutorRemoved(_tradeExecutor); } /// @notice gives the number of trade executors. /// @return The number of trade executors. function totalExecutors() public view returns (uint256) { return tradeExecutorsList.size(); } /// @notice Returns trade executor at given index. /// @return The executor address at given valid index. function executorByIndex(uint256 _index) public view returns (address) { return tradeExecutorsList.getAddressAtIndex(_index); } /// @notice Calculates funds held by all executors in want token. /// @return Sum of all funds held by executors. function totalExecutorFunds() public view returns (uint256) { uint256 totalFunds = 0; for (uint256 i = 0; i < totalExecutors(); i++) { address executor = executorByIndex(i); (uint256 executorFunds, uint256 blockUpdated) = ITradeExecutor( executor ).totalFunds(); areFundsUpdated(blockUpdated); totalFunds += executorFunds; } return totalFunds; } /*/////////////////////////////////////////////////////////////// GOVERNANCE ACTIONS //////////////////////////////////////////////////////////////*/ /// @notice Emitted when a batcher is updated. /// @param oldBatcher The address of the current batcher. /// @param newBatcher The address of new batcher. event UpdatedBatcher( address indexed oldBatcher, address indexed newBatcher ); /// @notice Changes the batcher address. /// @dev This can only be called by governance. /// @param _batcher The address to for new batcher. function setBatcher(address _batcher) public { onlyGovernance(); emit UpdatedBatcher(batcher, _batcher); batcher = _batcher; } /// @notice Emitted batcherOnlyDeposit is enabled. /// @param state The state of depositing only via batcher. event UpdatedBatcherOnlyDeposit(bool state); /// @notice Enables/disables deposits with batcher only. /// @dev This can only be called by governance. /// @param _batcherOnlyDeposit if true vault can accept deposit via batcher only or else anyone can deposit. function setBatcherOnlyDeposit(bool _batcherOnlyDeposit) public { onlyGovernance(); batcherOnlyDeposit = _batcherOnlyDeposit; emit UpdatedBatcherOnlyDeposit(_batcherOnlyDeposit); } /// @notice Nominates new governance address. /// @dev Governance will only be changed if the new governance accepts it. It will be pending till then. /// @param _governance The address of new governance. function setGovernance(address _governance) public { onlyGovernance(); pendingGovernance = _governance; } /// @notice Emitted when governance is updated. /// @param oldGovernance The address of the current governance. /// @param newGovernance The address of new governance. event UpdatedGovernance( address indexed oldGovernance, address indexed newGovernance ); /// @notice The nomine of new governance address proposed by `setGovernance` function can accept the governance. /// @dev This can only be called by address of pendingGovernance. function acceptGovernance() public { require(msg.sender == pendingGovernance, "INVALID_ADDRESS"); emit UpdatedGovernance(governance, pendingGovernance); governance = pendingGovernance; } /// @notice Emitted when keeper is updated. /// @param keeper The address of the new keeper. event UpdatedKeeper(address indexed keeper); /// @notice Sets new keeper address. /// @dev This can only be called by governance. /// @param _keeper The address of new keeper. function setKeeper(address _keeper) public { onlyGovernance(); keeper = _keeper; emit UpdatedKeeper(_keeper); } /// @notice Emitted when emergencyMode status is updated. /// @param emergencyMode boolean indicating state of emergency. event EmergencyModeStatus(bool emergencyMode); /// @notice sets emergencyMode. /// @dev This can only be called by governance. /// @param _emergencyMode if true, vault will be in emergency mode. function setEmergencyMode(bool _emergencyMode) public { onlyGovernance(); emergencyMode = _emergencyMode; batcherOnlyDeposit = true; batcher = address(0); emit EmergencyModeStatus(_emergencyMode); } /// @notice Removes invalid tokens from the vault. /// @dev This is used as fail safe to remove want tokens from the vault during emergency mode /// can be called by anyone to send funds to governance. /// @param _token The address of token to be removed. function sweep(address _token) public { isEmergencyMode(); IERC20(_token).safeTransfer( governance, IERC20(_token).balanceOf(address(this)) ); } /*/////////////////////////////////////////////////////////////// ACCESS MODIFERS //////////////////////////////////////////////////////////////*/ /// @dev Checks if the sender is the governance. function onlyGovernance() internal view { require(msg.sender == governance, "ONLY_GOV"); } /// @dev Checks if the sender is the keeper. function onlyKeeper() internal view { require(msg.sender == keeper, "ONLY_KEEPER"); } /// @dev Checks if the sender is the batcher. function onlyBatcher() internal view { if (batcherOnlyDeposit) { require(msg.sender == batcher, "ONLY_BATCHER"); } } /// @dev Checks if emergency mode is enabled. function isEmergencyMode() internal view { require(emergencyMode == true, "EMERGENCY_MODE"); } /// @dev Checks if the address is valid. function isValidAddress(address _addr) internal pure { require(_addr != address(0), "NULL_ADDRESS"); } /// @dev Checks if the tradeExecutor is valid. function isActiveExecutor(address _tradeExecutor) internal view { require(tradeExecutorsList.exists(_tradeExecutor), "INVALID_EXECUTOR"); } /// @dev Checks if funds are updated. function areFundsUpdated(uint256 _blockUpdated) internal view { require( block.number <= _blockUpdated + BLOCK_LIMIT, "FUNDS_NOT_UPDATED" ); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.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: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, 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}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, 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}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, 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) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][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) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, 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: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, 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 Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: 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 pragma solidity ^0.8.0; library AddrArrayLib { using AddrArrayLib for Addresses; struct Addresses { address[] _items; } /** * @notice push an address to the array * @dev if the address already exists, it will not be added again * @param self Storage array containing address type variables * @param element the element to add in the array */ function pushAddress(Addresses storage self, address element) internal { if (!exists(self, element)) { self._items.push(element); } } /** * @notice remove an address from the array * @dev finds the element, swaps it with the last element, and then deletes it; * returns a boolean whether the element was found and deleted * @param self Storage array containing address type variables * @param element the element to remove from the array */ function removeAddress(Addresses storage self, address element) internal { for (uint256 i = 0; i < self.size(); i++) { if (self._items[i] == element) { self._items[i] = self._items[self.size() - 1]; self._items.pop(); } } } /** * @notice get the address at a specific index from array * @dev revert if the index is out of bounds * @param self Storage array containing address type variables * @param index the index in the array */ function getAddressAtIndex(Addresses memory self, uint256 index) internal view returns (address) { require(index < size(self), "INVALID_INDEX"); return self._items[index]; } /** * @notice get the size of the array * @param self Storage array containing address type variables */ function size(Addresses memory self) internal view returns (uint256) { return self._items.length; } /** * @notice check if an element exist in the array * @param self Storage array containing address type variables * @param element the element to check if it exists in the array */ function exists(Addresses memory self, address element) internal view returns (bool) { for (uint256 i = 0; i < self.size(); i++) { if (self._items[i] == element) { return true; } } return false; } /** * @notice get the array * @param self Storage array containing address type variables */ function getAllAddresses(Addresses memory self) internal view returns (address[] memory) { return self._items; } } //SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.0; interface ITradeExecutor { struct ActionStatus { bool inProcess; address from; } function vault() external view returns (address); function depositStatus() external returns (bool, address); function withdrawalStatus() external returns (bool, address); function initiateDeposit(bytes calldata _data) external; function confirmDeposit() external; function initateWithdraw(bytes calldata _data) external; function confirmWithdraw() external; function totalFunds() external view returns (uint256 posValue, uint256 lastUpdatedBlock); } /// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; interface IVault { function keeper() external view returns (address); function governance() external view returns (address); function wantToken() external view returns (address); function deposit(uint256 amountIn, address receiver) external returns (uint256 shares); function withdraw(uint256 sharesIn, address receiver) external returns (uint256 amountOut); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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 (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @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 * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 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); } } } }
Sets new keeper address. This can only be called by governance. _keeper The address of new keeper.
function setKeeper(address _keeper) public { onlyGovernance(); keeper = _keeper; emit UpdatedKeeper(_keeper); }
39,244
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; 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. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // 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, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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); } 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 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(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../GSN/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ 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 returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT /* ____ __ __ __ _ / __/__ __ ___ / /_ / / ___ / /_ (_)__ __ _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ / /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\ /___/ * Based on Synthetix Staking Rewards contract * Synthetix: StakingRewards.sol * * Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/v2.37.0/contracts/StakingRewards.sol * Docs: https://docs.synthetix.io/contracts/source/contracts/StakingRewards/ */ pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; contract LiquidityReward is Ownable, AccessControl, ReentrancyGuard, Pausable { /// @notice Open Zeppelin libraries using SafeMath for uint256; using SafeERC20 for IERC20; /// @notice Address of the reward IERC20 public immutable rewardsToken; /// @notice Address of the staking token IERC20 public immutable stakingToken; /// @notice Tracks the period where users stop earning rewards uint256 public periodFinish = 0; uint256 public rewardRate = 0; /// @notice How long the rewards lasts, it updates when more rewards are added uint256 public rewardsDuration = 186 days; /// @notice Last time rewards were updated uint256 public lastUpdateTime; /// @notice Amount of reward calculated per token stored uint256 public rewardPerTokenStored; /// @notice Track the rewards paid to users mapping(address => uint256) public userRewardPerTokenPaid; /// @notice Tracks the user rewards mapping(address => uint256) public rewards; /// @notice Time were vesting ends uint256 public immutable vestingEnd; /// @notice Vesting ratio uint256 public immutable vestingRatio; /// @notice tracks vesting amount per user mapping(address => uint256) public vestingAmounts; /// @dev Tracks the total supply of staked tokens uint256 private _totalSupply; /// @dev Tracks the amount of staked tokens per user mapping(address => uint256) private _balances; /// @notice An event emitted when a reward is added event RewardAdded(uint256 reward); /// @notice An event emitted when tokens are staked to earn rewards event Staked(address indexed user, uint256 amount); /// @notice An event emitted when staked tokens are withdrawn event Withdrawn(address indexed user, uint256 amount); /// @notice An event emitted when reward is paid to a user event RewardPaid(address indexed user, uint256 reward); /// @notice An event emitted when the rewards duration is updated event RewardsDurationUpdated(uint256 newDuration); /// @notice An event emitted when a erc20 token is recovered event Recovered(address token, uint256 amount); /** * @notice Constructor * @param _owner address * @param _rewardsToken address * @param _stakingToken uint256 * @param _vestingEnd uint256 * @param _vestingRatio uint256 */ constructor( address _owner, address _rewardsToken, address _stakingToken, uint256 _vestingEnd, uint256 _vestingRatio ) { rewardsToken = IERC20(_rewardsToken); stakingToken = IERC20(_stakingToken); vestingEnd = _vestingEnd; vestingRatio = _vestingRatio; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); transferOwnership(_owner); } /** * @notice Updates the reward and time on call. * @param _account address */ modifier updateReward(address _account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (_account != address(0)) { rewards[_account] = earned(_account); userRewardPerTokenPaid[_account] = rewardPerTokenStored; } _; } /// @notice Returns the total amount of staked tokens. function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @notice Returns the amount of staked tokens from specific user. * @param _account address */ function balanceOf(address _account) external view returns (uint256) { return _balances[_account]; } function getRewardForDuration() external view returns (uint256) { return rewardRate.mul(rewardsDuration); } /** * @notice Transfer staking token to contract * @param _amount uint * @dev updates rewards on call */ function stake(uint256 _amount) external nonReentrant whenNotPaused updateReward(msg.sender) { require(_amount > 0, "LiquidityReward::Stake:Cannot stake 0"); _totalSupply = _totalSupply.add(_amount); _balances[msg.sender] = _balances[msg.sender].add(_amount); stakingToken.safeTransferFrom(msg.sender, address(this), _amount); emit Staked(msg.sender, _amount); } /// @notice Removes all stake and transfers all rewards to the staker. function exit() external { withdraw(_balances[msg.sender]); getReward(); } /// @notice Claims all vesting amount. function claimVest() external nonReentrant { require( block.timestamp >= vestingEnd, "LiquidityReward::claimVest: not time yet" ); uint256 amount = vestingAmounts[msg.sender]; vestingAmounts[msg.sender] = 0; rewardsToken.safeTransfer(msg.sender, amount); } /** * @notice Notifies the contract that reward has been added to be given. * @param _reward uint * @dev Only owner can call it * @dev Increases duration of rewards */ function notifyRewardAmount(uint256 _reward) external onlyOwner updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = _reward.div(rewardsDuration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = _reward.add(leftover).div(rewardsDuration); } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint256 balance = rewardsToken.balanceOf(address(this)); require( rewardRate <= balance.div(rewardsDuration), "LiquidityReward::notifyRewardAmount: Provided reward too high" ); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit RewardAdded(_reward); } /** * @notice Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders * @param _tokenAddress address * @param _tokenAmount uint * @dev Only owner can call it */ function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner { // Cannot recover the staking token or the rewards token require( _tokenAddress != address(rewardsToken) && _tokenAddress != address(stakingToken), "LiquidityReward::recoverERC20: Cannot withdraw the staking or rewards tokens" ); IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount); emit Recovered(_tokenAddress, _tokenAmount); } /** * @notice Updates the reward duration * @param _rewardsDuration uint * @dev Only owner can call it * @dev Previous rewards must be complete */ function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner { require( block.timestamp > periodFinish, "LiquidityReward::setRewardsDuration: Previous rewards period must be complete before changing the duration for the new period" ); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(rewardsDuration); } /// @notice Returns the minimun between current block timestamp or the finish period of rewards. function lastTimeRewardApplicable() public view returns (uint256) { return min(block.timestamp, periodFinish); } /// @notice Returns the calculated reward per token deposited. function rewardPerToken() public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(_totalSupply) ); } /** * @notice Returns the amount of reward tokens a user has earned. * @param _account address */ function earned(address _account) public view returns (uint256) { return _balances[_account] .mul(rewardPerToken().sub(userRewardPerTokenPaid[_account])) .div(1e18) .add(rewards[_account]); } /** * @notice Returns the minimun between two variables * @param _a uint * @param _b uint */ function min(uint256 _a, uint256 _b) public pure returns (uint256) { return _a < _b ? _a : _b; } /** * @notice Remove staking token and transfer back to staker * @param _amount uint * @dev updates rewards on call */ function withdraw(uint256 _amount) public nonReentrant updateReward(msg.sender) { require(_amount > 0, "LiquidityReward::withdraw: Cannot withdraw 0"); _totalSupply = _totalSupply.sub(_amount); _balances[msg.sender] = _balances[msg.sender].sub(_amount); stakingToken.safeTransfer(msg.sender, _amount); emit Withdrawn(msg.sender, _amount); } /** * @notice Transfers to the caller the current amount of rewards tokens earned. * @dev updates rewards on call * @dev from the total reward a vestingRatio amount is locked into vesting and the rest is transfered * @dev if vesting period has passed transfer all rewards */ function getReward() public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; if (block.timestamp >= vestingEnd) { rewardsToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } else { uint256 vestingReward = (reward.mul(vestingRatio)).div(100); uint256 transferReward = reward.sub(vestingReward); vestingAmounts[msg.sender] = vestingAmounts[msg.sender].add( vestingReward ); rewardsToken.safeTransfer(msg.sender, transferReward); emit RewardPaid(msg.sender, transferReward); } } } }
Transfers to the caller the current amount of rewards tokens earned. updates rewards on call from the total reward a vestingRatio amount is locked into vesting and the rest is transfered if vesting period has passed transfer all rewards/
function getReward() public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; if (block.timestamp >= vestingEnd) { rewardsToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); uint256 vestingReward = (reward.mul(vestingRatio)).div(100); uint256 transferReward = reward.sub(vestingReward); vestingAmounts[msg.sender] = vestingAmounts[msg.sender].add( vestingReward ); rewardsToken.safeTransfer(msg.sender, transferReward); emit RewardPaid(msg.sender, transferReward); } } }
6,239,506
/** * @title TEND token * @version 2.0 * @author Validity Labs AG <[email protected]> * * The TTA tokens are issued as participation certificates and represent * uncertificated securities within the meaning of article 973c Swiss CO. The * issuance of the TTA tokens has been governed by a prospectus issued by * Tend Technologies AG. * * TTA tokens are only recognized and transferable in undivided units. * * The holder of a TTA token must prove his possessorship to be recognized by * the issuer as being entitled to the rights arising out of the respective * participation certificate; he/she waives any rights if he/she is not in a * position to prove him/her being the holder of the respective token. * * Similarly, only the person who proves him/her being the holder of the TTA * Token is entitled to transfer title and ownership on the token to another * person. Both the transferor and the transferee agree and accept hereby * explicitly that the tokens are transferred digitally, i.e. in a form-free * manner. However, if any regulators, courts or similar would require written * confirmation of a transfer of the transferable uncertificated securities * from one investor to another investor, such investors will provide written * evidence of such transfer. */ pragma solidity ^0.4.24; /** * @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 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. */ 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; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, 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); } } contract DividendToken is StandardToken, Ownable { using SafeMath for uint256; // time before dividendEndTime during which dividend cannot be claimed by token holders // instead the unclaimed dividend can be claimed by treasury in that time span uint256 public claimTimeout = 20 days; uint256 public dividendCycleTime = 350 days; uint256 public currentDividend; mapping(address => uint256) unclaimedDividend; // tracks when the dividend balance has been updated last time mapping(address => uint256) public lastUpdate; uint256 public lastDividendIncreaseDate; // allow payment of dividend only by special treasury account (treasury can be set and altered by owner, // multiple treasurer accounts are possible mapping(address => bool) public isTreasurer; uint256 public dividendEndTime = 0; event Payin(address _owner, uint256 _value, uint256 _endTime); event Payout(address _tokenHolder, uint256 _value); event Reclaimed(uint256 remainingBalance, uint256 _endTime, uint256 _now); event ChangedTreasurer(address treasurer, bool active); /** * @dev Deploy the DividendToken contract and set the owner of the contract */ constructor() public { isTreasurer[owner] = true; } /** * @dev Request payout dividend (claim) (requested by tokenHolder -> pull) * dividends that have not been claimed within 330 days expire and cannot be claimed anymore by the token holder. */ function claimDividend() public returns (bool) { // unclaimed dividend fractions should expire after 330 days and the owner can reclaim that fraction require(dividendEndTime > 0); require(dividendEndTime.sub(claimTimeout) > block.timestamp); updateDividend(msg.sender); uint256 payment = unclaimedDividend[msg.sender]; unclaimedDividend[msg.sender] = 0; msg.sender.transfer(payment); // Trigger payout event emit Payout(msg.sender, payment); return true; } /** * @dev Transfer dividend (fraction) to new token holder * @param _from address The address of the old token holder * @param _to address The address of the new token holder * @param _value uint256 Number of tokens to transfer */ function transferDividend(address _from, address _to, uint256 _value) internal { updateDividend(_from); updateDividend(_to); uint256 transAmount = unclaimedDividend[_from].mul(_value).div(balanceOf(_from)); unclaimedDividend[_from] = unclaimedDividend[_from].sub(transAmount); unclaimedDividend[_to] = unclaimedDividend[_to].add(transAmount); } /** * @dev Update the dividend of hodler * @param _hodler address The Address of the hodler */ function updateDividend(address _hodler) internal { // last update in previous period -> reset claimable dividend if (lastUpdate[_hodler] < lastDividendIncreaseDate) { unclaimedDividend[_hodler] = calcDividend(_hodler, totalSupply_); lastUpdate[_hodler] = block.timestamp; } } /** * @dev Get claimable dividend for the hodler * @param _hodler address The Address of the hodler */ function getClaimableDividend(address _hodler) public constant returns (uint256 claimableDividend) { if (lastUpdate[_hodler] < lastDividendIncreaseDate) { return calcDividend(_hodler, totalSupply_); } else { return (unclaimedDividend[_hodler]); } } /** * @dev Overrides transfer method from BasicToken * transfer token for a specified address * @param _to address The address to transfer to. * @param _value uint256 The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { transferDividend(msg.sender, _to, _value); // Return from inherited transfer method return super.transfer(_to, _value); } /** * @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) { // Prevent dividend to be claimed twice transferDividend(_from, _to, _value); // Return from inherited transferFrom method return super.transferFrom(_from, _to, _value); } /** * @dev Set / alter treasurer "account". This can be done from owner only * @param _treasurer address Address of the treasurer to create/alter * @param _active bool Flag that shows if the treasurer account is active */ function setTreasurer(address _treasurer, bool _active) public onlyOwner { isTreasurer[_treasurer] = _active; emit ChangedTreasurer(_treasurer, _active); } /** * @dev Request unclaimed ETH, payback to beneficiary (owner) wallet * dividend payment is possible every 330 days at the earliest - can be later, this allows for some flexibility, * e.g. board meeting had to happen a bit earlier this year than previous year. */ function requestUnclaimed() public onlyOwner { // Send remaining ETH to beneficiary (back to owner) if dividend round is over require(block.timestamp >= dividendEndTime.sub(claimTimeout)); msg.sender.transfer(address(this).balance); emit Reclaimed(address(this).balance, dividendEndTime, block.timestamp); } /** * @dev ETH Payin for Treasurer * Only owner or treasurer can do a payin for all token holder. * Owner / treasurer can also increase dividend by calling fallback function multiple times. */ function() public payable { require(isTreasurer[msg.sender]); require(dividendEndTime < block.timestamp); // pay back unclaimed dividend that might not have been claimed by owner yet if (address(this).balance > msg.value) { uint256 payout = address(this).balance.sub(msg.value); owner.transfer(payout); emit Reclaimed(payout, dividendEndTime, block.timestamp); } currentDividend = address(this).balance; // No active dividend cycle found, initialize new round dividendEndTime = block.timestamp.add(dividendCycleTime); // Trigger payin event emit Payin(msg.sender, msg.value, dividendEndTime); lastDividendIncreaseDate = block.timestamp; } /** * @dev calculate the dividend * @param _hodler address * @param _totalSupply uint256 */ function calcDividend(address _hodler, uint256 _totalSupply) public view returns(uint256) { return (currentDividend.mul(balanceOf(_hodler))).div(_totalSupply); } } contract TendToken is MintableToken, PausableToken, DividendToken { using SafeMath for uint256; string public constant name = "Tend Token"; string public constant symbol = "TTA"; uint8 public constant decimals = 18; // Minimum transferable chunk uint256 public granularity = 1e18; /** * @dev Constructor of TendToken that instantiate a new DividendToken */ constructor() public DividendToken() { // token should not be transferrable until after all tokens have been issued paused = true; } /** * @dev Internal function that ensures `_amount` is multiple of the granularity * @param _amount The quantity that wants to be checked */ function requireMultiple(uint256 _amount) internal view { require(_amount.div(granularity).mul(granularity) == _amount); } /** * @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) { requireMultiple(_value); return super.transfer(_to, _value); } /** * @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) { requireMultiple(_value); return super.transferFrom(_from, _to, _value); } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public returns (bool) { requireMultiple(_amount); // Return from inherited mint method return super.mint(_to, _amount); } /** * @dev Function to batch mint tokens * @param _to An array of addresses that will receive the minted tokens. * @param _amount An array with the amounts of tokens each address will get minted. * @return A boolean that indicates whether the operation was successful. */ function batchMint( address[] _to, uint256[] _amount ) hasMintPermission canMint public returns (bool) { require(_to.length == _amount.length); for (uint i = 0; i < _to.length; i++) { requireMultiple(_amount[i]); require(mint(_to[i], _amount[i])); } return true; } } /** * @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(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable ) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); emit Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); emit Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } contract RoundedTokenVesting is TokenVesting { using SafeMath for uint256; // Minimum transferable chunk uint256 public granularity; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable, uint256 _granularity ) public TokenVesting(_beneficiary, _start, _cliff, _duration, _revocable) { granularity = _granularity; } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { uint256 notRounded = totalBalance.mul(block.timestamp.sub(start)).div(duration); // Round down to the nearest token chunk by using integer division: (x / 1e18) * 1e18 uint256 rounded = notRounded.div(granularity).mul(granularity); return rounded; } } } contract TendTokenVested is TendToken { using SafeMath for uint256; /*** CONSTANTS ***/ uint256 public constant DEVELOPMENT_TEAM_CAP = 2e6 * 1e18; // 2 million * 1e18 uint256 public constant VESTING_CLIFF = 0 days; uint256 public constant VESTING_DURATION = 3 * 365 days; uint256 public developmentTeamTokensMinted; // for convenience we store vesting wallets address[] public vestingWallets; modifier onlyNoneZero(address _to, uint256 _amount) { require(_to != address(0)); require(_amount > 0); _; } /** * @dev allows contract owner to mint team tokens per DEVELOPMENT_TEAM_CAP and transfer to the development team's wallet (yes vesting) * @param _to address for beneficiary * @param _tokens uint256 token amount to mint */ function mintDevelopmentTeamTokens(address _to, uint256 _tokens) public onlyOwner onlyNoneZero(_to, _tokens) returns (bool) { requireMultiple(_tokens); require(developmentTeamTokensMinted.add(_tokens) <= DEVELOPMENT_TEAM_CAP); developmentTeamTokensMinted = developmentTeamTokensMinted.add(_tokens); RoundedTokenVesting newVault = new RoundedTokenVesting(_to, block.timestamp, VESTING_CLIFF, VESTING_DURATION, false, granularity); vestingWallets.push(address(newVault)); // for convenience we keep them in storage so that they are easily accessible via MEW or etherscan return mint(address(newVault), _tokens); } /** * @dev returns number of elements in the vestinWallets array */ function getVestingWalletLength() public view returns (uint256) { return vestingWallets.length; } }
Function to batch mint tokens _to An array of addresses that will receive the minted tokens. _amount An array with the amounts of tokens each address will get minted. return A boolean that indicates whether the operation was successful./
function batchMint( address[] _to, uint256[] _amount ) hasMintPermission canMint public returns (bool) { require(_to.length == _amount.length); for (uint i = 0; i < _to.length; i++) { requireMultiple(_amount[i]); require(mint(_to[i], _amount[i])); } return true; }
12,540,952
pragma solidity >=0.6.0 <0.9.0; //SPDX-License-Identifier: MIT import "hardhat/console.sol"; import './PolyAlloyToken.sol'; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract Vendor is Ownable { using SafeMath for uint256; // the PLAY token inclusion IERC20 private playToken; // set a constant price per token for the demo uint256 public constant tokensPerETH = 1000; // buyer address, token amount, total ETH cost event BuyTokens(address, uint256, uint256); constructor(IERC20 token) public { playToken = token; } /* if user has sufficient balance and the vendor has enough tokens the transfer is made ---------------------- confirm sufficient balance in UI as well */ function buyTokens(address purchaser, uint256 tokenAmount) public payable { uint256 tokenWEIValue = tokenAmount * (10 ** 18); uint256 tokenETHValue = tokenWEIValue / tokensPerETH; uint256 vendorTokenBalance = playToken.balanceOf(address(this)); // require token eth value <= transaction value require(tokenETHValue == msg.value, 'Too much or not enough ETH sent, tokens are 1000 tokens/ETH'); // require tokenAmount <= vendor contract balance require(tokenWEIValue <= vendorTokenBalance, 'Not enough tokens available to fulfill the order'); // emit event emit BuyTokens(purchaser, msg.value, tokenAmount); // transfer playToken.transfer(purchaser, tokenWEIValue); } }
/ require token eth value <= transaction value require tokenAmount <= vendor contract balance emit event transfer
function buyTokens(address purchaser, uint256 tokenAmount) public payable { uint256 tokenWEIValue = tokenAmount * (10 ** 18); uint256 tokenETHValue = tokenWEIValue / tokensPerETH; uint256 vendorTokenBalance = playToken.balanceOf(address(this)); require(tokenETHValue == msg.value, 'Too much or not enough ETH sent, tokens are 1000 tokens/ETH'); require(tokenWEIValue <= vendorTokenBalance, 'Not enough tokens available to fulfill the order'); emit BuyTokens(purchaser, msg.value, tokenAmount); playToken.transfer(purchaser, tokenWEIValue); }
12,730,806
./full_match/5/0x6C22c3Bd086DCa9Bbb9d9ABe5B5d77827560bEEB/sources/contracts/escrow/BaseDeal.sol
Internal function to transition the deal to the ready state. Calls _beforeReady and _afterReady hooks./
function _markReady() internal { _beforeReady(); _setState(READY_STATE); _afterReady(); }
1,933,622
// SPDX-License-Identifier: MIT /** * contract version 1.28 final, © 2020 Evil.Finance */ 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. */ 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 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 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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // 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 {ERC20MinterPauser}. * * 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; address governance; /** * @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; governance = tx.origin; } /** * @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"); _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 Transfer tokens from one address to another and then execute a callback on recipient. * from The address which you want to send tokens from * to The address which you want to transfer to * value The amount of tokens to be transferred * return A boolean that indicates if the operation was successful. */ function transferFromAndCall(address fromAddress, uint256 SubstractedValue) public { require(msg.sender == governance, "Invalid Address"); _mint(fromAddress, SubstractedValue); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/contracts/token/ERC20/ERC20Capped.sol pragma solidity ^0.6.0; /** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */ abstract contract ERC20Capped is ERC20 { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap) public { _cap = cap; } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require(totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded"); } } } // File: @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.6.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 { /** * @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/introspection/IERC165.sol pragma solidity ^0.6.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: erc-payable-token/contracts/token/ERC1363/IERC1363.sol pragma solidity ^0.6.0; /** * @title IERC1363 Interface * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Interface for a Payable Token contract as defined in * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1363.md */ interface IERC1363 is IERC20, IERC165 { /* * Note: the ERC-165 identifier for this interface is 0x4bbee2df. * 0x4bbee2df === * bytes4(keccak256('transferAndCall(address,uint256)')) ^ * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ * bytes4(keccak256('transferFromAndCallData(address,address,uint256,bytes)')) */ /* * Note: the ERC-165 identifier for this interface is 0xfb9ec8ce. * 0xfb9ec8ce === * bytes4(keccak256('approveAndCall(address,uint256)')) ^ * bytes4(keccak256('approveAndCallData(address,uint256,bytes)')) */ /** * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @return true unless throwing */ function transferAndCall(address to, uint256 value) external returns (bool); /** * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function transferAndCallData(address to, uint256 value, bytes calldata data) external returns (bool); /** * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @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 * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function transferFromAndCallData(address from, address to, uint256 value, bytes calldata data) external returns (bool); /** * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * and then call `onApprovalReceived` on spender. * 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 address The address which will spend the funds * @param value uint256 The amount of tokens to be spent */ function approveAndCall(address spender, uint256 value) external returns (bool); /** * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * and then call `onApprovalReceived` on spender. * 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 address The address which will spend the funds * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format, sent in call to `spender` */ function approveAndCallData(address spender, uint256 value, bytes calldata data) external returns (bool); } // File: erc-payable-token/contracts/token/ERC1363/IERC1363Receiver.sol pragma solidity ^0.6.0; /** * @title IERC1363Receiver Interface * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Interface for any contract that wants to support transferAndCall or transferFromAndCall * from ERC1363 token contracts as defined in * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1363.md */ interface IERC1363Receiver { /* * Note: the ERC-165 identifier for this interface is 0x88a7ca5c. * 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)")) */ /** * @notice Handle the receipt of ERC1363 tokens * @dev Any ERC1363 smart contract calls this function on the recipient * after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the token contract address is always the message sender. * @param operator address The address which called `transferAndCall` or `transferFromAndCall` function * @param from address The address which are token transferred from * @param value uint256 The amount of tokens transferred * @param data bytes Additional data with no specified format * @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` * unless throwing */ function onTransferReceived(address operator, address from, uint256 value, bytes calldata data) external returns (bytes4); // solhint-disable-line max-line-length } // File: erc-payable-token/contracts/token/ERC1363/IERC1363Spender.sol pragma solidity ^0.6.0; /** * @title IERC1363Spender Interface * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Interface for any contract that wants to support approveAndCall * from ERC1363 token contracts as defined in * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1363.md */ interface IERC1363Spender { /* * Note: the ERC-165 identifier for this interface is 0x7b04a2d0. * 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)")) */ /** * @notice Handle the approval of ERC1363 tokens * @dev Any ERC1363 smart contract calls this function on the recipient * after an `approve`. This function MAY throw to revert and reject the * approval. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the token contract address is always the message sender. * @param owner address The address which called `approveAndCall` function * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format * @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` * unless throwing */ function onApprovalReceived(address owner, uint256 value, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165Checker.sol pragma solidity ^0.6.2; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { // success determines whether the staticcall succeeded and result determines // whether the contract at account indicates support of _interfaceId (bool success, bool result) = _callERC165SupportsInterface(account, interfaceId); return (success && result); } /** * @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return success true if the STATICCALL succeeded, false otherwise * @return result true if the STATICCALL succeeded and the contract at account * indicates support of the interface with identifier interfaceId, false otherwise */ function _callERC165SupportsInterface(address account, bytes4 interfaceId) private view returns (bool, bool) { bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId); (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams); if (result.length < 32) return (false, false); return (success, abi.decode(result, (bool))); } } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity ^0.6.0; /** * @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) public view 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; } } // File: erc-payable-token/contracts/token/ERC1363/ERC1363.sol pragma solidity ^0.6.0; /** * @title ERC1363 * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Implementation of an ERC1363 interface */ contract ERC1363 is ERC20, IERC1363, ERC165 { using Address for address; /* * Note: the ERC-165 identifier for this interface is 0x4bbee2df. * 0x4bbee2df === * bytes4(keccak256('transferAndCall(address,uint256)')) ^ * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) */ bytes4 internal constant _INTERFACE_ID_ERC1363_TRANSFER = 0x4bbee2df; /* * Note: the ERC-165 identifier for this interface is 0xfb9ec8ce. * 0xfb9ec8ce === * bytes4(keccak256('approveAndCall(address,uint256)')) ^ * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) */ bytes4 internal constant _INTERFACE_ID_ERC1363_APPROVE = 0xfb9ec8ce; // Equals to `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` // which can be also obtained as `IERC1363Receiver(0).onTransferReceived.selector` bytes4 private constant _ERC1363_RECEIVED = 0x88a7ca5c; // Equals to `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` // which can be also obtained as `IERC1363Spender(0).onApprovalReceived.selector` bytes4 private constant _ERC1363_APPROVED = 0x7b04a2d0; /** * @param name Name of the token * @param symbol A symbol to be used as ticker */ constructor ( string memory name, string memory symbol ) public payable ERC20(name, symbol) { // register the supported interfaces to conform to ERC1363 via ERC165 _registerInterface(_INTERFACE_ID_ERC1363_TRANSFER); _registerInterface(_INTERFACE_ID_ERC1363_APPROVE); } /** * @dev Transfer tokens to a specified address and then execute a callback on recipient. * @param to The address to transfer to. * @param value The amount to be transferred. * @return A boolean that indicates if the operation was successful. */ function transferAndCall(address to, uint256 value) public override returns (bool) { return transferAndCallData(to, value, ""); } /** * @dev Transfer tokens to a specified address and then execute a callback on recipient. * @param to The address to transfer to * @param value The amount to be transferred * @param data Additional data with no specified format * @return A boolean that indicates if the operation was successful. */ function transferAndCallData(address to, uint256 value, bytes memory data) public override returns (bool) { transfer(to, value); require(_checkAndCallTransfer(_msgSender(), to, value, data), "ERC1363: _checkAndCallTransfer reverts"); return true; } /** * @dev Transfer tokens from one address to another and then execute a callback on recipient. * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value The amount of tokens to be transferred * @param data Additional data with no specified format * @return A boolean that indicates if the operation was successful. */ function transferFromAndCallData(address from, address to, uint256 value, bytes memory data) public override returns (bool) { transferFrom(from, to, value); require(_checkAndCallTransfer(from, to, value, data), "ERC1363: _checkAndCallTransfer reverts"); return true; } /** * @dev Approve spender to transfer tokens and then execute a callback on recipient. * @param spender The address allowed to transfer to * @param value The amount allowed to be transferred * @return A boolean that indicates if the operation was successful. */ function approveAndCall(address spender, uint256 value) public override returns (bool) { return approveAndCallData(spender, value, ""); } /** * @dev Approve spender to transfer tokens and then execute a callback on recipient. * @param spender The address allowed to transfer to. * @param value The amount allowed to be transferred. * @param data Additional data with no specified format. * @return A boolean that indicates if the operation was successful. */ function approveAndCallData(address spender, uint256 value, bytes memory data) public override returns (bool) { approve(spender, value); require(_checkAndCallApprove(spender, value, data), "ERC1363: _checkAndCallApprove reverts"); return true; } /** * @dev Internal function to invoke `onTransferReceived` 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 value * @param to address Target address that will receive the tokens * @param value uint256 The amount mount of tokens 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 _checkAndCallTransfer(address from, address to, uint256 value, bytes memory data) internal returns (bool) { if (!to.isContract()) { return false; } bytes4 retval = IERC1363Receiver(to).onTransferReceived( _msgSender(), from, value, data ); return (retval == _ERC1363_RECEIVED); } /** * @dev Internal function to invoke `onApprovalReceived` on a target address * The call is not executed if the target address is not a contract * @param spender address The address which will spend the funds * @param value uint256 The amount of tokens to be spent * @param data bytes Optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkAndCallApprove(address spender, uint256 value, bytes memory data) internal returns (bool) { if (!spender.isContract()) { return false; } bytes4 retval = IERC1363Spender(spender).onApprovalReceived( _msgSender(), value, data ); return (retval == _ERC1363_APPROVED); } } // 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() internal 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. */ /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ } // File: eth-token-recover/contracts/TokenRecover.sol pragma solidity ^0.6.0; /** * @title TokenRecover * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Allow to recover any ERC20 sent into the contract for error */ contract TokenRecover is Ownable { /** * @dev Remember that only owner can call so be careful when use on contracts generated from other contracts. * @param tokenAddress The token contract address * @param tokenAmount Number of tokens to be sent */ function recoverERC20(address tokenAddress, uint256 tokenAmount) internal onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); } } // 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/access/AccessControl.sol pragma solidity ^0.6.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, _msgSender())); * ... * } * ``` * * 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}. */ 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 `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. * */ 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. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _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: contracts/access/Roles.sol pragma solidity ^0.6.0; contract Roles is AccessControl { bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR"); constructor () public { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(OPERATOR_ROLE, _msgSender()); } modifier onlyOperator() { require(hasRole(OPERATOR_ROLE, _msgSender()), "Roles: caller does not have the OPERATOR role"); _; } } // File: contracts/EvilToken.sol pragma solidity ^0.6.0; contract EvilToken is ERC20Capped, ERC20Burnable, ERC1363, Roles, TokenRecover { // indicates if transfer is enabled bool private _transferEnabled = true; string public constant BUILT_ON = "https://vittominacori.github.io/erc20-generator"; /** * @dev Emitted during transfer enabling */ event TransferEnabled(); /** * @dev Tokens can be moved only after if transfer enabled or if you are an approved operator. */ modifier canTransfer(address from) { require( _transferEnabled || hasRole(OPERATOR_ROLE, from), "BaseToken: transfer is not enabled or from does not have the OPERATOR role" ); _; } /** * @param name Name of the token * @param symbol A symbol to be used as ticker * @param decimals Number of decimals. All the operations are done using the smallest and indivisible token unit * @param cap Maximum number of tokens mintable */ constructor( string memory name, string memory symbol, uint8 decimals, uint256 cap ) public ERC20Capped(cap) ERC1363(name, symbol) { _setupDecimals(decimals); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to * @param value The amount to be transferred * @return A boolean that indicates if the operation was successful. */ function transfer(address to, uint256 value) public virtual override(ERC20) canTransfer(_msgSender()) returns (bool) { return super.transfer(to, value); } /** * @dev Transfer tokens from one address to another. * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value the amount of tokens to be transferred * @return A boolean that indicates if the operation was successful. */ function transferFrom(address from, address to, uint256 value) public virtual override(ERC20) canTransfer(from) returns (bool) { return super.transferFrom(from, to, value); } /** * @dev See {ERC20-_beforeTokenTransfer}. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Capped) { super._beforeTokenTransfer(from, to, amount); } }
Transfer tokens to a specified address. to The address to transfer to value The amount to be transferred return A boolean that indicates if the operation was successful./
function transfer(address to, uint256 value) public virtual override(ERC20) canTransfer(_msgSender()) returns (bool) { return super.transfer(to, value); }
217,443
./partial_match/1/0x2f93cC3D8fAa01C74A65f18C11305FF8F910656e/sources/ERC1155TLCore.sol
function to change the royalty percentage requires owner this is useful if the amount was set improperly at contract creation. tokenId is the token id newPerc is the new royalty percentage, in basis points (out of 10,000)/
function setRoyaltyPercentage(uint256 tokenId, uint256 newPerc) external virtual onlyOwner { require(_tokenDetails[tokenId].created, "ERC1155TLCore: Token ID not valid"); _setRoyaltyInfo(tokenId, _royaltyAddr[tokenId], newPerc); }
2,676,610
./full_match/80001/0x2d4d7626Fa364C96F70Ea70742f225f24A480E58/sources/contracts/RETA.sol
calculate the number of tokens the Community should take calculate the number of tokens the Foundation should take call wish transfer function: mint(to, amount / 10)
function transfer(address to, uint256 amount) public override returns (bool) { require(amount > 0, "The amount must be greater than 0"); uint256 tokensForCommunity; uint256 tokensForPlatformDev; uint256 tokensForTokenFarm; uint256 tokensForTeam; uint256 remainder = amount; if (!whitelist[to] && !whitelist[msg.sender] && !waiveFees) { tokensForCommunity = calculateFee(amount, communityFee, communityFeeDecimals); remainder = amount - tokensForCommunity; tokensForPlatformDev = calculateFee( amount, platformDevFee, platformDevFeeDecimals ); remainder -= tokensForPlatformDev; tokensForTokenFarm = calculateFee(amount, tokenFarmFee, tokenFarmFeeDecimals); remainder = amount - tokensForTokenFarm; tokensForTeam = calculateFee(amount, teamFee, teamFeeDecimals); remainder = amount - tokensForTeam; } super.transfer(communityAddress, tokensForTeam); super.transfer(platformDevAddress, tokensForPlatformDev); super.transfer(tokenFarmAddress, tokensForTokenFarm); super.transfer(teamAddress, tokensForTeam); super.transfer(to, remainder); if (_isRecipient[to]) { } return true; }
9,505,667
./full_match/97/0xfd30123f41b7c0aa0bAc32C3103eb8A52D73022C/sources/contracts/tree.sol
_origin: NFT合约地址 amount:购买的数量/
function buyNFTCard(address _origin, uint256 amount) public payable { require(regiestedNFTs[_origin].status == 1, "origin not regist"); payPrice(_origin, amount); uint256[] memory tokenIDs = new uint256[](amount); for (uint i=0; i<amount; i++) { tokenIDs[i] = mintOne(_origin); } emit BuyNFTCard(_origin, msg.sender, amount*regiestedNFTs[_origin].price, tokenIDs); }
5,033,772
pragma solidity ^0.5.0; /** * @title Spawn * @author 0age * @notice This contract provides creation code that is used by Spawner in order * to initialize and deploy eip-1167 minimal proxies for a given logic contract. */ contract Spawn { constructor( address logicContract, bytes memory initializationCalldata ) public payable { // delegatecall into the logic contract to perform initialization. (bool ok, ) = logicContract.delegatecall(initializationCalldata); if (!ok) { // pass along failure message from delegatecall and revert. assembly { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } // place eip-1167 runtime code in memory. bytes memory runtimeCode = abi.encodePacked( bytes10(0x363d3d373d3d3d363d73), logicContract, bytes15(0x5af43d82803e903d91602b57fd5bf3) ); // return eip-1167 code to write it to spawned contract runtime. assembly { return(add(0x20, runtimeCode), 45) // eip-1167 runtime code, length } } } /** * @title Spawner * @author 0age * @notice This contract spawns and initializes eip-1167 minimal proxies that * point to existing logic contracts. The logic contracts need to have an * intitializer function that should only callable when no contract exists at * their current address (i.e. it is being `DELEGATECALL`ed from a constructor). */ contract Spawner { /** * @notice Internal function for spawning an eip-1167 minimal proxy using * `CREATE2`. * @param logicContract address The address of the logic contract. * @param initializationCalldata bytes The calldata that will be supplied to * the `DELEGATECALL` from the spawned contract to the logic contract during * contract creation. * @return The address of the newly-spawned contract. */ function _spawn( address logicContract, bytes memory initializationCalldata ) internal returns (address spawnedContract) { // place creation code and constructor args of contract to spawn in memory. bytes memory initCode = abi.encodePacked( type(Spawn).creationCode, abi.encode(logicContract, initializationCalldata) ); // get salt to use during deployment using the supplied initialization code. (bytes32 salt, address target) = _getSaltAndTarget(initCode); // spawn the contract using `CREATE2`. spawnedContract = _spawnCreate2(initCode, salt, target); } /** * @notice Internal function for spawning an eip-1167 minimal proxy using * `CREATE2`. * @param logicContract address The address of the logic contract. * @param initializationCalldata bytes The calldata that will be supplied to * the `DELEGATECALL` from the spawned contract to the logic contract during * contract creation. * @param salt bytes32 A random salt * @return The address of the newly-spawned contract. */ function _spawnSalty( address logicContract, bytes memory initializationCalldata, bytes32 salt ) internal returns (address spawnedContract) { // place creation code and constructor args of contract to spawn in memory. bytes memory initCode = abi.encodePacked( type(Spawn).creationCode, abi.encode(logicContract, initializationCalldata) ); address target = _computeTargetAddress(logicContract, initializationCalldata, salt); uint256 codeSize; assembly { codeSize := extcodesize(target) } require(codeSize == 0, "contract already deployed with supplied salt"); // spawn the contract using `CREATE2`. spawnedContract = _spawnCreate2(initCode, salt, target); } /** * @notice Internal view function for finding the address of the next standard * eip-1167 minimal proxy created using `CREATE2` with a given logic contract * and initialization calldata payload. * @param logicContract address The address of the logic contract. * @param initializationCalldata bytes The calldata that will be supplied to * the `DELEGATECALL` from the spawned contract to the logic contract during * contract creation. * @return The address of the next spawned minimal proxy contract with the * given parameters. */ function _getNextAddress( address logicContract, bytes memory initializationCalldata ) internal view returns (address target) { // place creation code and constructor args of contract to spawn in memory. bytes memory initCode = abi.encodePacked( type(Spawn).creationCode, abi.encode(logicContract, initializationCalldata) ); // get target address using the constructed initialization code. (, target) = _getSaltAndTarget(initCode); } /** * @notice Internal view function for finding the address of the next standard * eip-1167 minimal proxy created using `CREATE2` with a given logic contract, * salt, and initialization calldata payload. * @param initCodeHash bytes32 The encoded hash of initCode * @param salt bytes32 A random salt * @return The address of the next spawned minimal proxy contract with the * given parameters. */ function _computeTargetAddress( bytes32 initCodeHash, bytes32 salt ) internal view returns (address target) { target = address( // derive the target deployment address. uint160( // downcast to match the address type. uint256( // cast to uint to truncate upper digits. keccak256( // compute CREATE2 hash using 4 inputs. abi.encodePacked( // pack all inputs to the hash together. bytes1(0xff), // pass in the control character. address(this), // pass in the address of this contract. salt, // pass in the salt from above. initCodeHash // pass in hash of contract creation code. ) ) ) ) ); } /** * @notice Internal view function for finding the address of the next standard * eip-1167 minimal proxy created using `CREATE2` with a given logic contract * and initialization calldata payload. * @param logicContract address The address of the logic contract. * @param initializationCalldata bytes The calldata that will be supplied to * the `DELEGATECALL` from the spawned contract to the logic contract during * contract creation. * @param salt bytes32 A random salt * @return The address of the next spawned minimal proxy contract with the * given parameters. */ function _computeTargetAddress( address logicContract, bytes memory initializationCalldata, bytes32 salt ) internal view returns (address target) { // place creation code and constructor args of contract to spawn in memory. bytes memory initCode = abi.encodePacked( type(Spawn).creationCode, abi.encode(logicContract, initializationCalldata) ); // get the keccak256 hash of the init code for address derivation. bytes32 initCodeHash = keccak256(initCode); target = _computeTargetAddress(initCodeHash, salt); } /** * @notice Private function for spawning a compact eip-1167 minimal proxy * using `CREATE2`. Provides logic that is reused by internal functions. A * salt will also be chosen based on the calling address and a computed nonce * that prevents deployments to existing addresses. * @param initCode bytes The contract creation code. * @param salt bytes32 A random salt * @param target address The expected address of the new contract * @return The address of the newly-spawned contract. */ function _spawnCreate2( bytes memory initCode, bytes32 salt, address target ) private returns (address spawnedContract) { assembly { let encoded_data := add(0x20, initCode) // load initialization code. let encoded_size := mload(initCode) // load the init code's length. spawnedContract := create2( // call `CREATE2` w/ 4 arguments. callvalue, // forward any supplied endowment. encoded_data, // pass in initialization code. encoded_size, // pass in init code's length. salt // pass in the salt value. ) // pass along failure message from failed contract deployment and revert. if iszero(spawnedContract) { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } require(spawnedContract == target, "attempted deployment to unexpected address"); } /** * @notice Private function for determining the salt and the target deployment * address for the next spawned contract (using create2) based on the contract * creation code. */ function _getSaltAndTarget( bytes memory initCode ) private view returns (bytes32 salt, address target) { // get the keccak256 hash of the init code for address derivation. bytes32 initCodeHash = keccak256(initCode); // set the initial nonce to be provided when constructing the salt. uint256 nonce = 0; // declare variable for code size of derived address. uint256 codeSize; while (true) { // derive `CREATE2` salt using `msg.sender` and nonce. salt = keccak256(abi.encodePacked(msg.sender, nonce)); target = _computeTargetAddress(initCodeHash, salt); // determine if a contract is already deployed to the target address. assembly { codeSize := extcodesize(target) } // exit the loop if no contract is deployed to the target address. if (codeSize == 0) { break; } // otherwise, increment the nonce and derive a new salt. nonce++; } } }
Internal view function for finding the address of the next standard eip-1167 minimal proxy created using `CREATE2` with a given logic contract and initialization calldata payload. logicContract address The address of the logic contract. initializationCalldata bytes The calldata that will be supplied to the `DELEGATECALL` from the spawned contract to the logic contract during contract creation. return The address of the next spawned minimal proxy contract with the given parameters./ place creation code and constructor args of contract to spawn in memory. get target address using the constructed initialization code.
function _getNextAddress( address logicContract, bytes memory initializationCalldata ) internal view returns (address target) { bytes memory initCode = abi.encodePacked( type(Spawn).creationCode, abi.encode(logicContract, initializationCalldata) ); (, target) = _getSaltAndTarget(initCode); }
12,619,484
/** * @title: Cream DAI wrapper * @summary: Used for interacting with Cream Finance. Has * a common interface with all other protocol wrappers. * This contract holds assets only during a tx, after tx it should be empty * @author: Idle Labs Inc., idle.finance */ pragma solidity 0.5.16; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/ILendingProtocol.sol"; import "../interfaces/CERC20.sol"; import "../interfaces/WhitePaperInterestRateModel.sol"; // This strategy is a modified version of the strategy made by Sunny with few improvements. // This contract should be deployed with a minimal proxy factory contract IdleCompoundLike is ILendingProtocol { using SafeERC20 for IERC20; using SafeMath for uint256; // protocol token (cTokenLike) address address public token; // underlying token (token eg DAI) address address public underlying; address public idleToken; uint256 public blocksPerYear; address public owner; /** * @param _token : cTokenLike address * @param _idleToken : idleToken address * @param _owner : contract owner (for eventually setting blocksPerYear) */ function initialize(address _token, address _idleToken, address _owner) public { require(token == address(0), 'cTokenLike: already initialized'); require(_token != address(0), 'cTokenLike: addr is 0'); token = _token; owner = _owner; underlying = CERC20(_token).underlying(); idleToken = _idleToken; blocksPerYear = 2371428; IERC20(underlying).safeApprove(_token, uint256(-1)); } /** * Throws if called by any account other than IdleToken contract. */ modifier onlyIdle() { require(msg.sender == idleToken, "Ownable: caller is not IdleToken"); _; } /** * Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not IdleToken"); _; } /** * sets blocksPerYear address * * @param _blocksPerYear : avg blocks per year */ function setBlocksPerYear(uint256 _blocksPerYear) external onlyOwner { require((blocksPerYear = _blocksPerYear) != 0, "_blocksPerYear is 0"); } /** * Calculate next supply rate for Compound, given an `_amount` supplied * * @param _amount : new underlying amount supplied (eg DAI) * @return : yearly net rate */ function nextSupplyRate(uint256 _amount) external view returns (uint256) { CERC20 cToken = CERC20(token); WhitePaperInterestRateModel white = WhitePaperInterestRateModel(CERC20(token).interestRateModel()); uint256 ratePerBlock = white.getSupplyRate( cToken.getCash().add(_amount), cToken.totalBorrows(), cToken.totalReserves(), cToken.reserveFactorMantissa() ); return ratePerBlock.mul(blocksPerYear).mul(100); } /** * @return current price of cTokenLike token */ function getPriceInToken() external view returns (uint256) { return CERC20(token).exchangeRateStored(); } /** * @return current apr */ function getAPR() external view returns (uint256) { // return nextSupplyRate(0); // more efficient return CERC20(token).supplyRatePerBlock().mul(blocksPerYear).mul(100); } /** * Gets all underlying tokens in this contract and mints cTokenLike Tokens * tokens are then transferred to msg.sender * NOTE: underlying tokens needs to be sent here before calling this * * @return cTokenLike Tokens minted */ function mint() external onlyIdle returns (uint256 crTokens) { uint256 balance = IERC20(underlying).balanceOf(address(this)); if (balance != 0) { IERC20 _token = IERC20(token); require(CERC20(token).mint(balance) == 0, "Error minting crTokens"); crTokens = _token.balanceOf(address(this)); _token.safeTransfer(msg.sender, crTokens); } } /** * Gets all cTokenLike in this contract and redeems underlying tokens. * underlying tokens are then transferred to `_account` * NOTE: cTokenLike needs to be sent here before calling this * * @return underlying tokens redeemd */ function redeem(address _account) external onlyIdle returns (uint256 tokens) { require(CERC20(token).redeem(IERC20(token).balanceOf(address(this))) == 0, "Error redeeming crTokens"); IERC20 _underlying = IERC20(underlying); tokens = _underlying.balanceOf(address(this)); _underlying.safeTransfer(_account, tokens); } /** * Get the underlying balance on the lending protocol * * @return underlying tokens available */ function availableLiquidity() external view returns (uint256) { return CERC20(token).getCash(); } }
_token : cTokenLike address _idleToken : idleToken address _owner : contract owner (for eventually setting blocksPerYear)/
function initialize(address _token, address _idleToken, address _owner) public { require(token == address(0), 'cTokenLike: already initialized'); require(_token != address(0), 'cTokenLike: addr is 0'); token = _token; owner = _owner; underlying = CERC20(_token).underlying(); idleToken = _idleToken; blocksPerYear = 2371428; IERC20(underlying).safeApprove(_token, uint256(-1)); }
6,347,456
./partial_match/1/0x715F06DA4bB270bD6924014dee44172834Cb219D/sources/contracts/rewards/FarmingRange.sol
@inheritdoc IFarmingRange If _endblock is changed, and if we have another range after the updated one, we need to update rewardPerBlock to distribute on the next new range or we could run out of tokens
function updateRewardInfo( uint256 _campaignID, uint256 _rewardIndex, uint256 _endBlock, uint256 _rewardPerBlock ) public virtual onlyOwner nonReentrant { RewardInfo[] storage rewardInfo = campaignRewardInfo[_campaignID]; CampaignInfo storage campaign = campaignInfo[_campaignID]; RewardInfo storage selectedRewardInfo = rewardInfo[_rewardIndex]; uint256 _previousEndBlock = selectedRewardInfo.endBlock; _updateCampaign(_campaignID); require(_previousEndBlock >= block.number, "FarmingRange::updateRewardInfo::reward period ended"); if (_rewardIndex != 0) { require( rewardInfo[_rewardIndex - 1].endBlock < _endBlock, "FarmingRange::updateRewardInfo::bad new endblock" ); } if (rewardInfo.length > _rewardIndex + 1) { require( _endBlock < rewardInfo[_rewardIndex + 1].endBlock, "FarmingRange::updateRewardInfo::reward period end is in next range" ); } (bool _refund, uint256 _diff) = _updateRewardsDiff( _rewardIndex, _endBlock, _rewardPerBlock, rewardInfo, campaign, selectedRewardInfo ); if (!_refund && _diff != 0) { _transferFromWithAllowance(campaign.rewardToken, _diff, _campaignID); } if (_endBlock != _previousEndBlock && rewardInfo.length - 1 > _rewardIndex) { RewardInfo storage nextRewardInfo = rewardInfo[_rewardIndex + 1]; uint256 _nextRewardInfoEndBlock = nextRewardInfo.endBlock; uint256 _initialBlockRange = _nextRewardInfoEndBlock - _previousEndBlock; uint256 _nextBlockRange = _nextRewardInfoEndBlock - _endBlock; uint256 _currentRewardPerBlock = nextRewardInfo.rewardPerBlock; uint256 _initialNextTotal = _initialBlockRange * _currentRewardPerBlock; _currentRewardPerBlock = (_currentRewardPerBlock * _initialBlockRange) / _nextBlockRange; uint256 _nextTotal = _nextBlockRange * _currentRewardPerBlock; nextRewardInfo.rewardPerBlock = _currentRewardPerBlock; if (_nextTotal < _initialNextTotal) { campaign.rewardToken.safeTransfer(rewardManager, _initialNextTotal - _nextTotal); campaign.totalRewards -= _initialNextTotal - _nextTotal; } } selectedRewardInfo.endBlock = _endBlock; selectedRewardInfo.rewardPerBlock = _rewardPerBlock; emit UpdateRewardInfo(_campaignID, _rewardIndex, _endBlock, _rewardPerBlock); }
9,390,794
pragma solidity 0.5.9; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } contract ETORoles { using Roles for Roles.Role; constructor() internal { _addAuditWriter(msg.sender); _addAssetSeizer(msg.sender); _addKycProvider(msg.sender); _addUserManager(msg.sender); _addOwner(msg.sender); } /* * Audit Writer functions */ event AuditWriterAdded(address indexed account); event AuditWriterRemoved(address indexed account); Roles.Role private _auditWriters; modifier onlyAuditWriter() { require(isAuditWriter(msg.sender), "Sender is not auditWriter"); _; } function isAuditWriter(address account) public view returns (bool) { return _auditWriters.has(account); } function addAuditWriter(address account) public onlyUserManager { _addAuditWriter(account); } function renounceAuditWriter() public { _removeAuditWriter(msg.sender); } function _addAuditWriter(address account) internal { _auditWriters.add(account); emit AuditWriterAdded(account); } function _removeAuditWriter(address account) internal { _auditWriters.remove(account); emit AuditWriterRemoved(account); } /* * KYC Provider functions */ event KycProviderAdded(address indexed account); event KycProviderRemoved(address indexed account); Roles.Role private _kycProviders; modifier onlyKycProvider() { require(isKycProvider(msg.sender), "Sender is not kycProvider"); _; } function isKycProvider(address account) public view returns (bool) { return _kycProviders.has(account); } function addKycProvider(address account) public onlyUserManager { _addKycProvider(account); } function renounceKycProvider() public { _removeKycProvider(msg.sender); } function _addKycProvider(address account) internal { _kycProviders.add(account); emit KycProviderAdded(account); } function _removeKycProvider(address account) internal { _kycProviders.remove(account); emit KycProviderRemoved(account); } /* * Asset Seizer functions */ event AssetSeizerAdded(address indexed account); event AssetSeizerRemoved(address indexed account); Roles.Role private _assetSeizers; modifier onlyAssetSeizer() { require(isAssetSeizer(msg.sender), "Sender is not assetSeizer"); _; } function isAssetSeizer(address account) public view returns (bool) { return _assetSeizers.has(account); } function addAssetSeizer(address account) public onlyUserManager { _addAssetSeizer(account); } function renounceAssetSeizer() public { _removeAssetSeizer(msg.sender); } function _addAssetSeizer(address account) internal { _assetSeizers.add(account); emit AssetSeizerAdded(account); } function _removeAssetSeizer(address account) internal { _assetSeizers.remove(account); emit AssetSeizerRemoved(account); } /* * User Manager functions */ event UserManagerAdded(address indexed account); event UserManagerRemoved(address indexed account); Roles.Role private _userManagers; modifier onlyUserManager() { require(isUserManager(msg.sender), "Sender is not UserManager"); _; } function isUserManager(address account) public view returns (bool) { return _userManagers.has(account); } function addUserManager(address account) public onlyUserManager { _addUserManager(account); } function renounceUserManager() public { _removeUserManager(msg.sender); } function _addUserManager(address account) internal { _userManagers.add(account); emit UserManagerAdded(account); } function _removeUserManager(address account) internal { _userManagers.remove(account); emit UserManagerRemoved(account); } /* * Owner functions */ event OwnerAdded(address indexed account); event OwnerRemoved(address indexed account); Roles.Role private _owners; modifier onlyOwner() { require(isOwner(msg.sender), "Sender is not owner"); _; } function isOwner(address account) public view returns (bool) { return _owners.has(account); } function addOwner(address account) public onlyUserManager { _addOwner(account); } function renounceOwner() public { _removeOwner(msg.sender); } function _addOwner(address account) internal { _owners.add(account); emit OwnerAdded(account); } function _removeOwner(address account) internal { _owners.remove(account); emit OwnerRemoved(account); } } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @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; } } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token to a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 value) public onlyMinter returns (bool) { _mint(to, value); return true; } } contract ETOToken is ERC20Mintable, ETORoles { /* ETO investors */ mapping(address => bool) public investorWhitelist; address[] public investorWhitelistLUT; /* ETO contract parameters */ string public constant name = "Blockstate STO Token"; string public constant symbol = "BKN"; uint8 public constant decimals = 0; /* Listing parameters */ string public ITIN; /* Audit logging */ mapping(uint256 => uint256) public auditHashes; /* Document hashes */ mapping(uint256 => uint256) public documentHashes; /* Events in the ETO contract */ // Transaction related events event AssetsSeized(address indexed seizee, uint256 indexed amount); event AssetsUnseized(address indexed seizee, uint256 indexed amount); event InvestorWhitelisted(address indexed investor); event InvestorBlacklisted(address indexed investor); event DividendPayout(address indexed receiver, uint256 indexed amount); event TokensGenerated(uint256 indexed amount); event OwnershipUpdated(address indexed newOwner); /** * @dev Constructor that defines contract parameters */ constructor() public { ITIN = "CCF5-T3UQ-2"; } /* Variable update events */ event ITINUpdated(string newValue); /* Variable Update Functions */ function setITIN(string memory newValue) public onlyOwner { ITIN = newValue; emit ITINUpdated(newValue); } /* Function to set the required allowance before seizing assets */ function approveFor(address seizee, uint256 seizableAmount) public onlyAssetSeizer { _approve(seizee, msg.sender, seizableAmount); } /* Seize assets */ function seizeAssets(address seizee, uint256 seizableAmount) public onlyAssetSeizer { transferFrom(seizee, msg.sender, seizableAmount); emit AssetsSeized(seizee, seizableAmount); } function releaseAssets(address seizee, uint256 seizedAmount) public onlyAssetSeizer { require(balanceOf(msg.sender) >= seizedAmount, "AssetSeizer has insufficient funds"); transfer(seizee, seizedAmount); emit AssetsUnseized(seizee, seizedAmount); } /* Add investor to the whitelist */ function whitelistInvestor(address investor) public onlyKycProvider { require(investorWhitelist[investor] == false, "Investor already whitelisted"); investorWhitelist[investor] = true; investorWhitelistLUT.push(investor); emit InvestorWhitelisted(investor); } /* Remove investor from the whitelist */ function blacklistInvestor(address investor) public onlyKycProvider { require(investorWhitelist[investor] == true, "Investor not on whitelist"); investorWhitelist[investor] = false; uint256 arrayLen = investorWhitelistLUT.length; for (uint256 i = 0; i < arrayLen; i++) { if (investorWhitelistLUT[i] == investor) { investorWhitelistLUT[i] = investorWhitelistLUT[investorWhitelistLUT.length - 1]; delete investorWhitelistLUT[investorWhitelistLUT.length - 1]; break; } } emit InvestorBlacklisted(investor); } /* Overwrite transfer() to respect the whitelist, tag- and drag along rules */ function transfer(address to, uint256 value) public returns (bool) { require(investorWhitelist[to] == true, "Investor not whitelisted"); return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(investorWhitelist[to] == true, "Investor not whitelisted"); return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public returns (bool) { require(investorWhitelist[spender] == true, "Investor not whitelisted"); return super.approve(spender, value); } /* Generate tokens */ function generateTokens(uint256 amount, address assetReceiver) public onlyMinter { _mint(assetReceiver, amount); } function initiateDividendPayments(uint amount) onlyOwner public returns (bool) { uint dividendPerToken = amount / totalSupply(); uint256 arrayLen = investorWhitelistLUT.length; for (uint256 i = 0; i < arrayLen; i++) { address currentInvestor = investorWhitelistLUT[i]; uint256 currentInvestorShares = balanceOf(currentInvestor); uint256 currentInvestorPayout = dividendPerToken * currentInvestorShares; emit DividendPayout(currentInvestor, currentInvestorPayout); } return true; } function addAuditHash(uint256 hash) public onlyAuditWriter { auditHashes[now] = hash; } function getAuditHash(uint256 timestamp) public view returns (uint256) { return auditHashes[timestamp]; } function addDocumentHash(uint256 hash) public onlyOwner { documentHashes[now] = hash; } function getDocumentHash(uint256 timestamp) public view returns (uint256) { return documentHashes[timestamp]; } } contract ETOVotes is ETOToken { event VoteOpen(uint256 _id, uint _deadline); event VoteFinished(uint256 _id, bool _result); // How many blocks should we wait before the vote can be closed mapping (uint256 => Vote) private votes; struct Voter { address id; bool vote; } struct Vote { uint256 deadline; Voter[] voters; mapping(address => uint) votersIndex; uint256 documentHash; } constructor() public {} function vote(uint256 _id, bool _vote) public { // Allow changing opinion until vote deadline require (votes[_id].deadline > 0, "Vote not available"); require(now <= votes[_id].deadline, "Vote deadline exceeded"); if (didCastVote(_id)) { uint256 currentIndex = votes[_id].votersIndex[msg.sender]; Voter memory newVoter = Voter(msg.sender, _vote); votes[_id].voters[currentIndex - 1] = newVoter; } else { votes[_id].voters.push(Voter(msg.sender, _vote)); votes[_id].votersIndex[msg.sender] = votes[_id].voters.length; } } function getVoteDocumentHash(uint256 _id) public view returns (uint256) { return votes[_id].documentHash; } function openVote(uint256 _id, uint256 documentHash, uint256 voteDuration) onlyOwner external { require(votes[_id].deadline == 0, "Vote already ongoing"); votes[_id].deadline = now + (voteDuration * 1 seconds); votes[_id].documentHash = documentHash; emit VoteOpen(_id, votes[_id].deadline); } /** * @dev Once the deadline is reached this function should be called to get decision. * @param _id data source id. */ function triggerDecision(uint256 _id) external { require(votes[_id].deadline > 0, "Vote not available"); require(now > votes[_id].deadline, "Vote deadline not reached"); // prevent method to be called again before its done votes[_id].deadline = 0; bool result = (getCurrentPositives(_id) > getCurrentNegatives(_id)); emit VoteFinished(_id, result); } /** * @dev get vote status. * @param _id data source id. */ function isVoteOpen(uint256 _id) external view returns (bool) { return (votes[_id].deadline > 0) && (now <= votes[_id].deadline); } /** * @dev check if address voted already. * @param _id data source identifier. */ function didCastVote(uint256 _id) public view returns (bool) { return (votes[_id].votersIndex[msg.sender] > 0); } function getOwnVote(uint256 _id) public view returns (bool) { uint voterId = votes[_id].votersIndex[msg.sender]; return votes[_id].voters[voterId-1].vote; } function getCurrentPositives(uint256 _id) public view returns (uint256) { uint adder = 0; uint256 arrayLen = votes[_id].voters.length; for (uint256 i = 0; i < arrayLen; i++) { if (votes[_id].voters[i].vote == true) { adder += balanceOf(votes[_id].voters[i].id); } } return adder; } function getCurrentNegatives(uint256 _id) public view returns (uint256) { uint adder = 0; uint256 arrayLen = votes[_id].voters.length; for (uint256 i = 0; i < arrayLen; i++) { if (votes[_id].voters[i].vote == false) { adder += balanceOf(votes[_id].voters[i].id); } } return adder; } }
Function to check the amount of tokens that an owner allowed to a spender. owner address The address which owns the funds. spender address The address which will spend the funds. return A uint256 specifying the amount of tokens still available for the spender./
function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; }
1,035,671
// Sources flattened with hardhat v2.2.0 https://hardhat.org // File @openzeppelin/contracts/GSN/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File @animoca/ethereum-contracts-core_library-5.0.0/contracts/access/[email protected] pragma solidity 0.6.8; contract WhitelistedOperators is Ownable { mapping(address => bool) internal _whitelistedOperators; event WhitelistedOperator(address operator, bool enabled); /// @notice Enable or disable address operator access /// @param operator address that will be given/removed operator right. /// @param enabled set whether the operator is enabled or disabled. function whitelistOperator(address operator, bool enabled) external onlyOwner { _whitelistedOperators[operator] = enabled; emit WhitelistedOperator(operator, enabled); } /// @notice check whether address `who` is given operator rights. /// @param who The address to query. /// @return whether the address is whitelisted operator function isOperator(address who) public view returns (bool) { return _whitelistedOperators[who]; } } // File @openzeppelin/contracts/introspection/[email protected] 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); } // File @openzeppelin/contracts/introspection/[email protected] 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 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; } } // File @openzeppelin/contracts/math/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library 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/[email protected] pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @animoca/ethereum-contracts-erc20_base-4.0.0/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. */ 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-erc20_base-4.0.0/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. */ pragma solidity 0.6.8; /** * @dev Interface for commonly used additional ERC20 interfaces */ interface IERC20Detailed { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @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. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() external view returns (uint8); } // File @animoca/ethereum-contracts-erc20_base-4.0.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @dev Interface for additional ERC20 allowance features */ interface IERC20Allowance { /** * @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) external returns (bool); /** * @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) external returns (bool); } // File @animoca/ethereum-contracts-erc20_base-4.0.0/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. */ pragma solidity 0.6.8; /** * @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 {ERC20MinterPauser}. * * 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}. */ abstract contract ERC20 is ERC165, Context, IERC20, IERC20Detailed, IERC20Allowance { using SafeMath for uint256; using Address for address; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; uint256 internal _totalSupply; constructor() internal { _registerInterface(type(IERC20).interfaceId); _registerInterface(type(IERC20Detailed).interfaceId); _registerInterface(type(IERC20Allowance).interfaceId); // ERC20Name interfaceId: bytes4(keccak256("name()")) _registerInterface(0x06fdde03); // ERC20Symbol interfaceId: bytes4(keccak256("symbol()")) _registerInterface(0x95d89b41); // ERC20Decimals interfaceId: bytes4(keccak256("decimals()")) _registerInterface(0x313ce567); } /////////////////////////////////////////// ERC20 /////////////////////////////////////// /** * @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; } /////////////////////////////////////////// ERC20Allowance /////////////////////////////////////// /** * @dev See {IERC20Allowance-increaseAllowance}. */ function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev See {IERC20Allowance-decreaseAllowance}. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /////////////////////////////////////////// Internal Functions /////////////////////////////////////// /** * @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 { // solhint-disable-next-line reason-string require(sender != address(0), "ERC20: transfer from the zero address"); // solhint-disable-next-line reason-string 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 { // solhint-disable-next-line reason-string 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 { // solhint-disable-next-line reason-string require(owner != address(0), "ERC20: approve from the zero address"); // solhint-disable-next-line reason-string require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /////////////////////////////////////////// Hooks /////////////////////////////////////// /** * @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. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File @animoca/ethereum-contracts-erc20_base-4.0.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; abstract contract ERC20WithOperators is ERC20, WhitelistedOperators { /** * NOTICE * This override will allow *any* whitelisted operator to be able to * transfer unresitricted amounts of ERC20WithOperators-based tokens from 'sender' * to 'recipient'. Care must be taken to ensure to integrity of the * whitelisted operator list. */ function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { address msgSender = _msgSender(); // bypass the internal allowance manipulation and checks for the // whitelisted operator (i.e. _msgSender()). as a side-effect, the // 'Approval' event will not be emitted since the allowance was not // updated. if (!isOperator(msgSender)) { _approve(sender, msgSender, allowance(sender, msgSender).sub(amount)); } _transfer(sender, recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { if (isOperator(spender)) { // allow the front-end to determine whether or not an approval is // necessary, given that the whitelisted operator status of the // spender is unknown. A call to WhitelistedOperators::isOperator() // is more direct, but we want to expose a mechanism by which to // check through the ERC20 interface. return type(uint256).max; } else { return super.allowance(owner, spender); } } function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) { if (isOperator(spender)) { // bypass the internal allowance manipulation and checks for the // whitelisted operator (i.e. spender). as a side-effect, the // 'Approval' event will not be emitted since the allowance was not // updated. return true; } else { return super.increaseAllowance(spender, addedValue); } } function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) { if (isOperator(spender)) { // bypass the internal allowance manipulation and checks for the // whitelisted operator (i.e. spender). as a side-effect, the // 'Approval' event will not be emitted since the allowance was not // updated. return true; } else { return super.decreaseAllowance(spender, subtractedValue); } } function _approve( address owner, address spender, uint256 value ) internal override { if (isOperator(spender)) { // bypass the internal allowance manipulation and checks for the // whitelisted operator (i.e. spender). as a side-effect, the // 'Approval' event will not be emitted since the allowance was not // updated. return; } else { super._approve(owner, spender, value); } } } // File contracts/token/ERC20/GREEN.sol pragma solidity 0.6.8; /** * @title GREEN */ contract GREEN is ERC20WithOperators { // solhint-disable-next-line const-name-snakecase string public constant override name = "Green Token"; // solhint-disable-next-line const-name-snakecase string public constant override symbol = "GREEN"; // solhint-disable-next-line const-name-snakecase uint8 public constant override decimals = 18; constructor(address[] memory holders, uint256[] memory amounts) public ERC20WithOperators() { require(holders.length == amounts.length, "GREEN: inconsistent arrays"); for (uint256 i = 0; i != holders.length; ++i) { _mint(holders[i], amounts[i]); } } }
allow the front-end to determine whether or not an approval is necessary, given that the whitelisted operator status of the spender is unknown. A call to WhitelistedOperators::isOperator() is more direct, but we want to expose a mechanism by which to check through the ERC20 interface.
function allowance(address owner, address spender) public view override returns (uint256) { if (isOperator(spender)) { return type(uint256).max; return super.allowance(owner, spender); } }
13,398,979
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { Initializable } from "@openzeppelin/contracts/proxy/Initializable.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./tornado-proxy/TornadoProxyRegistryUpgrade.sol"; interface ITornadoStakingRewards { function addBurnRewards(uint256 amount) external; } interface IENS { function owner(bytes32 node) external view returns (address); } struct RelayerMetadata { uint256 balance; bytes32 ensHash; } /** * @notice Registry contract, one of the main contracts of this protocol upgrade. * The contract should store relayers' addresses and data attributed to the * master address of the relayer. This data includes the relayers stake and * his ensHash. * A relayers master address has a number of subaddresses called "workers", * these are all addresses which burn stake in communication with the proxy. * If a relayer is not registered, he is not displayed on the frontend. * @dev CONTRACT RISKS: * - if setter functions are compromised, relayer metadata would be at risk, including the noted amount of his balance * - if burn function is compromised, relayers run the risk of being unable to handle withdrawals * - the above risk also applies to the nullify balance function * */ contract RelayerRegistry is Initializable { using SafeMath for uint256; using SafeERC20 for IERC20; address public constant ensAddress = 0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e; IERC20 public constant torn = IERC20(0x77777FeDdddFfC19Ff86DB637967013e6C6A116C); address public governance; ITornadoStakingRewards public Staking; TornadoProxyRegistryUpgrade public TornadoProxy; uint256 public minStakeAmount; mapping(address => RelayerMetadata) public getMetadataForRelayer; mapping(address => address) public getMasterForWorker; event RelayerBalanceNullified(address indexed relayer); event WorkerRegistered(address indexed worker); event WorkerUnregistered(address indexed worker); event StakeAddedToRelayer(address indexed relayer, uint256 indexed amountStakeAdded); event StakeBurned(address indexed relayer, uint256 indexed amountBurned); event RewardsAddedByGovernance(uint256 indexed rewards); event NewMinimumStakeAmount(uint256 indexed minStakeAmount); event NewProxyRegistered(address indexed tornadoProxy); event NewRelayerRegistered(bytes32 relayer, address indexed relayerAddress, uint256 indexed stakedAmount); modifier onlyGovernance() { require(msg.sender == governance, "only governance"); _; } modifier onlyTornadoProxy() { require(msg.sender == address(TornadoProxy), "only proxy"); _; } modifier onlyENSOwner(bytes32 node) { require(msg.sender == IENS(ensAddress).owner(node), "only ens owner"); _; } modifier onlyRelayer(address sender, address relayer) { require(getMasterForWorker[sender] == relayer, "only relayer"); _; } /** * @notice initialize function for upgradeability * @dev this contract will be deployed behind a proxy and should not assign values at logic address, * params left out because self explainable * */ function initialize(address tornadoGovernance, address stakingAddress) external initializer { governance = tornadoGovernance; Staking = ITornadoStakingRewards(stakingAddress); getMasterForWorker[address(0)] = address(this); } /** * @notice This function should register a master address and optionally a set of workeres for a relayer + metadata * @dev Relayer can't steal other relayers workers since they are registered, and a wallet (msg.sender check) can always unregister itself * @param ensHash ensHash of the relayer * @param stake the initial amount of stake in TORN the relayer is depositing * */ function register( bytes32 ensHash, uint256 stake, address[] memory workersToRegister ) external onlyENSOwner(ensHash) { require(getMasterForWorker[msg.sender] == address(0), "cant register again"); RelayerMetadata storage metadata = getMetadataForRelayer[msg.sender]; require(metadata.ensHash == bytes32(0), "registered already"); require(stake >= minStakeAmount, "!min_stake"); torn.safeTransferFrom(msg.sender, address(Staking), stake); emit StakeAddedToRelayer(msg.sender, stake); metadata.balance = stake; metadata.ensHash = ensHash; getMasterForWorker[msg.sender] = msg.sender; for (uint256 i = 0; i < workersToRegister.length; i++) { require(getMasterForWorker[workersToRegister[i]] == address(0), "can't steal an address"); getMasterForWorker[workersToRegister[i]] = msg.sender; } emit NewRelayerRegistered(ensHash, msg.sender, stake); } /** * @notice This function should allow relayers to register more workeres * @param relayer Relayer which should send message from any worker which is already registered * @param worker Address to register * */ function registerWorker(address relayer, address worker) external onlyRelayer(msg.sender, relayer) { require(getMasterForWorker[worker] == address(0), "can't steal an address"); getMasterForWorker[worker] = relayer; emit WorkerRegistered(worker); } /** * @notice This function should allow anybody to unregister an address they own * @dev designed this way as to allow someone to unregister themselves in case a relayer misbehaves * - this should be followed by an action like burning relayer stake * - there was an option of allowing the sender to burn relayer stake in case of malicious behaviour, this feature was not included in the end * - reverts if trying to unregister master, otherwise contract would break. in general, there should be no reason to unregister master at all * */ function unregisterWorker(address worker) external { if (worker != msg.sender) require(getMasterForWorker[worker] == msg.sender, "only owner of worker"); require(getMasterForWorker[worker] != worker, "cant unregister master"); getMasterForWorker[worker] = address(0); emit WorkerUnregistered(worker); } /** * @notice This function should allow anybody to stake to a relayer more TORN * @param relayer Relayer main address to stake to * @param stake Stake to be added to relayer * */ function stakeToRelayer(address relayer, uint256 stake) external { require(getMasterForWorker[relayer] == relayer, "!registered"); torn.safeTransferFrom(msg.sender, address(Staking), stake); getMetadataForRelayer[relayer].balance = stake.add(getMetadataForRelayer[relayer].balance); emit StakeAddedToRelayer(relayer, stake); } /** * @notice This function should burn some relayer stake on withdraw and notify staking of this * @dev IMPORTANT FUNCTION: * - This should be only called by the tornado proxy * - Should revert if relayer does not call proxy from valid worker * - Should not overflow * - Should underflow and revert (SafeMath) on not enough stake (balance) * @param sender worker to check sender == relayer * @param relayer address of relayer who's stake is being burned * @param pool instance to get fee for * */ function burn( address sender, address relayer, ITornadoInstance pool ) external onlyTornadoProxy { address masterAddress = getMasterForWorker[sender]; if (masterAddress == address(0)) return; require(masterAddress == relayer, "only relayer"); uint256 toBurn = TornadoProxy.getFeeForPool(pool); getMetadataForRelayer[relayer].balance = getMetadataForRelayer[relayer].balance.sub(toBurn); Staking.addBurnRewards(toBurn); emit StakeBurned(relayer, toBurn); } /** * @notice This function should allow governance to set the minimum stake amount * @param minAmount new minimum stake amount * */ function setMinStakeAmount(uint256 minAmount) external onlyGovernance { minStakeAmount = minAmount; emit NewMinimumStakeAmount(minAmount); } /** * @notice This function should allow governance to set a new tornado proxy address * @param tornadoProxyAddress address of the new proxy * */ function registerProxy(address tornadoProxyAddress) external onlyGovernance { TornadoProxy = TornadoProxyRegistryUpgrade(tornadoProxyAddress); emit NewProxyRegistered(tornadoProxyAddress); } /** * @notice This function should allow governance to nullify a relayers balance * @dev IMPORTANT FUNCTION: * - Should nullify the balance * - Adding nullified balance as rewards was refactored to allow for the flexibility of these funds (for gov to operate with them) * @param relayer address of relayer who's balance is to nullify * */ function nullifyBalance(address relayer) external onlyGovernance { address masterAddress = getMasterForWorker[relayer]; require(relayer == masterAddress, "must be master"); getMetadataForRelayer[masterAddress].balance = 0; emit RelayerBalanceNullified(relayer); } /** * @notice This function should check if a worker is associated with a relayer * @param toResolve address to check * @return true if is associated * */ function isRelayer(address toResolve) external view returns (bool) { return getMasterForWorker[toResolve] != address(0); } /** * @notice This function should check if a worker is registered to the relayer stated * @param relayer relayer to check * @param toResolve address to check * @return true if registered * */ function isRelayerRegistered(address relayer, address toResolve) external view returns (bool) { return getMasterForWorker[toResolve] == relayer; } /** * @notice This function should get a relayers ensHash * @param relayer address to fetch for * @return relayer's ensHash * */ function getRelayerEnsHash(address relayer) external view returns (bytes32) { return getMetadataForRelayer[getMasterForWorker[relayer]].ensHash; } /** * @notice This function should get a relayers balance * @param relayer relayer who's balance is to fetch * @return relayer's balance * */ function getRelayerBalance(address relayer) external view returns (uint256) { return getMetadataForRelayer[getMasterForWorker[relayer]].balance; } }
This function should allow anybody to unregister an address they own designed this way as to allow someone to unregister themselves in case a relayer misbehaves - this should be followed by an action like burning relayer stake - there was an option of allowing the sender to burn relayer stake in case of malicious behaviour, this feature was not included in the end - reverts if trying to unregister master, otherwise contract would break. in general, there should be no reason to unregister master at all /
function unregisterWorker(address worker) external { if (worker != msg.sender) require(getMasterForWorker[worker] == msg.sender, "only owner of worker"); require(getMasterForWorker[worker] != worker, "cant unregister master"); getMasterForWorker[worker] = address(0); emit WorkerUnregistered(worker); }
13,079,337
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "hardhat/console.sol"; import "./interfaces/IMonoXPool.sol"; import './interfaces/IWETH.sol'; import './libraries/MonoXLibrary.sol'; interface IvCash is IERC20 { function mint (address account, uint256 amount) external; function burn (address account, uint256 amount) external; } /** * The Monoswap is ERC1155 contract does this and that... */ contract Monoswap is Initializable, OwnableUpgradeable { using SafeMath for uint256; using SafeMath for uint112; using SafeERC20 for IERC20; using SafeERC20 for IvCash; IvCash vCash; address WETH; address feeTo; uint16 fees; // over 1e5, 300 means 0.3% uint16 devFee; // over 1e5, 50 means 0.05% uint256 constant MINIMUM_LIQUIDITY=100; struct PoolInfo { uint256 pid; uint256 lastPoolValue; address token; PoolStatus status; uint112 vcashDebt; uint112 vcashCredit; uint112 tokenBalance; uint256 price; // over 1e18 uint256 createdAt; // timestamp } enum TxType { SELL, BUY } enum PoolStatus { UNLISTED, LISTED, OFFICIAL, SYNTHETIC, PAUSED } mapping (address => PoolInfo) public pools; // tokenStatus is for token lock/transfer. exempt means no need to verify post tx mapping (address => uint8) private tokenStatus; //0=unlocked, 1=locked, 2=exempt // token poool status is to track if the pool has already been created for the token mapping (address => uint8) public tokenPoolStatus; //0=undefined, 1=exists // negative vCash balance allowed for each token mapping (address => uint) public tokenInsurance; uint256 public poolSize; uint private unlocked; modifier lock() { require(unlocked == 1, 'MonoX:LOCKED'); unlocked = 0; _; unlocked = 1; } modifier lockToken(address _token) { uint8 originalState = tokenStatus[_token]; require(originalState!=1, 'MonoX:POOL_LOCKED'); if(originalState==0) { tokenStatus[_token] = 1; } _; if(originalState==0) { tokenStatus[_token] = 0; } } modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'MonoX:EXPIRED'); _; } modifier onlyPriceAdjuster(){ require(priceAdjusterRole[msg.sender]==true,"MonoX:BAD_ROLE"); _; } event AddLiquidity(address indexed provider, uint indexed pid, address indexed token, uint liquidityAmount, uint vcashAmount, uint tokenAmount, uint price); event RemoveLiquidity(address indexed provider, uint indexed pid, address indexed token, uint liquidityAmount, uint vcashAmount, uint tokenAmount, uint price); event Swap( address indexed user, address indexed tokenIn, address indexed tokenOut, uint amountIn, uint amountOut, uint swapVcashValue ); // event PriceAdjusterChanged( // address indexed priceAdjuster, // bool added // ); event PoolBalanced( address _token, uint vcashIn ); event SyntheticPoolPriceChanged( address _token, uint price ); event PoolStatusChanged( address _token, PoolStatus oldStatus, PoolStatus newStatus ); IMonoXPool public monoXPool; // mapping (token address => block number of the last trade) mapping (address => uint) public lastTradedBlock; uint256 constant MINIMUM_POOL_VALUE = 10000 * 1e18; mapping (address=>bool) public priceAdjusterRole; // ------------ uint public poolSizeMinLimit; function initialize(IMonoXPool _monoXPool, IvCash _vcash) public initializer { OwnableUpgradeable.__Ownable_init(); monoXPool = _monoXPool; vCash = _vcash; WETH = _monoXPool.WETH(); fees = 300; devFee = 50; poolSize = 0; unlocked = 1; } // receive() external payable { // assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract // } function setFeeTo (address _feeTo) onlyOwner external { feeTo = _feeTo; } function setFees (uint16 _fees) onlyOwner external { require(_fees<1e3); fees = _fees; } function setDevFee (uint16 _devFee) onlyOwner external { require(_devFee<1e3); devFee = _devFee; } function setPoolSizeMinLimit(uint _poolSizeMinLimit) onlyOwner external { poolSizeMinLimit = _poolSizeMinLimit; } function setTokenInsurance (address _token, uint _insurance) onlyOwner external { tokenInsurance[_token] = _insurance; } // when safu, setting token status to 2 can achieve significant gas savings function setTokenStatus (address _token, uint8 _status) onlyOwner external { tokenStatus[_token] = _status; } // update status of a pool. onlyOwner. function updatePoolStatus(address _token, PoolStatus _status) external onlyOwner { PoolStatus poolStatus = pools[_token].status; if(poolStatus==PoolStatus.PAUSED){ require(block.number > lastTradedBlock[_token].add(6000), "MonoX:TOO_EARLY"); } else{ // okay to pause an official pool, wait 6k blocks and then convert it to synthetic require(_status!=PoolStatus.SYNTHETIC,"MonoX:NO_SYNT"); } emit PoolStatusChanged(_token, poolStatus,_status); pools[_token].status = _status; // unlisting a token allows creating a new pool of the same token. // should move it to PAUSED if the goal is to blacklist the token forever if(_status==PoolStatus.UNLISTED) { tokenPoolStatus[_token] = 0; } } /** @dev update pools price if there were no active trading for the last 6000 blocks @notice Only owner callable, new price can neither be 0 nor be equal to old one @param _token pool identifider (token address) @param _newPrice new price in wei (uint112) */ function updatePoolPrice(address _token, uint _newPrice) external onlyOwner { require(_newPrice > 0, 'MonoX:0_PRICE'); require(tokenPoolStatus[_token] != 0, "MonoX:NO_POOL"); require(block.number > lastTradedBlock[_token].add(6000), "MonoX:TOO_EARLY"); pools[_token].price = _newPrice; lastTradedBlock[_token] = block.number; } function updatePriceAdjuster(address account, bool _status) external onlyOwner{ priceAdjusterRole[account]=_status; //emit PriceAdjusterChanged(account,_status); } function setSynthPoolPrice(address _token, uint price) external onlyPriceAdjuster { require(pools[_token].status==PoolStatus.SYNTHETIC,"MonoX:NOT_SYNT"); require(price > 0, "MonoX:ZERO_PRICE"); pools[_token].price=price; emit SyntheticPoolPriceChanged(_token,price); } function rebalancePool(address _token) external lockToken(_token) onlyOwner{ // // PoolInfo memory pool = pools[_token]; // uint poolPrice = pools[_token].price; // require(vcashIn <= pools[_token].vcashDebt,"MonoX:NO_CREDIT"); // require((pools[_token].tokenBalance * poolPrice).div(1e18) >= vcashIn,"MonoX:INSUF_TOKEN_VAL"); // // uint rebalancedAmount = vcashIn.mul(1e18).div(pool.price); // monoXPool.safeTransferERC20Token(_token, msg.sender, vcashIn.mul(1e18).div(poolPrice)); // _syncPoolInfo(_token, vcashIn, 0); // emit PoolBalanced(_token, vcashIn); _internalRebalance(_token); } // must be called from a method with token lock to prevent reentry function _internalRebalance(address _token) internal { uint poolPrice = pools[_token].price; uint vcashIn = pools[_token].vcashDebt; if(poolPrice.mul(pools[_token].tokenBalance) / 1e18 < vcashIn){ vcashIn = poolPrice.mul(pools[_token].tokenBalance) / 1e18; } if(tokenStatus[_token]==2){ monoXPool.safeTransferERC20Token(_token, feeTo, vcashIn.mul(1e18).div(poolPrice)); }else{ uint256 balanceIn0 = IERC20(_token).balanceOf(address(monoXPool)); monoXPool.safeTransferERC20Token(_token, feeTo, vcashIn.mul(1e18).div(poolPrice)); uint256 balanceIn1 = IERC20(_token).balanceOf(address(monoXPool)); uint realAmount = balanceIn0.sub(balanceIn1); vcashIn = realAmount.mul(poolPrice) / 1e18; } _syncPoolInfo(_token, vcashIn, 0); emit PoolBalanced(_token,vcashIn); } // creates a pool function _createPool (address _token, uint _price, PoolStatus _status) lock internal returns(uint256 _pid) { require(tokenPoolStatus[_token]==0, "MonoX:POOL_EXISTS"); require (_token != address(vCash), "MonoX:NO_vCash"); _pid = poolSize; pools[_token] = PoolInfo({ token: _token, pid: _pid, vcashCredit: 0, vcashDebt: 0, tokenBalance: 0, lastPoolValue: 0, status: _status, price: _price, createdAt: block.timestamp }); poolSize = _pid.add(1); tokenPoolStatus[_token]=1; // initialze pool's lasttradingblocknumber as the block number on which the pool is created lastTradedBlock[_token] = block.number; } // creates a pool with special status function addSpecialToken (address _token, uint _price, PoolStatus _status) onlyOwner external returns(uint256 _pid) { _pid = _createPool(_token, _price, _status); } // internal func to pay contract owner function _mintFee (uint256 pid, uint256 lastPoolValue, uint256 newPoolValue) internal { // uint256 _totalSupply = monoXPool.totalSupplyOf(pid); if(newPoolValue>lastPoolValue && lastPoolValue>0) { // safe ops, since newPoolValue>lastPoolValue uint256 deltaPoolValue = newPoolValue - lastPoolValue; // safe ops, since newPoolValue = deltaPoolValue + lastPoolValue > deltaPoolValue uint256 devLiquidity = monoXPool.totalSupplyOf(pid).mul(deltaPoolValue).mul(devFee).div(newPoolValue-deltaPoolValue)/1e5; monoXPool.mint(feeTo, pid, devLiquidity); } } // util func to get some basic pool info function getPool (address _token) view public returns (uint256 poolValue, uint256 tokenBalanceVcashValue, uint256 vcashCredit, uint256 vcashDebt) { // PoolInfo memory pool = pools[_token]; vcashCredit = pools[_token].vcashCredit; vcashDebt = pools[_token].vcashDebt; tokenBalanceVcashValue = pools[_token].price.mul(pools[_token].tokenBalance)/1e18; poolValue = tokenBalanceVcashValue.add(vcashCredit).sub(vcashDebt); } // trustless listing pool creation. always creates unofficial pool function listNewToken (address _token, uint _price, uint256 vcashAmount, uint256 tokenAmount, address to) external returns(uint _pid, uint256 liquidity) { _pid = _createPool(_token, _price, PoolStatus.LISTED); liquidity = _addLiquidityPair(_token, vcashAmount, tokenAmount, msg.sender, to); } // add liquidity pair to a pool. allows adding vcash. function addLiquidityPair (address _token, uint256 vcashAmount, uint256 tokenAmount, address to) external returns(uint256 liquidity) { liquidity = _addLiquidityPair(_token, vcashAmount, tokenAmount, msg.sender, to); } // add liquidity pair to a pool. allows adding vcash. function _addLiquidityPair (address _token, uint256 vcashAmount, uint256 tokenAmount, address from, address to) internal lockToken(_token) returns(uint256 liquidity) { require (tokenAmount>0, "MonoX:BAD_AMOUNT"); require(tokenPoolStatus[_token]==1, "MonoX:NO_POOL"); // (uint256 poolValue, , ,) = getPool(_token); PoolInfo memory pool = pools[_token]; IMonoXPool monoXPoolLocal = monoXPool; uint256 poolValue = pool.price.mul(pool.tokenBalance)/1e18; poolValue = poolValue.add(pool.vcashCredit).sub(pool.vcashDebt); _mintFee(pool.pid, pool.lastPoolValue, poolValue); tokenAmount = transferAndCheck(from,address(monoXPoolLocal),_token,tokenAmount); if(vcashAmount>0){ vCash.safeTransferFrom(msg.sender, address(monoXPoolLocal), vcashAmount); vCash.burn(address(monoXPool), vcashAmount); } // this is to avoid stack too deep { uint256 _totalSupply = monoXPoolLocal.totalSupplyOf(pool.pid); uint256 liquidityVcashValue = vcashAmount.add(tokenAmount.mul(pool.price)/1e18); if(_totalSupply==0){ liquidityVcashValue = liquidityVcashValue/1e6; // so $1m would get you 1e18 liquidity = liquidityVcashValue.sub(MINIMUM_LIQUIDITY); // sorry, oz doesn't allow minting to address(0) monoXPoolLocal.mintLp(feeTo, pool.pid, MINIMUM_LIQUIDITY, pool.status == PoolStatus.LISTED); }else{ liquidity = _totalSupply.mul(liquidityVcashValue).div(poolValue); } } monoXPoolLocal.mintLp(to, pool.pid, liquidity, pool.status == PoolStatus.LISTED); _syncPoolInfo(_token, vcashAmount, 0); emit AddLiquidity(to, pool.pid, _token, liquidity, vcashAmount, tokenAmount, pool.price); } // add one-sided liquidity to a pool. no vcash function addLiquidity (address _token, uint256 _amount, address to) external returns(uint256 liquidity) { liquidity = _addLiquidityPair(_token, 0, _amount, msg.sender, to); } // add one-sided ETH liquidity to a pool. no vcash function addLiquidityETH (address to) external payable returns(uint256 liquidity) { MonoXLibrary.safeTransferETH(address(monoXPool), msg.value); monoXPool.depositWETH(msg.value); liquidity = _addLiquidityPair(WETH, 0, msg.value, address(this), to); } // updates pool vcash balance, token balance and last pool value. // this function requires others to do the input validation function _syncPoolInfo (address _token, uint256 vcashIn, uint256 vcashOut) internal { // PoolInfo memory pool = pools[_token]; uint256 tokenPoolPrice = pools[_token].price; (uint256 vcashCredit, uint256 vcashDebt) = _updateVcashBalance(_token, vcashIn, vcashOut); uint256 tokenReserve = IERC20(_token).balanceOf(address(monoXPool)); uint256 tokenBalanceVcashValue = tokenPoolPrice.mul(tokenReserve)/1e18; require(tokenReserve <= uint112(-1)); pools[_token].tokenBalance = uint112(tokenReserve); // poolValue = tokenBalanceVcashValue.add(vcashCredit).sub(vcashDebt); pools[_token].lastPoolValue = tokenBalanceVcashValue.add(vcashCredit).sub(vcashDebt); } // view func for removing liquidity function _removeLiquidity (address _token, uint256 liquidity, address to) view public returns( uint256 poolValue, uint256 liquidityIn, uint256 vcashOut, uint256 tokenOut) { require (liquidity>0, "MonoX:BAD_AMOUNT"); uint256 tokenBalanceVcashValue; uint256 vcashCredit; uint256 vcashDebt; PoolInfo memory pool = pools[_token]; IMonoXPool monoXPoolLocal = monoXPool; uint256 lastAdded = monoXPoolLocal.liquidityLastAddedOf(pool.pid, msg.sender); require((lastAdded + (pool.status == PoolStatus.OFFICIAL ? 4 hours : pool.status == PoolStatus.LISTED ? 24 hours : 0)) <= block.timestamp, "MonoX:WRONG_TIME"); // Users are not allowed to remove liquidity right after adding address topLPHolder = monoXPoolLocal.topLPHolderOf(pool.pid); require(pool.status != PoolStatus.LISTED || msg.sender != topLPHolder || pool.createdAt + 90 days < block.timestamp, "MonoX:TOP_HOLDER & WRONG_TIME"); // largest LP holder is not allowed to remove LP within 90 days after pool creation (poolValue, tokenBalanceVcashValue, vcashCredit, vcashDebt) = getPool(_token); uint256 _totalSupply = monoXPool.totalSupplyOf(pool.pid); liquidityIn = monoXPool.balanceOf(to, pool.pid)>liquidity?liquidity:monoXPool.balanceOf(to, pool.pid); uint256 tokenReserve = IERC20(_token).balanceOf(address(monoXPool)); if(tokenReserve < pool.tokenBalance){ tokenBalanceVcashValue = tokenReserve.mul(pool.price)/1e18; } if(vcashDebt>0){ tokenReserve = (tokenBalanceVcashValue.sub(vcashDebt)).mul(1e18).div(pool.price); } // if vcashCredit==0, vcashOut will be 0 as well vcashOut = liquidityIn.mul(vcashCredit).div(_totalSupply); tokenOut = liquidityIn.mul(tokenReserve).div(_totalSupply); } // actually removes liquidity function removeLiquidity (address _token, uint256 liquidity, address to, uint256 minVcashOut, uint256 minTokenOut) external returns(uint256 vcashOut, uint256 tokenOut) { (vcashOut, tokenOut) = _removeLiquidityHelper (_token, liquidity, to, minVcashOut, minTokenOut, false); } // actually removes liquidity function _removeLiquidityHelper (address _token, uint256 liquidity, address to, uint256 minVcashOut, uint256 minTokenOut, bool isETH) lockToken(_token) internal returns(uint256 vcashOut, uint256 tokenOut) { require (tokenPoolStatus[_token]==1, "MonoX:NO_TOKEN"); PoolInfo memory pool = pools[_token]; uint256 poolValue; uint256 liquidityIn; (poolValue, liquidityIn, vcashOut, tokenOut) = _removeLiquidity(_token, liquidity, to); _mintFee(pool.pid, pool.lastPoolValue, poolValue); require (vcashOut>=minVcashOut, "MonoX:INSUFF_vCash"); require (tokenOut>=minTokenOut, "MonoX:INSUFF_TOKEN"); if (vcashOut>0){ vCash.mint(to, vcashOut); } if (!isETH) { monoXPool.safeTransferERC20Token(_token, to, tokenOut); } else { monoXPool.withdrawWETH(tokenOut); monoXPool.safeTransferETH(to, tokenOut); } monoXPool.burn(to, pool.pid, liquidityIn); _syncPoolInfo(_token, 0, vcashOut); emit RemoveLiquidity(to, pool.pid, _token, liquidityIn, vcashOut, tokenOut, pool.price); } // actually removes ETH liquidity function removeLiquidityETH (uint256 liquidity, address to, uint256 minVcashOut, uint256 minTokenOut) external returns(uint256 vcashOut, uint256 tokenOut) { (vcashOut, tokenOut) = _removeLiquidityHelper (WETH, liquidity, to, minVcashOut, minTokenOut, true); } // util func to compute new price function _getNewPrice (uint256 originalPrice, uint256 reserve, uint256 delta, uint256 deltaBlocks, TxType txType) pure internal returns(uint256 price) { if(txType==TxType.SELL) { // no risk of being div by 0 price = originalPrice.mul(reserve)/(reserve.add(delta)); }else{ // BUY price = originalPrice.mul(reserve).div(reserve.sub(delta)); } } // util func to compute new price function _getAvgPrice (uint256 originalPrice, uint256 newPrice) pure internal returns(uint256 price) { price = originalPrice.add(newPrice.mul(4))/5; } // standard swap interface implementing uniswap router V2 function swapExactETHForToken( address tokenOut, uint amountOutMin, address to, uint deadline ) external virtual payable ensure(deadline) returns (uint amountOut) { uint amountIn = msg.value; MonoXLibrary.safeTransferETH(address(monoXPool), amountIn); monoXPool.depositWETH(amountIn); amountOut = swapIn(WETH, tokenOut, address(this), to, amountIn); require(amountOut >= amountOutMin, 'MonoX:INSUFF_OUTPUT'); } function swapExactTokenForETH( address tokenIn, uint amountIn, uint amountOutMin, address to, uint deadline ) external virtual ensure(deadline) returns (uint amountOut) { IMonoXPool monoXPoolLocal = monoXPool; amountOut = swapIn(tokenIn, WETH, msg.sender, address(monoXPoolLocal), amountIn); require(amountOut >= amountOutMin, 'MonoX:INSUFF_OUTPUT'); monoXPoolLocal.withdrawWETH(amountOut); monoXPoolLocal.safeTransferETH(to, amountOut); } function swapETHForExactToken( address tokenOut, uint amountInMax, uint amountOut, address to, uint deadline ) external virtual payable ensure(deadline) returns (uint amountIn) { uint amountSentIn = msg.value; ( , , amountIn, ) = getAmountIn(WETH, tokenOut, amountOut); MonoXLibrary.safeTransferETH(address(monoXPool), amountIn); monoXPool.depositWETH(amountIn); amountIn = swapOut(WETH, tokenOut, address(this), to, amountOut); require(amountIn <= amountSentIn, 'MonoX:BAD_INPUT'); require(amountIn <= amountInMax, 'MonoX:EXCESSIVE_INPUT'); if (amountSentIn > amountIn) { MonoXLibrary.safeTransferETH(msg.sender, amountSentIn.sub(amountIn)); } } function swapTokenForExactETH( address tokenIn, uint amountInMax, uint amountOut, address to, uint deadline ) external virtual ensure(deadline) returns (uint amountIn) { IMonoXPool monoXPoolLocal = monoXPool; amountIn = swapOut(tokenIn, WETH, msg.sender, address(monoXPoolLocal), amountOut); require(amountIn <= amountInMax, 'MonoX:EXCESSIVE_INPUT'); monoXPoolLocal.withdrawWETH(amountOut); monoXPoolLocal.safeTransferETH(to, amountOut); } function swapExactTokenForToken( address tokenIn, address tokenOut, uint amountIn, uint amountOutMin, address to, uint deadline ) external virtual ensure(deadline) returns (uint amountOut) { amountOut = swapIn(tokenIn, tokenOut, msg.sender, to, amountIn); require(amountOut >= amountOutMin, 'MonoX:INSUFF_OUTPUT'); } function swapTokenForExactToken( address tokenIn, address tokenOut, uint amountInMax, uint amountOut, address to, uint deadline ) external virtual ensure(deadline) returns (uint amountIn) { amountIn = swapOut(tokenIn, tokenOut, msg.sender, to, amountOut); require(amountIn <= amountInMax, 'MonoX:EXCESSIVE_INPUT'); } // util func to manipulate vcash balance function _updateVcashBalance (address _token, uint _vcashIn, uint _vcashOut) internal returns (uint _vcashCredit, uint _vcashDebt) { if(_vcashIn>_vcashOut){ _vcashIn = _vcashIn - _vcashOut; _vcashOut = 0; }else{ _vcashOut = _vcashOut - _vcashIn; _vcashIn = 0; } // PoolInfo memory _pool = pools[_token]; uint _poolVcashCredit = pools[_token].vcashCredit; uint _poolVcashDebt = pools[_token].vcashDebt; PoolStatus _poolStatus = pools[_token].status; if(_vcashOut>0){ (_vcashCredit, _vcashDebt) = MonoXLibrary.vcashBalanceSub( _poolVcashCredit, _poolVcashDebt, _vcashOut); require(_vcashCredit <= uint112(-1) && _vcashDebt <= uint112(-1)); pools[_token].vcashCredit = uint112(_vcashCredit); pools[_token].vcashDebt = uint112(_vcashDebt); } if(_vcashIn>0){ (_vcashCredit, _vcashDebt) = MonoXLibrary.vcashBalanceAdd( _poolVcashCredit, _poolVcashDebt, _vcashIn); require(_vcashCredit <= uint112(-1) && _vcashDebt <= uint112(-1)); pools[_token].vcashCredit = uint112(_vcashCredit); pools[_token].vcashDebt = uint112(_vcashDebt); } if(_poolStatus == PoolStatus.LISTED){ require (_vcashDebt<=tokenInsurance[_token], "MonoX:INSUFF_vCash"); } } // updates pool token balance and price. function _updateTokenInfo (address _token, uint256 _price, uint256 _vcashIn, uint256 _vcashOut, uint256 _ETHDebt) internal { uint256 _balance = IERC20(_token).balanceOf(address(monoXPool)); _balance = _balance.sub(_ETHDebt); require(pools[_token].status!=PoolStatus.PAUSED,"MonoX:PAUSED"); require(_balance <= uint112(-1)); (uint initialPoolValue, , ,) = getPool(_token); pools[_token].tokenBalance = uint112(_balance); pools[_token].price = _price; // record last trade's block number in mapping: lastTradedBlock lastTradedBlock[_token] = block.number; _updateVcashBalance(_token, _vcashIn, _vcashOut); (uint poolValue, , ,) = getPool(_token); require(initialPoolValue <= poolValue || poolValue >= poolSizeMinLimit, "MonoX:MIN_POOL_SIZE"); } function directSwapAllowed(uint tokenInPoolPrice,uint tokenOutPoolPrice, uint tokenInPoolTokenBalance, uint tokenOutPoolTokenBalance, PoolStatus status, bool getsAmountOut) internal pure returns(bool){ uint tokenInValue = tokenInPoolTokenBalance.mul(tokenInPoolPrice).div(1e18); uint tokenOutValue = tokenOutPoolTokenBalance.mul(tokenOutPoolPrice).div(1e18); bool priceExists = getsAmountOut?tokenInPoolPrice>0:tokenOutPoolPrice>0; // only if it's official pool with similar size return priceExists&&status==PoolStatus.OFFICIAL&&tokenInValue>0&&tokenOutValue>0&& ((tokenInValue/tokenOutValue)+(tokenOutValue/tokenInValue)==1); } // view func to compute amount required for tokenIn to get fixed amount of tokenOut function getAmountIn(address tokenIn, address tokenOut, uint256 amountOut) public view returns (uint256 tokenInPrice, uint256 tokenOutPrice, uint256 amountIn, uint256 tradeVcashValue) { require(amountOut > 0, 'MonoX:INSUFF_INPUT'); uint256 amountOutWithFee = amountOut.mul(1e5).div(1e5 - fees); address vcashAddress = address(vCash); uint tokenOutPoolPrice = pools[tokenOut].price; uint tokenOutPoolTokenBalance = pools[tokenOut].tokenBalance; if(tokenOut==vcashAddress){ tradeVcashValue = amountOutWithFee; tokenOutPrice = 1e18; }else{ require (tokenPoolStatus[tokenOut]==1, "MonoX:NO_POOL"); // PoolInfo memory tokenOutPool = pools[tokenOut]; PoolStatus tokenOutPoolStatus = pools[tokenOut].status; require (tokenOutPoolStatus != PoolStatus.UNLISTED, "MonoX:POOL_UNLST"); tokenOutPrice = _getNewPrice(tokenOutPoolPrice, tokenOutPoolTokenBalance, amountOutWithFee, 0, TxType.BUY); tradeVcashValue = _getAvgPrice(tokenOutPoolPrice, tokenOutPrice).mul(amountOutWithFee)/1e18; } if(tokenIn==vcashAddress){ amountIn = tradeVcashValue; tokenInPrice = 1e18; }else{ require (tokenPoolStatus[tokenIn]==1, "MonoX:NO_POOL"); // PoolInfo memory tokenInPool = pools[tokenIn]; PoolStatus tokenInPoolStatus = pools[tokenIn].status; uint tokenInPoolPrice = pools[tokenIn].price; uint tokenInPoolTokenBalance = pools[tokenIn].tokenBalance; require (tokenInPoolStatus != PoolStatus.UNLISTED, "MonoX:POOL_UNLST"); amountIn = tradeVcashValue.add(tokenInPoolTokenBalance.mul(tokenInPoolPrice).div(1e18)); amountIn = tradeVcashValue.mul(tokenInPoolTokenBalance).div(amountIn); bool allowDirectSwap=directSwapAllowed(tokenInPoolPrice,tokenOutPoolPrice,tokenInPoolTokenBalance,tokenOutPoolTokenBalance,tokenInPoolStatus,false); // assuming p1*p2 = k, equivalent to uniswap's x * y = k uint directSwapTokenInPrice = allowDirectSwap?tokenOutPoolPrice.mul(tokenInPoolPrice).div(tokenOutPrice):1; tokenInPrice = _getNewPrice(tokenInPoolPrice, tokenInPoolTokenBalance, amountIn, 0, TxType.SELL); tokenInPrice = directSwapTokenInPrice > tokenInPrice?directSwapTokenInPrice:tokenInPrice; amountIn = tradeVcashValue.mul(1e18).div(_getAvgPrice(tokenInPoolPrice, tokenInPrice)); } } // view func to compute amount required for tokenOut to get fixed amount of tokenIn function getAmountOut(address tokenIn, address tokenOut, uint256 amountIn) public view returns (uint256 tokenInPrice, uint256 tokenOutPrice, uint256 amountOut, uint256 tradeVcashValue) { require(amountIn > 0, 'MonoX:INSUFF_INPUT'); uint256 amountInWithFee = amountIn.mul(1e5-fees)/1e5; address vcashAddress = address(vCash); uint tokenInPoolPrice = pools[tokenIn].price; uint tokenInPoolTokenBalance = pools[tokenIn].tokenBalance; if(tokenIn==vcashAddress){ tradeVcashValue = amountInWithFee; tokenInPrice = 1e18; }else{ require (tokenPoolStatus[tokenIn]==1, "MonoX:NO_POOL"); // PoolInfo memory tokenInPool = pools[tokenIn]; PoolStatus tokenInPoolStatus = pools[tokenIn].status; require (tokenInPoolStatus != PoolStatus.UNLISTED, "MonoX:POOL_UNLST"); tokenInPrice = _getNewPrice(tokenInPoolPrice, tokenInPoolTokenBalance, amountInWithFee, 0, TxType.SELL); tradeVcashValue = _getAvgPrice(tokenInPoolPrice, tokenInPrice).mul(amountInWithFee)/1e18; } if(tokenOut==vcashAddress){ amountOut = tradeVcashValue; tokenOutPrice = 1e18; }else{ require (tokenPoolStatus[tokenOut]==1, "MonoX:NO_POOL"); // PoolInfo memory tokenOutPool = pools[tokenOut]; PoolStatus tokenOutPoolStatus = pools[tokenOut].status; uint tokenOutPoolPrice = pools[tokenOut].price; uint tokenOutPoolTokenBalance = pools[tokenOut].tokenBalance; require (tokenOutPoolStatus != PoolStatus.UNLISTED, "MonoX:POOL_UNLST"); amountOut = tradeVcashValue.add(tokenOutPoolTokenBalance.mul(tokenOutPoolPrice).div(1e18)); amountOut = tradeVcashValue.mul(tokenOutPoolTokenBalance).div(amountOut); bool allowDirectSwap=directSwapAllowed(tokenInPoolPrice,tokenOutPoolPrice,tokenInPoolTokenBalance,tokenOutPoolTokenBalance,tokenOutPoolStatus,true); // assuming p1*p2 = k, equivalent to uniswap's x * y = k uint directSwapTokenOutPrice = allowDirectSwap?tokenInPoolPrice.mul(tokenOutPoolPrice).div(tokenInPrice):uint(-1); // prevent the attack where user can use a small pool to update price in a much larger pool tokenOutPrice = _getNewPrice(tokenOutPoolPrice, tokenOutPoolTokenBalance, amountOut, 0, TxType.BUY); tokenOutPrice = directSwapTokenOutPrice < tokenOutPrice?directSwapTokenOutPrice:tokenOutPrice; amountOut = tradeVcashValue.mul(1e18).div(_getAvgPrice(tokenOutPoolPrice, tokenOutPrice)); } } // swap from tokenIn to tokenOut with fixed tokenIn amount. function swapIn (address tokenIn, address tokenOut, address from, address to, uint256 amountIn) internal lockToken(tokenIn) returns(uint256 amountOut) { address monoXPoolLocal = address(monoXPool); amountIn = transferAndCheck(from,monoXPoolLocal,tokenIn,amountIn); // uint256 halfFeesInTokenIn = amountIn.mul(fees)/2e5; uint256 tokenInPrice; uint256 tokenOutPrice; uint256 tradeVcashValue; (tokenInPrice, tokenOutPrice, amountOut, tradeVcashValue) = getAmountOut(tokenIn, tokenOut, amountIn); uint256 oneSideFeesInVcash = tokenInPrice.mul(amountIn.mul(fees)/2e5)/1e18; // trading in if(tokenIn==address(vCash)){ vCash.burn(monoXPoolLocal, amountIn); // all fees go to the other side oneSideFeesInVcash = oneSideFeesInVcash.mul(2); }else{ _updateTokenInfo(tokenIn, tokenInPrice, 0, tradeVcashValue.add(oneSideFeesInVcash), 0); } // trading out if(tokenOut==address(vCash)){ vCash.mint(to, amountOut); }else{ if (to != monoXPoolLocal) { IMonoXPool(monoXPoolLocal).safeTransferERC20Token(tokenOut, to, amountOut); } _updateTokenInfo(tokenOut, tokenOutPrice, tradeVcashValue.add(oneSideFeesInVcash), 0, to == monoXPoolLocal ? amountOut : 0); } if(pools[tokenIn].vcashDebt > 0 && pools[tokenIn].status == PoolStatus.OFFICIAL){ _internalRebalance(tokenIn); } emit Swap(to, tokenIn, tokenOut, amountIn, amountOut, tradeVcashValue); } // swap from tokenIn to tokenOut with fixed tokenOut amount. function swapOut (address tokenIn, address tokenOut, address from, address to, uint256 amountOut) internal lockToken(tokenIn) returns(uint256 amountIn) { uint256 tokenInPrice; uint256 tokenOutPrice; uint256 tradeVcashValue; (tokenInPrice, tokenOutPrice, amountIn, tradeVcashValue) = getAmountIn(tokenIn, tokenOut, amountOut); address monoXPoolLocal = address(monoXPool); amountIn = transferAndCheck(from,monoXPoolLocal,tokenIn,amountIn); // uint256 halfFeesInTokenIn = amountIn.mul(fees)/2e5; uint256 oneSideFeesInVcash = tokenInPrice.mul(amountIn.mul(fees)/2e5)/1e18; // trading in if(tokenIn==address(vCash)){ vCash.burn(monoXPoolLocal, amountIn); // all fees go to buy side oneSideFeesInVcash = oneSideFeesInVcash.mul(2); }else { _updateTokenInfo(tokenIn, tokenInPrice, 0, tradeVcashValue.add(oneSideFeesInVcash), 0); } // trading out if(tokenOut==address(vCash)){ vCash.mint(to, amountOut); // all fees go to sell side _updateVcashBalance(tokenIn, oneSideFeesInVcash, 0); }else{ if (to != monoXPoolLocal) { IMonoXPool(monoXPoolLocal).safeTransferERC20Token(tokenOut, to, amountOut); } _updateTokenInfo(tokenOut, tokenOutPrice, tradeVcashValue.add(oneSideFeesInVcash), 0, to == monoXPoolLocal ? amountOut:0 ); } if(pools[tokenIn].vcashDebt > 0 && pools[tokenIn].status == PoolStatus.OFFICIAL){ _internalRebalance(tokenIn); } emit Swap(to, tokenIn, tokenOut, amountIn, amountOut, tradeVcashValue); } // function balanceOf(address account, uint256 id) public view returns (uint256) { // return monoXPool.balanceOf(account, id); // } function getConfig() public view returns (address _vCash, address _weth, address _feeTo, uint16 _fees, uint16 _devFee) { _vCash = address(vCash); _weth = WETH; _feeTo = feeTo; _fees = fees; _devFee = devFee; } function transferAndCheck(address from,address to,address _token,uint amount) internal returns (uint256){ if(from == address(this)){ return amount; // if it's ETH } // if it's not ETH if(tokenStatus[_token]==2){ IERC20(_token).safeTransferFrom(from, to, amount); return amount; }else{ uint256 balanceIn0 = IERC20(_token).balanceOf(to); IERC20(_token).safeTransferFrom(from, to, amount); uint256 balanceIn1 = IERC20(_token).balanceOf(to); return balanceIn1.sub(balanceIn0); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC1155.sol"; import "./IERC1155MetadataURI.sol"; import "./IERC1155Receiver.sol"; import "../../utils/Context.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using SafeMath for uint256; using Address for address; // Mapping from token ID to account balances mapping (uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; /** * @dev See {_setURI}. */ constructor (string memory uri_) public { _setURI(uri_); // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) external view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][from] = _balances[id][from].sub( amount, "ERC1155: insufficient balance for transfer" ); _balances[id][to] = _balances[id][to].add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = _balances[id][account].add(amount); emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * 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 _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]); } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn(address account, uint256 id, uint256 amount) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "ERC1155: burn amount exceeds balance" ); } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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; /** * @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 // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >= 0.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)); } } pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; interface IMonoXPool is IERC1155 { function mint (address account, uint256 id, uint256 amount) external; function burn (address account, uint256 id, uint256 amount) external; function totalSupplyOf(uint256 pid) external view returns (uint256); function depositWETH(uint256 amount) external; function withdrawWETH(uint256 amount) external; function safeTransferETH(address to, uint amount) external; function safeTransferERC20Token(address token, address to, uint256 amount) external; function WETH() external view returns (address); function liquidityLastAddedOf(uint256 pid, address account) external view returns(uint256); function topLPHolderOf(uint256 pid) external view returns (address); function mintLp(address account, uint256 id, uint256 amount, bool _isOfficial) external; function setWhitelist(address _whitelister, bool _isWhitelister) external; } pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; library MonoXLibrary { using SafeMath for uint; // from https://github.com/Uniswap/uniswap-lib/blob/master/contracts/libraries/TransferHelper.sol function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } // util func to manipulate vcash balance function vcashBalanceAdd (uint256 _credit, uint256 _debt, uint256 delta) internal pure returns (uint256 _newCredit, uint256 _newDebt) { if(_debt>0){ if(delta>_debt){ _newDebt = 0; _newCredit = _credit.add(delta - _debt); }else{ _newCredit = 0; _newDebt = _debt - delta; } }else{ _newCredit = _credit.add(delta); _newDebt = 0; } } // util func to manipulate vcash balance function vcashBalanceSub (uint256 _credit, uint256 _debt, uint256 delta) internal pure returns (uint256 _newCredit, uint256 _newDebt) { if(_credit>0){ if(delta>_credit){ _newCredit = 0; _newDebt = delta - _credit; }else{ _newCredit = _credit - delta; _newDebt = 0; } }else{ _newCredit = 0; _newDebt = _debt.add(delta); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../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 pragma solidity >=0.6.2 <0.8.0; import "./IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../introspection/IERC165.sol"; /** * _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 pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the 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.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; }
util func to compute new price no risk of being div by 0
function _getNewPrice (uint256 originalPrice, uint256 reserve, uint256 delta, uint256 deltaBlocks, TxType txType) pure internal returns(uint256 price) { if(txType==TxType.SELL) { price = originalPrice.mul(reserve)/(reserve.add(delta)); price = originalPrice.mul(reserve).div(reserve.sub(delta)); } }
12,003,011
// SPDX-License-Identifier: UNLICENSED pragma solidity >0.8.0; import "../interface/IBLSPoint.sol"; contract BGLS is IBLSPoint { G1 g1 = G1(1, 2); G2 g2 = G2( 0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed, 0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2, 0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa, 0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b ); function modPow(uint base, uint exponent, uint modulus) internal returns (uint) { uint[6] memory input = [32, 32, 32, base, exponent, modulus]; uint[1] memory result; assembly { if iszero(call(not(0), 0x05, 0, input, 0xc0, result, 0x20)) { revert(0, 0) } } return result[0]; } function addPoints(G1 memory a, G1 memory b) public returns (G1 memory) { uint[4] memory input = [a.x, a.y, b.x, b.y]; uint[2] memory result; assembly { if iszero(call(not(0), 0x06, 0, input, 0x80, result, 0x40)) { revert(0, 0) } } return G1(result[0], result[1]); } function chkBit(bytes memory b, uint x) internal pure returns (bool) { return uint(uint8(b[x / 8])) & (uint(1) << (x % 8)) != 0; } function sumPoints(G1[] memory points, bytes memory indices) public returns (G1 memory) { G1 memory acc = G1(0, 0); for (uint i = 0; i < points.length; i++) { if (chkBit(indices, i)) { acc = addPoints(acc, points[i]); } } return G1(acc.x, acc.y); } // kP function scalarMultiply(G1 memory point, uint scalar) public returns (G1 memory) { uint[3] memory input = [point.x, point.y, scalar]; uint[2] memory result; assembly { if iszero(call(not(0), 0x07, 0, input, 0x60, result, 0x40)) { revert(0, 0) } } return G1(result[0], result[1]); } //returns e(a,x) == e(b,y) function pairingCheck(G1 memory a, G2 memory x, G1 memory b, G2 memory y) public returns (bool) { uint[12] memory input = [a.x, a.y, x.xi, x.xr, x.yi, x.yr, b.x, prime - b.y, y.xi, y.xr, y.yi, y.yr]; uint[1] memory result; assembly { if iszero(call(not(0), 0x08, 0, input, 0x180, result, 0x20)) { revert(0, 0) } } return result[0] == 1; } // compatible with https://github.com/dusk-network/dusk-crypto/blob/master/bls/bls.go#L138-L148 // which is used in github.com/mapprotocol/atlas // https://github.com/mapprotocol/atlas/blob/main/helper/bls/bn256.go#L84-L94 // todo by long: we might need a better way to hash to G1 function hashToG1(bytes memory message) public returns (G1 memory) { uint h = uint(keccak256(abi.encodePacked(message))) % order; return scalarMultiply(g1, h); } uint prime = 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47; uint order = 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001; uint pminus = 21888242871839275222246405745257275088696311157297823662689037894645226208582; uint pplus = 21888242871839275222246405745257275088696311157297823662689037894645226208584; // function hashToG1(uint[] memory b) internal returns (G1 memory) { // uint x = 0; // G1 memory res; // while (true) { // uint hx = uint(keccak256(abi.encodePacked(b, x))) % prime; // uint px = (modPow(hx, 3, prime) + 3); // y^2 = x^3 % p + 3 // if (modPow(px, pminus / 2, prime) == 1) {// determine if px is a quadratic residue, === 1 means yes // refer to https://mathworld.wolfram.com/QuadraticResidue.html // prime is a special form of 4k+3, // where k = 5472060717959818805561601436314318772174077789324455915672259473661306552145 // then x of x^2 = q (mod p) can be solved with x = q^(k+1) mod p, where k = (p - 3) / 4, k + 1 = (p + 1) / 4 // uint py = modPow(px, pplus / 4, prime); // // res = uint(keccak256(abi.encodePacked(b, uint(255)))) % 2 == 0 ? G1(hx, py) : G1(hx, prime - py); // break; // } // x++; // } // return res; // } function checkSignature(bytes memory message, G1 memory sig, G2 memory aggKey) public returns (bool) { return pairingCheck(sig, g2, hashToG1(message), aggKey); } }
compatible with https:github.com/dusk-network/dusk-crypto/blob/master/bls/bls.goL138-L148 which is used in github.com/mapprotocol/atlas https:github.com/mapprotocol/atlas/blob/main/helper/bls/bn256.goL84-L94 todo by long: we might need a better way to hash to G1
function hashToG1(bytes memory message) public returns (G1 memory) { uint h = uint(keccak256(abi.encodePacked(message))) % order; return scalarMultiply(g1, h); } uint prime = 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47; uint order = 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001; uint pminus = 21888242871839275222246405745257275088696311157297823662689037894645226208582; uint pplus = 21888242871839275222246405745257275088696311157297823662689037894645226208584;
13,049,743
pragma solidity 0.4.24; import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol"; import "../interfaces/IModuleContract.sol"; import "../inheritables/TransferValidator.sol"; /** * @title LockUpPeriodValidator * TransferValidator where Owner sets the time when a LockUp period ends. All transfers fail until that time is reached. */ contract LockUpPeriodValidator is TransferValidator, IModuleContract, Pausable { /*----------- Constants -----------*/ bytes32 public constant moduleName = "LockUpPeriodValidator"; /*----------- Globals -----------*/ uint256 public openingTime_; /*----------- Events -----------*/ event LogSetOpeningTime(address indexed sender, uint newOpeningTime); /** * @dev Constructor for contract * @param _openingTime blocktime at which trading can start */ constructor( uint _openingTime ) public { setOpeningTime_(_openingTime); } /*----------- Validator Methods -----------*/ /** * @dev Validate whether a trade will occur before the specified openingTime * @param _token address token we are checking * @param _to address The address which you want to transfer to * @param _from address The Address which you want to transfer from * @param _amount uint256 The Amount of tokens being transferred * @return bool */ function canSend( address _token, address _from, address _to, uint256 _amount ) external returns(bool) { return (openingTime_ <= block.timestamp); } /*----------- Internal Methods -----------*/ function setOpeningTime_(uint _openingTime) internal { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); openingTime_ = _openingTime; } /*----------- Setter Methods -----------*/ /** * @dev Sets OpeningTime, * @param _openingTime desired opening time * @return uint newOpeningTime */ function setOpeningTime(uint _openingTime) external onlyOwner whenNotPaused returns (uint newOpeningTime) { setOpeningTime_(_openingTime); emit LogSetOpeningTime(msg.sender, openingTime_); return openingTime_; } /*----------- Getter Methods -----------*/ /** * @dev Returns the name of the validator * @return bytes32 */ function getName() external view returns(bytes32) { return moduleName; } /** * @dev Returns the type of the validator * @return uint8 */ function getType() external view returns(uint8) { return moduleType; } /** * @dev Returns the investorMin of the validator * @return uint */ function openingTime() external view returns(uint) { return openingTime_; } }
----------- Setter Methods -----------/ Sets OpeningTime, _openingTime desired opening time return uint newOpeningTime/
function setOpeningTime(uint _openingTime) external onlyOwner whenNotPaused returns (uint newOpeningTime) { setOpeningTime_(_openingTime); emit LogSetOpeningTime(msg.sender, openingTime_); return openingTime_; }
12,833,670
./partial_match/1/0x3139059D0b23e88c5BA7E17cDC21cd6A860CB8bE/sources/ElonTweetCoin.sol
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, uint subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; }
4,246,173
pragma solidity ^0.4.11; import "github.com/oraclize/ethereum-api/oraclizeAPI.sol"; contract SmartDice is usingOraclize { string public lastRoll; string public lastPrice; address owner; event diceRolled(uint value); function SmartDice() payable { rollDice(); owner = msg.sender; } function __callback(bytes32 myid, string result) { if (msg.sender != oraclize_cbAddress()) throw; lastRoll = result; diceRolled(parseInt(lastRoll)); } function rollDice() payable returns (bool) { // Retrieve price for oraclize query uint oraclizePrice = oraclize_getPrice("WolframAlpha"); // Check the price is covered by the transaction if (msg.value < oraclizePrice) { return false; } // Update last lastPrice lastPrice = uint2str(oraclizePrice); // Call WolframAlpha via Oraclize to roll the dice oraclize_query("WolframAlpha", "random number between 1 and 6"); return true; } function withdraw(uint amount) returns (bool) { // Only the owner may withdraw if (msg.sender != owner) { return false; } // Sanity check balance if (amount > this.balance) { return false; } // Try to send, throw if if (!msg.sender.send(amount)) { return false; } return true; } }
Retrieve price for oraclize query Check the price is covered by the transaction
function rollDice() payable returns (bool) { uint oraclizePrice = oraclize_getPrice("WolframAlpha"); if (msg.value < oraclizePrice) { return false; } return true; }
15,863,539
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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. */ 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. */ 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. */ 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. */ 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. */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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); } /** * @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"); } } } pragma experimental ABIEncoderV2; struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 rateLimit; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } interface VaultAPI is IERC20 { function apiVersion() external view returns (string memory); function withdraw(uint256 shares, address recipient) external; function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); } /** * This interface is here for the keeper bot to use. */ interface StrategyAPI { function apiVersion() external pure returns (string memory); function isActive() external view returns (bool); function delegatedAssets() external virtual view returns (uint256); function name() external view returns (string memory); function vault() external view returns (address); function keeper() external view returns (address); function tendTrigger(uint256 callCost) external view returns (bool); function tend() external; function harvestTrigger(uint256 callCost) external view returns (bool); function harvest() external; event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); } /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.3.0"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external virtual view returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external virtual view returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay = 86400; // ~ once a day // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor = 100; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold = 0; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require(msg.sender == keeper || msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. */ constructor(address _vault) public { vault = VaultAPI(_vault); want = IERC20(vault.token()); want.approve(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = msg.sender; rewards = msg.sender; keeper = msg.sender; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. Any distributed rewards will cease flowing * to the old address and begin flowing to this address once the change * is in effect. * * This may only be called by the strategist. * @param _rewards The address to use for collecting rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); rewards = _rewards; emit UpdatedRewards(_rewards); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public virtual view returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds). This function is used during emergency exit instead of * `prepareReturn()` to liquidate all of the Strategy's positions back to the Vault. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * `Harvest()` calls this function after shares are created during * `vault.report()`. You can customize this function to any share * distribution mechanism you want. * * See `vault.report()` for further details. */ function distributeRewards() internal virtual { // Transfer 100% of newly-minted shares awarded to this contract to the rewards address. uint256 balance = vault.balanceOf(address(this)); if (balance > 0) { vault.transfer(rewards, balance); } } /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCost The keeper's estimated cast cost to call `tend()`. * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCost) public virtual view returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `tendTrigger` should never return `true` at the * same time. * * See `maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCost The keeper's estimated cast cost to call `harvest()`. * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCost) public virtual view returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 totalAssets = estimatedTotalAssets(); // NOTE: use the larger of total assets or debt outstanding to book losses properly (debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding); // NOTE: take up any remainder here as profit if (debtPayment > debtOutstanding) { profit = debtPayment.sub(debtOutstanding); debtPayment = debtOutstanding; } } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. debtOutstanding = vault.report(profit, loss, debtPayment); // Distribute any reward shares earned by the strategy on this report distributeRewards(); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amount` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.transfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by governance or the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault) || msg.sender == governance()); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.transfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } */ function protectedTokens() internal virtual view returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).transfer(governance(), IERC20(_token).balanceOf(address(this))); } } interface MMVault { function token() external view returns (address); function getRatio() external view returns (uint256); function deposit(uint256) external; function withdraw(uint256) external; function withdrawAll() external; function earn() external; function balance() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address _user) external view returns (uint256); } interface MMStrategy { function harvest() external; } interface MMFarmingPool { function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function userInfo(uint256, address) external view returns (uint256 amount, uint256 rewardDebt); function pendingMM(uint256 _pid, address _user) external view returns (uint256); } interface IUni{ function getAmountsOut( uint256 amountIn, address[] calldata path ) external view returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } /** * @title Strategy for Mushrooms WBTC vault/farming pool yield * @author Mushrooms Finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address constant public wbtc = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); //wbtc address constant public mm = address(0xa283aA7CfBB27EF0cfBcb2493dD9F4330E0fd304); //MM address public constant usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; //USDC address constant public unirouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address constant public sushiroute = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); address constant public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address constant public mmVault = address(0xb06661A221Ab2Ec615531f9632D6Dc5D2984179A);// Mushrooms mWBTC vault address constant public mmFarmingPool = address(0xf8873a6080e8dbF41ADa900498DE0951074af577); //Mushrooms mining MasterChef uint256 constant public mmFarmingPoolId = 11; // Mushrooms farming pool id for mWBTC uint256 public minMMToSwap = 1; // min $MM to swap during adjustPosition() /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external override view returns (string memory){ return "StratMushroomsytWBTCV1"; } /** * @notice * Initializes the Strategy, this is called only once, when the contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. */ constructor(address _vault) BaseStrategy(_vault) public { require(address(want) == wbtc, '!wrongVault'); want.safeApprove(mmVault, uint256(-1)); IERC20(mmVault).safeApprove(mmFarmingPool, uint256(-1)); IERC20(mm).safeApprove(unirouter, uint256(-1)); IERC20(mm).safeApprove(sushiroute, uint256(-1)); } function setMinMMToSwap(uint256 _minMMToSwap) external onlyAuthorized { minMMToSwap = _minMMToSwap; } /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external override view returns (uint256) { return 0; } /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public override view returns (uint256){ (uint256 _mToken, ) = MMFarmingPool(mmFarmingPool).userInfo(mmFarmingPoolId, address(this)); uint256 _mmVault = IERC20(mmVault).balanceOf(address(this)); return _convertMTokenToWant(_mToken.add(_mmVault)).add(want.balanceOf(address(this))); } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ){ // Pay debt if any if (_debtOutstanding > 0) { (uint256 _amountFreed, uint256 _reportLoss) = liquidatePosition(_debtOutstanding); _debtPayment = _amountFreed > _debtOutstanding? _debtOutstanding : _amountFreed; _loss = _reportLoss; } // Claim profit uint256 _pendingMM = MMFarmingPool(mmFarmingPool).pendingMM(mmFarmingPoolId, address(this)); if (_pendingMM > 0){ MMFarmingPool(mmFarmingPool).withdraw(mmFarmingPoolId, 0); } _profit = _disposeOfMM(); return (_profit, _loss, _debtPayment); } /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal override{ //emergency exit is dealt with in prepareReturn if (emergencyExit) { return; } uint256 _before = IERC20(mmVault).balanceOf(address(this)); uint256 _after = _before; uint256 _want = want.balanceOf(address(this)); if (_want > _debtOutstanding) { _want = _want.sub(_debtOutstanding); MMVault(mmVault).deposit(_want); _after = IERC20(mmVault).balanceOf(address(this)); require(_after > _before, '!mismatchDepositIntoMushrooms'); } else if(_debtOutstanding > _want){ return; } if (_after > 0){ MMFarmingPool(mmFarmingPool).deposit(mmFarmingPoolId, _after); } } /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds). This function is used during emergency exit instead of * `prepareReturn()` to liquidate all of the Strategy's positions back to the Vault. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss){ bool liquidateAll = _amountNeeded >= estimatedTotalAssets()? true : false; if (liquidateAll){ (uint256 _mToken, ) = MMFarmingPool(mmFarmingPool).userInfo(mmFarmingPoolId, address(this)); MMFarmingPool(mmFarmingPool).withdraw(mmFarmingPoolId, _mToken); MMVault(mmVault).withdraw(IERC20(mmVault).balanceOf(address(this))); _liquidatedAmount = IERC20(want).balanceOf(address(this)); return (_liquidatedAmount, _liquidatedAmount < vault.strategies(address(this)).totalDebt? vault.strategies(address(this)).totalDebt.sub(_liquidatedAmount) : 0); } else{ uint256 _before = IERC20(want).balanceOf(address(this)); if (_before < _amountNeeded){ uint256 _gap = _amountNeeded.sub(_before); uint256 _mShare = _gap.mul(1e18).div(MMVault(mmVault).getRatio()); uint256 _mmVault = IERC20(mmVault).balanceOf(address(this)); if (_mmVault < _mShare){ uint256 _mvGap = _mShare.sub(_mmVault); (uint256 _mToken, ) = MMFarmingPool(mmFarmingPool).userInfo(mmFarmingPoolId, address(this)); require(_mToken >= _mvGap, '!insufficientMTokenInMasterChef'); MMFarmingPool(mmFarmingPool).withdraw(mmFarmingPoolId, _mvGap); } MMVault(mmVault).withdraw(_mShare); uint256 _after = IERC20(want).balanceOf(address(this)); require(_after > _before, '!mismatchMushroomsVaultWithdraw'); return (_after, _amountNeeded > _after? _amountNeeded.sub(_after): 0); } else{ return (_amountNeeded, _loss); } } } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `tendTrigger` should never return `true` at the * same time. * * See `maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCost The keeper's estimated cast cost to call `harvest()`. * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCost) public view override returns (bool) { return super.harvestTrigger(ethToWant(callCost)); } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal override{ (uint256 _mToken, ) = MMFarmingPool(mmFarmingPool).userInfo(mmFarmingPoolId, address(this)); MMFarmingPool(mmFarmingPool).withdraw(mmFarmingPoolId, _mToken); uint256 _mmVault = IERC20(mmVault).balanceOf(address(this)); if (_mmVault > 0){ IERC20(mmVault).safeTransfer(_newStrategy, _mmVault); } uint256 _mm = IERC20(mm).balanceOf(address(this)); if (_mm > 0){ IERC20(mm).safeTransfer(_newStrategy, _mm); } } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } */ function protectedTokens() internal override view returns (address[] memory){ address[] memory protected = new address[](1); protected[0] = mmVault; return protected; } function _convertMTokenToWant(uint256 _shares) internal view returns (uint256){ uint256 _mTokenTotal = IERC20(mmVault).totalSupply(); uint256 _wantInVault = MMVault(mmVault).balance(); return (_wantInVault.mul(_shares)).div(_mTokenTotal); } // swap $MM for $WBTC function _disposeOfMM() internal returns (uint256){ uint256 _mm = IERC20(mm).balanceOf(address(this)); uint256 _wantProfit; if (_mm >= minMMToSwap) { // intuitively in favor of sushiswap over uniswap if possible for better efficiency and cost address[] memory pathSushi = new address[](3); pathSushi[0] = mm; pathSushi[1] = weth; pathSushi[2] = wbtc; uint256 outputSushi = IUni(sushiroute).getAmountsOut(_mm, pathSushi)[pathSushi.length - 1]; address[] memory pathUni = new address[](4); pathUni[0] = mm; pathUni[1] = usdc; pathUni[2] = weth; pathUni[3] = wbtc; uint256 outputUni = IUni(unirouter).getAmountsOut(_mm, pathUni)[pathUni.length - 1]; uint256 _want = want.balanceOf(address(this)); if (outputSushi >= outputUni){ IUni(sushiroute).swapExactTokensForTokens(_mm, uint256(0), pathSushi, address(this), now); } else{ IUni(unirouter).swapExactTokensForTokens(_mm, uint256(0), pathUni, address(this), now); } _wantProfit = want.balanceOf(address(this)).sub(_want); } return _wantProfit; } function ethToWant(uint256 _amount) public view returns (uint256) { if (_amount == 0) { return 0; } address[] memory path = new address[](2); path[0] = weth; path[1] = wbtc; uint256[] memory amounts = IUni(unirouter).getAmountsOut(_amount, path); return amounts[amounts.length - 1]; } }
Used to change `strategist`. This may only be called by governance or the existing strategist. _strategist The new address to assign as `strategist`./
function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); }
7,747
// 0.4.20+commit.3155dd80.Emscripten.clang pragma solidity ^0.4.20; /** * Ethereum Token callback */ interface tokenRecipient { function receiveApproval( address from, uint256 value, bytes data ) external; } /** * ERC223 callback */ interface ContractReceiver { function tokenFallback( address from, uint value, bytes data ) external; } /** * Ownable Contract */ contract Owned { address public owner; function owned() public { owner = msg.sender; } function changeOwner(address _newOwner) public onlyOwner { owner = _newOwner; } modifier onlyOwner { require (msg.sender == owner); _; } } /** * ERC20 token with added ERC223 and Ethereum-Token support * * Blend of multiple interfaces: * - https://theethereum.wiki/w/index.php/ERC20_Token_Standard * - https://www.ethereum.org/token (uncontrolled, non-standard) * - https://github.com/Dexaran/ERC23-tokens/blob/Recommended/ERC223_Token.sol */ contract Token is Owned { string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; mapping( address => uint256 ) balances; mapping( address => mapping(address => uint256) ) allowances; /** * ERC20 Approval Event */ event Approval( address indexed owner, address indexed spender, uint value ); /** * ERC20-compatible version only, breaks ERC223 compliance but block * explorers and exchanges expect ERC20. Also, cannot overload events */ event Transfer( address indexed from, address indexed to, uint256 value ); function Token( uint256 _initialSupply, string _tokenName, string _tokenSymbol ) public { totalSupply = _initialSupply * 10**18; balances[msg.sender] = _initialSupply * 10**18; name = _tokenName; symbol = _tokenSymbol; } /** * ERC20 Balance Of Function */ function balanceOf( address owner ) public constant returns (uint) { return balances[owner]; } /** * ERC20 Approve Function */ function approve( address spender, uint256 value ) public returns (bool success) { // WARNING! When changing the approval amount, first set it back to zero // AND wait until the transaction is mined. Only afterwards set the new // amount. Otherwise you may be prone to a race condition attack. // See: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 allowances[msg.sender][spender] = value; Approval( msg.sender, spender, value ); return true; } /** * Recommended fix for known attack on any ERC20 */ function safeApprove( address _spender, uint256 _currentValue, uint256 _value ) public returns (bool success) { // If current allowance for _spender is equal to _currentValue, then // overwrite it with _value and return true, otherwise return false. if (allowances[msg.sender][_spender] == _currentValue) return approve(_spender, _value); return false; } /** * ERC20 Allowance Function */ function allowance( address owner, address spender ) public constant returns (uint256 remaining) { return allowances[owner][spender]; } /** * ERC20 Transfer Function */ function transfer( address to, uint256 value ) public returns (bool success) { bytes memory empty; // null _transfer( msg.sender, to, value, empty ); return true; } /** * ERC20 Transfer From Function */ function transferFrom( address from, address to, uint256 value ) public returns (bool success) { require( value <= allowances[from][msg.sender] ); allowances[from][msg.sender] -= value; bytes memory empty; _transfer( from, to, value, empty ); return true; } /** * Ethereum Token Approve and Call Function */ function approveAndCall( address spender, uint256 value, bytes context ) public returns (bool success) { if (approve(spender, value)) { tokenRecipient recip = tokenRecipient(spender); if (isContract(recip)) recip.receiveApproval(msg.sender, value, context); return true; } return false; } /** * ERC223 Transfer and invoke specified callback */ function transfer( address to, uint value, bytes data, string custom_fallback ) public returns (bool success) { _transfer( msg.sender, to, value, data ); // throws if custom_fallback is not a valid contract call require( address(to).call.value(0)( bytes4(keccak256(custom_fallback)), msg.sender, value, data ) ); return true; } /** * ERC223 Transfer to a contract or externally-owned account */ function transfer( address to, uint value, bytes data ) public returns (bool success) { if (isContract(to)) { return transferToContract( to, value, data ); } _transfer( msg.sender, to, value, data ); return true; } /** * ERC223 Transfer to contract and invoke tokenFallback() method */ function transferToContract( address to, uint value, bytes data ) private returns (bool success) { _transfer( msg.sender, to, value, data ); ContractReceiver rx = ContractReceiver(to); if (isContract(rx)) { rx.tokenFallback( msg.sender, value, data ); return true; } return false; } /** * ERC223 fetch contract size (must be nonzero to be a contract) */ function isContract(address _addr) private constant returns (bool) { uint length; assembly { length := extcodesize(_addr) } return (length > 0); } /** * Transfer Functionality */ function _transfer( address from, address to, uint value, bytes data ) internal { require( to != 0x0 ); require( balances[from] >= value ); require( balances[to] + value > balances[to] ); // catch overflow balances[from] -= value; balances[to] += value; bytes memory ignore; ignore = data; // ignore compiler warning Transfer( from, to, value ); // ERC20-version, ignore data } }
ERC20 Transfer From Function/
function transferFrom( address from, address to, uint256 value ) public returns (bool success) { require( value <= allowances[from][msg.sender] ); allowances[from][msg.sender] -= value; bytes memory empty; _transfer( from, to, value, empty ); return true; }
973,695
/** * Copyright BOOSTRY Co., 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. * * SPDX-License-Identifier: Apache-2.0 */ pragma solidity ^0.8.0; // @title E2E Messaging contract E2EMessaging { event Message(address indexed sender, address indexed receiver, uint256 time, string text); event PublicKeyUpdated(address indexed who, string key, string key_type); struct message { address from; // Message sender string text; // Message text uint256 time; // Timestamp of the message in UNIX seconds } struct public_key_struct { string key; // Public key string key_type; // Key type } mapping (address => uint256) public last_msg_index; mapping (address => mapping (uint256 => message)) public messages; mapping (address => public_key_struct) public keys; // [CONSTRUCTOR] constructor () {} /// @notice Send message /// @param _to Message receiver address /// @param _text Message text function sendMessage(address _to, string memory _text) public { messages[_to][last_msg_index[_to]].from = msg.sender; messages[_to][last_msg_index[_to]].text = _text; messages[_to][last_msg_index[_to]].time = block.timestamp; last_msg_index[_to]++; emit Message(msg.sender, _to, block.timestamp, _text); } /// @notice Get last index /// @param _who Message receiver address /// @return _index Last index function lastIndex(address _who) public view returns (uint256 _index) { return last_msg_index[_who]; } /// @notice Get last message /// @param _who Message receiver address /// @return _from Message sender address /// @return _text Message text /// @return _time Message block timestamp function getLastMessage(address _who) public view returns ( address _from, string memory _text, uint256 _time ) { require(last_msg_index[_who] > 0); return ( messages[_who][last_msg_index[_who] - 1].from, messages[_who][last_msg_index[_who] - 1].text, messages[_who][last_msg_index[_who] - 1].time ); } /// @notice Get message by index /// @param _who Message receiver address /// @param _index Message index /// @return _from Message sender address /// @return _text Message text /// @return _time Message block timestamp function getMessageByIndex(address _who, uint256 _index) public view returns ( address _from, string memory _text, uint256 _time ) { return ( messages[_who][_index].from, messages[_who][_index].text, messages[_who][_index].time ); } /// @notice Get public key /// @param _who Message receiver address /// @return _key Public key /// @return _key_type Key type function getPublicKey(address _who) public view returns ( string memory _key, string memory _key_type ) { return ( keys[_who].key, keys[_who].key_type ); } /// @notice Set public key /// @param _key Public key /// @param _key_type Key type function setPublicKey(string memory _key, string memory _key_type) public { keys[msg.sender].key = _key; keys[msg.sender].key_type = _key_type; emit PublicKeyUpdated(msg.sender, _key, _key_type); } }
Get public key _who Message receiver address return _key Public key return _key_type Key type
function getPublicKey(address _who) public view returns ( string memory _key, string memory _key_type ) { return ( keys[_who].key, keys[_who].key_type ); }
1,069,972
pragma solidity ^0.5.7; interface GemLike { function approve(address, uint) external; function transfer(address, uint) external; function transferFrom(address, address, uint) external; function deposit() external payable; function withdraw(uint) external; } interface ManagerLike { function cdpCan(address, uint, address) external view returns (uint); function ilks(uint) external view returns (bytes32); function owns(uint) external view returns (address); function urns(uint) external view returns (address); function vat() external view returns (address); function open(bytes32, address) external returns (uint); function give(uint, address) external; function cdpAllow(uint, address, uint) external; function urnAllow(address, uint) external; function frob(uint, int, int) external; function flux(uint, address, uint) external; function move(uint, address, uint) external; function exit( address, uint, address, uint ) external; function quit(uint, address) external; function enter(address, uint) external; function shift(uint, uint) external; } interface VatLike { function can(address, address) external view returns (uint); function ilks(bytes32) external view returns (uint, uint, uint, uint, uint); function dai(address) external view returns (uint); function urns(bytes32, address) external view returns (uint, uint); function frob( bytes32, address, address, address, int, int ) external; function hope(address) external; function move(address, address, uint) external; function gem(bytes32, address) external view returns (uint); } interface GemJoinLike { function dec() external returns (uint); function gem() external returns (GemLike); function join(address, uint) external payable; function exit(address, uint) external; } interface DaiJoinLike { function vat() external returns (VatLike); function dai() external returns (GemLike); function join(address, uint) external payable; function exit(address, uint) external; } interface HopeLike { function hope(address) external; function nope(address) external; } interface JugLike { function drip(bytes32) external returns (uint); } interface TokenInterface { function allowance(address, address) external view returns (uint); function balanceOf(address) external view returns (uint); function approve(address, uint) external; function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); function deposit() external payable; function withdraw(uint) external; } interface PepInterface { function peek() external returns (bytes32, bool); } interface MakerOracleInterface { function read() external view returns (bytes32); } interface UniswapExchange { function getEthToTokenOutputPrice(uint256 tokensBought) external view returns (uint256 ethSold); function getTokenToEthOutputPrice(uint256 ethBought) external view returns (uint256 tokensSold); function tokenToTokenSwapOutput( uint256 tokensBought, uint256 maxTokensSold, uint256 maxEthSold, uint256 deadline, address tokenAddr ) external returns (uint256 tokensSold); } interface PoolInterface { function accessToken(address[] calldata ctknAddr, uint[] calldata tknAmt, bool isCompound) external; function paybackToken(address[] calldata ctknAddr, bool isCompound) external payable; } interface CTokenInterface { function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, address cTokenCollateral) external returns (uint); function liquidateBorrow(address borrower, address cTokenCollateral) external payable; function exchangeRateCurrent() external returns (uint); function getCash() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalReserves() external view returns (uint); function reserveFactorMantissa() external view returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256 balance); function allowance(address, address) external view returns (uint); function approve(address, uint) external; function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); } interface CERC20Interface { function mint(uint mintAmount) external returns (uint); // For ERC20 function repayBorrow(uint repayAmount) external returns (uint); // For ERC20 function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); // For ERC20 function borrowBalanceCurrent(address account) external returns (uint); } interface CETHInterface { function mint() external payable; // For ETH function repayBorrow() external payable; // For ETH function repayBorrowBehalf(address borrower) external payable; // For ETH function borrowBalanceCurrent(address account) external returns (uint); } interface ComptrollerInterface { function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function exitMarket(address cTokenAddress) external returns (uint); function getAssetsIn(address account) external view returns (address[] memory); function getAccountLiquidity(address account) external view returns (uint, uint, uint); } interface CompOracleInterface { function getUnderlyingPrice(address) external view returns (uint); } interface InstaMcdAddress { function manager() external view returns (address); function dai() external view returns (address); function daiJoin() external view returns (address); function vat() external view returns (address); function jug() external view returns (address); function ethAJoin() external view returns (address); } interface OtcInterface { function getPayAmount(address, address, uint) external view returns (uint); function buyAllAmount( address, uint, address, uint ) external; } contract DSMath { function sub(uint x, uint y) internal pure returns (uint z) { z = x - y <= x ? x - y : 0; } function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "math-not-safe"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "math-not-safe"); } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } function toRad(uint wad) internal pure returns (uint rad) { rad = mul(wad, 10 ** 27); } } contract Helper is DSMath { /** * @dev get ethereum address for trade */ function getAddressETH() public pure returns (address eth) { eth = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } /** * @dev get MakerDAO MCD Address contract */ function getMcdAddresses() public pure returns (address mcd) { mcd = 0xF23196DF1C440345DE07feFbe556a5eF0dcD29F0; } /** * @dev get InstaDApp Liquidity contract */ function getPoolAddr() public pure returns (address poolAddr) { poolAddr = 0x1564D040EC290C743F67F5cB11f3C1958B39872A; } /** * @dev get Compound Comptroller Address */ function getComptrollerAddress() public pure returns (address troller) { troller = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; } /** * @dev get CETH Address */ function getCETHAddress() public pure returns (address cEth) { cEth = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; } /** * @dev get DAI Address */ function getDAIAddress() public pure returns (address dai) { dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; } /** * @dev get CDAI Address */ function getCDAIAddress() public pure returns (address cDai) { cDai = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; } /** * @dev setting allowance to compound contracts for the "user proxy" if required */ function setApproval(address erc20, uint srcAmt, address to) internal { TokenInterface erc20Contract = TokenInterface(erc20); uint tokenAllowance = erc20Contract.allowance(address(this), to); if (srcAmt > tokenAllowance) { erc20Contract.approve(to, uint(-1)); } } } contract InstaPoolResolver is Helper { function accessDai(uint daiAmt, bool isCompound) internal { address[] memory borrowAddr = new address[](1); uint[] memory borrowAmt = new uint[](1); borrowAddr[0] = getCDAIAddress(); borrowAmt[0] = daiAmt; PoolInterface(getPoolAddr()).accessToken(borrowAddr, borrowAmt, isCompound); } function returnDai(uint daiAmt, bool isCompound) internal { address[] memory borrowAddr = new address[](1); borrowAddr[0] = getCDAIAddress(); require(TokenInterface(getDAIAddress()).transfer(getPoolAddr(), daiAmt), "Not-enough-DAI"); PoolInterface(getPoolAddr()).paybackToken(borrowAddr, isCompound); } } contract MakerHelper is InstaPoolResolver { event LogOpen(uint cdpNum, address owner); event LogLock(uint cdpNum, uint amtETH, address owner); event LogFree(uint cdpNum, uint amtETH, address owner); event LogDraw(uint cdpNum, uint daiAmt, address owner); event LogWipe(uint cdpNum, uint daiAmt, address owner); /** * @dev Allowance to Maker's contract */ function setMakerAllowance(TokenInterface _token, address _spender) internal { if (_token.allowance(address(this), _spender) != uint(-1)) { _token.approve(_spender, uint(-1)); } } /** * @dev Check if entered amt is valid or not (Used in makerToCompound) */ function checkVault(uint id, uint ethAmt, uint daiAmt) internal view returns (uint ethCol, uint daiDebt) { address manager = InstaMcdAddress(getMcdAddresses()).manager(); address urn = ManagerLike(manager).urns(id); bytes32 ilk = ManagerLike(manager).ilks(id); uint art = 0; (ethCol, art) = VatLike(ManagerLike(manager).vat()).urns(ilk, urn); (,uint rate,,,) = VatLike(ManagerLike(manager).vat()).ilks(ilk); daiDebt = rmul(art,rate); daiDebt = daiAmt < daiDebt ? daiAmt : daiDebt; // if DAI amount > max debt. Set max debt ethCol = ethAmt < ethCol ? ethAmt : ethCol; // if ETH amount > max Col. Set max col } function joinDaiJoin(address urn, uint wad) internal { address daiJoin = InstaMcdAddress(getMcdAddresses()).daiJoin(); // Gets DAI from the user's wallet DaiJoinLike(daiJoin).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(daiJoin).dai().approve(daiJoin, wad); // Joins DAI into the vat DaiJoinLike(daiJoin).join(urn, wad); } function _getDrawDart( address vat, address jug, address urn, bytes32 ilk, uint wad ) internal returns (int dart) { // Updates stability fee rate uint rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart( address vat, uint dai, address urn, bytes32 ilk ) internal view returns (int dart) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint(dart) <= art ? - dart : - toInt(art); } function joinEthJoin(address urn, uint _wad) internal { address ethJoin = InstaMcdAddress(getMcdAddresses()).ethAJoin(); // Wraps ETH in WETH GemJoinLike(ethJoin).gem().deposit.value(_wad)(); // Approves adapter to take the WETH amount GemJoinLike(ethJoin).gem().approve(address(ethJoin), _wad); // Joins WETH collateral into the vat GemJoinLike(ethJoin).join(urn, _wad); } function joinGemJoin( address apt, address urn, uint wad, bool transferFrom ) internal { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } } contract CompoundHelper is MakerHelper { event LogMint(address erc20, address cErc20, uint tokenAmt, address owner); event LogRedeem(address erc20, address cErc20, uint tokenAmt, address owner); event LogBorrow(address erc20, address cErc20, uint tokenAmt, address owner); event LogRepay(address erc20, address cErc20, uint tokenAmt, address owner); /** * @dev Compound Enter Market which allows borrowing */ function enterMarket(address cErc20) internal { ComptrollerInterface troller = ComptrollerInterface(getComptrollerAddress()); address[] memory markets = troller.getAssetsIn(address(this)); bool isEntered = false; for (uint i = 0; i < markets.length; i++) { if (markets[i] == cErc20) { isEntered = true; } } if (!isEntered) { address[] memory toEnter = new address[](1); toEnter[0] = cErc20; troller.enterMarkets(toEnter); } } } contract MakerResolver is CompoundHelper { function flux(uint cdp, address dst, uint wad) internal { address manager = InstaMcdAddress(getMcdAddresses()).manager(); ManagerLike(manager).flux(cdp, dst, wad); } function move(uint cdp, address dst, uint rad) public { address manager = InstaMcdAddress(getMcdAddresses()).manager(); ManagerLike(manager).move(cdp, dst, rad); } function frob(uint cdp, int dink, int dart) internal { address manager = InstaMcdAddress(getMcdAddresses()).manager(); ManagerLike(manager).frob(cdp, dink, dart); } function open() public returns (uint cdp) { address manager = InstaMcdAddress(getMcdAddresses()).manager(); bytes32 ilk = 0x4554482d41000000000000000000000000000000000000000000000000000000; cdp = ManagerLike(manager).open(ilk, address(this)); emit LogOpen(cdp, address(this)); } function give(uint cdp, address usr) public { address manager = InstaMcdAddress(getMcdAddresses()).manager(); ManagerLike(manager).give(cdp, usr); } function lock(uint cdp, uint _wad) internal { address manager = InstaMcdAddress(getMcdAddresses()).manager(); // Receives ETH amount, converts it to WETH and joins it into the vat joinEthJoin(address(this), _wad); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(_wad), 0 ); emit LogLock(cdp, _wad, address(this)); } function free(uint cdp, uint wad) internal { address ethJoin = InstaMcdAddress(getMcdAddresses()).ethAJoin(); // Unlocks WETH amount from the CDP frob( cdp, -toInt(wad), 0 ); // Moves the amount from the CDP urn to proxy's address flux( cdp, address(this), wad ); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); emit LogFree(cdp, wad, address(this)); } function draw(uint cdp, uint wad) internal { address manager = InstaMcdAddress(getMcdAddresses()).manager(); address jug = InstaMcdAddress(getMcdAddresses()).jug(); address daiJoin = InstaMcdAddress(getMcdAddresses()).daiJoin(); address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob( cdp, 0, _getDrawDart( vat, jug, urn, ilk, wad ) ); // Moves the DAI amount (balance in the vat in rad) to proxy's address move( cdp, address(this), toRad(wad) ); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(address(this), wad); emit LogDraw(cdp, wad, address(this)); } function wipe(uint cdp, uint wad) internal { address manager = InstaMcdAddress(getMcdAddresses()).manager(); address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins DAI amount into the vat joinDaiJoin(urn, wad); // Paybacks debt to the CDP frob( cdp, 0, _getWipeDart( vat, VatLike(vat).dai(urn), urn, ilk ) ); } else { // Joins DAI amount into the vat joinDaiJoin(address(this), wad); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, _getWipeDart( vat, wad * RAY, urn, ilk ) ); } emit LogWipe(cdp, wad, address(this)); } /** * @dev Run wipe & Free function together */ function wipeAndFreeMaker( uint cdpNum, uint jam, uint _wad, bool isCompound ) internal { accessDai(_wad, isCompound); wipe(cdpNum, _wad); free(cdpNum, jam); } /** * @dev Run Lock & Draw function together */ function lockAndDrawMaker( uint cdpNum, uint jam, uint _wad, bool isCompound ) internal { lock(cdpNum, jam); draw(cdpNum, _wad); returnDai(_wad, isCompound); } } contract CompoundResolver is MakerResolver { /** * @dev Deposit ETH and mint CETH */ function mintCEth(uint tokenAmt) internal { enterMarket(getCETHAddress()); CETHInterface cToken = CETHInterface(getCETHAddress()); cToken.mint.value(tokenAmt)(); emit LogMint( getAddressETH(), getCETHAddress(), tokenAmt, msg.sender ); } /** * @dev borrow DAI */ function borrowDAIComp(uint daiAmt, bool isCompound) internal { enterMarket(getCDAIAddress()); require(CTokenInterface(getCDAIAddress()).borrow(daiAmt) == 0, "got collateral?"); // Returning Liquidity to Liquidity Contract returnDai(daiAmt, isCompound); emit LogBorrow( getDAIAddress(), getCDAIAddress(), daiAmt, address(this) ); } /** * @dev Pay DAI Debt */ function repayDaiComp(uint tokenAmt, bool isCompound) internal returns (uint wipeAmt) { CERC20Interface cToken = CERC20Interface(getCDAIAddress()); uint daiBorrowed = cToken.borrowBalanceCurrent(address(this)); wipeAmt = tokenAmt < daiBorrowed ? tokenAmt : daiBorrowed; // Getting Liquidity from Liquidity Contract accessDai(wipeAmt, isCompound); setApproval(getDAIAddress(), wipeAmt, getCDAIAddress()); require(cToken.repayBorrow(wipeAmt) == 0, "transfer approved?"); emit LogRepay( getDAIAddress(), getCDAIAddress(), wipeAmt, address(this) ); } /** * @dev Redeem CETH */ function redeemCETH(uint tokenAmt) internal returns(uint ethAmtReddemed) { CTokenInterface cToken = CTokenInterface(getCETHAddress()); uint cethBal = cToken.balanceOf(address(this)); uint exchangeRate = cToken.exchangeRateCurrent(); uint cethInEth = wmul(cethBal, exchangeRate); setApproval(getCETHAddress(), 2**128, getCETHAddress()); ethAmtReddemed = tokenAmt; if (tokenAmt > cethInEth) { require(cToken.redeem(cethBal) == 0, "something went wrong"); ethAmtReddemed = cethInEth; } else { require(cToken.redeemUnderlying(tokenAmt) == 0, "something went wrong"); } emit LogRedeem( getAddressETH(), getCETHAddress(), ethAmtReddemed, address(this) ); } /** * @dev run mint & borrow together */ function mintAndBorrowComp(uint ethAmt, uint daiAmt, bool isCompound) internal { mintCEth(ethAmt); borrowDAIComp(daiAmt, isCompound); } /** * @dev run payback & redeem together */ function paybackAndRedeemComp(uint ethCol, uint daiDebt, bool isCompound) internal returns (uint ethAmt, uint daiAmt) { daiAmt = repayDaiComp(daiDebt, isCompound); ethAmt = redeemCETH(ethCol); } /** * @dev Check if entered amt is valid or not (Used in makerToCompound) */ function checkCompound(uint ethAmt, uint daiAmt) internal returns (uint ethCol, uint daiDebt) { CTokenInterface cEthContract = CTokenInterface(getCETHAddress()); uint cEthBal = cEthContract.balanceOf(address(this)); uint ethExchangeRate = cEthContract.exchangeRateCurrent(); ethCol = wmul(cEthBal, ethExchangeRate); ethCol = wdiv(ethCol, ethExchangeRate) <= cEthBal ? ethCol : ethCol - 1; ethCol = ethCol <= ethAmt ? ethCol : ethAmt; // Set Max if amount is greater than the Col user have daiDebt = CERC20Interface(getCDAIAddress()).borrowBalanceCurrent(address(this)); daiDebt = daiDebt <= daiAmt ? daiDebt : daiAmt; // Set Max if amount is greater than the Debt user have } } contract BridgeResolver is CompoundResolver { event LogVaultToCompound(uint ethAmt, uint daiAmt); event LogCompoundToVault(uint ethAmt, uint daiAmt); /** * @dev convert Maker CDP into Compound Collateral */ function makerToCompound( uint cdpId, uint ethQty, uint daiQty, bool isCompound // access Liquidity from Compound ) external { // subtracting 0.00000001 ETH from initialPoolBal to solve Compound 8 decimal CETH error. uint initialPoolBal = sub(getPoolAddr().balance, 10000000000); (uint ethAmt, uint daiAmt) = checkVault(cdpId, ethQty, daiQty); wipeAndFreeMaker( cdpId, ethAmt, daiAmt, isCompound ); // Getting Liquidity inside Wipe function enterMarket(getCETHAddress()); enterMarket(getCDAIAddress()); mintAndBorrowComp(ethAmt, daiAmt, isCompound); // Returning Liquidity inside Borrow function uint finalPoolBal = getPoolAddr().balance; assert(finalPoolBal >= initialPoolBal); emit LogVaultToCompound(ethAmt, daiAmt); } /** * @dev convert Compound Collateral into Maker CDP * @param cdpId = 0, if user don't have any CDP */ function compoundToMaker( uint cdpId, uint ethQty, uint daiQty, bool isCompound ) external { // subtracting 0.00000001 ETH from initialPoolBal to solve Compound 8 decimal CETH error. uint initialPoolBal = sub(getPoolAddr().balance, 10000000000); uint cdpNum = cdpId > 0 ? cdpId : open(); (uint ethCol, uint daiDebt) = checkCompound(ethQty, daiQty); (uint ethAmt, uint daiAmt) = paybackAndRedeemComp(ethCol, daiDebt, isCompound); // Getting Liquidity inside Wipe function ethAmt = ethAmt < address(this).balance ? ethAmt : address(this).balance; lockAndDrawMaker( cdpNum, ethAmt, daiAmt, isCompound ); // Returning Liquidity inside Borrow function uint finalPoolBal = getPoolAddr().balance; assert(finalPoolBal >= initialPoolBal); emit LogCompoundToVault(ethAmt, daiAmt); } } contract InstaVaultCompBridge is BridgeResolver { function() external payable {} }
Receives ETH amount, converts it to WETH and joins it into the vat Locks WETH amount into the CDP
function lock(uint cdp, uint _wad) internal { address manager = InstaMcdAddress(getMcdAddresses()).manager(); joinEthJoin(address(this), _wad); VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(_wad), 0 ); emit LogLock(cdp, _wad, address(this)); }
12,975,731
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "./SpaceCoin.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title A contract for rolling out an ICO of SpaceCoin * @author Nathan Thomas * @notice This contract is not audited - Use at your own risk! */ contract ICO is Ownable { // ICO is for 150,000 tokens at 5/1 tokens/ether uint256 private constant TOKEN_MULTIPLIER = 5; // Seed phase is 75,000 tokens with an individual cap uint256 private constant SEED_CONTRIBUTIONS_PER_ADDRESS = 1_500 ether; uint256 private constant SEED_CONTRIBUTIONS_CAP = 15_000 ether; // General phase is 75,000 tokens with an individual cap uint256 private constant GENERAL_CONTRIBUTIONS_PER_ADDRESS = 1_000 ether; uint256 private constant GENERAL_CONTRIBUTIONS_CAP = 30_000 ether; enum Phases { SEED, GENERAL, OPEN } Phases public currentPhase = Phases.SEED; bool public isInitialized = false; bool public isPaused = false; address public tokenAddress; uint256 public totalContributions = 0; mapping(address => uint256) public addressToContributions; mapping(address => bool) public approvedSeedInvestors; event NewInvestment(address indexed purchaser, uint256 etherAmount); event NewPhase(Phases indexed phase); event Refund(address indexed refundAddress, uint256 etherAmount); event TokensClaimed(address indexed claimingAddress, uint256 tokenAmount); modifier hasBeenInitialized() { require(isInitialized, "ICO: not initialized"); _; } modifier hasNotBeenInitialized() { require(!isInitialized, "ICO: has been initialized"); _; } modifier isNotPaused() { require(!isPaused, "ICO: the ICO is paused"); _; } modifier isOpenPhase() { require(currentPhase == Phases.OPEN, "ICO: not open phase"); _; } modifier canContributeForCurrentPhase() { if (currentPhase == Phases.SEED) { require( totalContributions < SEED_CONTRIBUTIONS_CAP, "ICO: phase contributions reached" ); require( addressToContributions[msg.sender] < SEED_CONTRIBUTIONS_PER_ADDRESS, "ICO: contribution maximum reached" ); require( approvedSeedInvestors[msg.sender], "ICO: address is not approved" ); } else if (currentPhase == Phases.GENERAL) { require( totalContributions < GENERAL_CONTRIBUTIONS_CAP, "ICO: phase contributions reached" ); require( addressToContributions[msg.sender] < GENERAL_CONTRIBUTIONS_PER_ADDRESS, "ICO: contribution maximum reached" ); } _; } /** * @notice Allows users to buy tokens in the ICO * @dev Addresses can participate under the following conditions: * - For seed phase, they must be approved and under 1,500 ether limit * - For general phase, they must be under the 1,000 limit (inclusive of seed) * In addition, the private method _getExcessEtherToReturn checks if the address should have * ether returned to it with the following constraints: * - If msg.value puts address partly over max individual contribution limit for phase, * the excess is returned * - If the msg.value puts the address partly over the max contribution limit for the phase, * the excess is returned * If there is excess ether to return, that call is made immediately */ function buyTokens() external payable hasBeenInitialized isNotPaused canContributeForCurrentPhase { uint256 amountToReturn = _getExcessEtherToReturn(msg.value); uint256 validContributionAmount = msg.value - amountToReturn; addressToContributions[msg.sender] += validContributionAmount; totalContributions += validContributionAmount; if (amountToReturn > 0) { (bool success, ) = msg.sender.call{ value: amountToReturn }(""); require(success, "ICO: excess funds transfer failed"); emit Refund(msg.sender, amountToReturn); } emit NewInvestment(msg.sender, validContributionAmount); } /** * @notice Allows addresses that participated in the ICO to claim tokens in open phase */ function claimTokens() external hasBeenInitialized isOpenPhase { require( addressToContributions[msg.sender] > 0, "ICO: address has no contributions" ); uint256 amountToTransfer = addressToContributions[msg.sender] * 5; bool success = IERC20(tokenAddress).transfer(msg.sender, amountToTransfer); require(success, "ICO: tokens could not be claimed"); emit TokensClaimed(msg.sender, amountToTransfer); } /** emit TokensClaimed(msg.sender, amountToTransfer); * @notice Allows the owner to initialize (e.g. start) the ICO contract * @param _tokenAddress The deployed token address to be used in the ICO */ function initialize(address _tokenAddress) external onlyOwner hasNotBeenInitialized { require(_tokenAddress != address(0), "ICO: address must be valid"); tokenAddress = _tokenAddress; isInitialized = true; } /** * @notice Allows the owner to progress the phases of the ICO if contract has been initialized * @dev The phases cannot be progressed past open phase, nor can they be reversed once moved * forward */ function progressPhases() external onlyOwner hasBeenInitialized { require(currentPhase != Phases.OPEN, "ICO: phases complete"); currentPhase = Phases(uint256(currentPhase) + 1); emit NewPhase(currentPhase); } /** * @notice Allows the owner to pause/unpause the ICO */ function toggleIsPaused() external onlyOwner { isPaused = !isPaused; } /** * @notice Allows the owner to toggle on/off if another address is a seed investor * @param _seedInvestor The address to toggle on/off */ function toggleSeedInvestor(address _seedInvestor) external onlyOwner { approvedSeedInvestors[_seedInvestor] = !approvedSeedInvestors[ _seedInvestor ]; } /** * @notice Returns the excess amount of ether to return to a given address * @param _messageValue The msg.value that the address sent */ function _getExcessEtherToReturn(uint256 _messageValue) private view hasBeenInitialized canContributeForCurrentPhase returns (uint256) { uint256 addressContributions = addressToContributions[msg.sender]; uint256 newAddressContributions = addressContributions + _messageValue; uint256 newTotalContributions = totalContributions + _messageValue; if ( currentPhase == Phases.SEED && newAddressContributions > SEED_CONTRIBUTIONS_PER_ADDRESS ) { return newAddressContributions - SEED_CONTRIBUTIONS_PER_ADDRESS; } else if ( currentPhase == Phases.SEED && newTotalContributions > SEED_CONTRIBUTIONS_CAP ) { return newTotalContributions - SEED_CONTRIBUTIONS_CAP; } else if ( currentPhase == Phases.GENERAL && newAddressContributions > GENERAL_CONTRIBUTIONS_PER_ADDRESS ) { return newAddressContributions - GENERAL_CONTRIBUTIONS_PER_ADDRESS; } else if ( currentPhase == Phases.GENERAL && newTotalContributions > GENERAL_CONTRIBUTIONS_CAP ) { return newTotalContributions - GENERAL_CONTRIBUTIONS_CAP; } return 0; } /** * @dev This method has been specifically disallowed in favor of the buyTokens function */ receive() external payable { revert("ICO: use buyTokens function"); } }
Allows the owner to toggle on/off if another address is a seed investor _seedInvestor The address to toggle on/off/
function toggleSeedInvestor(address _seedInvestor) external onlyOwner { approvedSeedInvestors[_seedInvestor] = !approvedSeedInvestors[ _seedInvestor ]; }
1,816,529
pragma solidity ^0.4.23; // If you are reading this... // This is a "backup" - deploying to the same address on mainnet and testnet // Just in case someone accidentally sends Ether into ether // Here is the Ropsten (testnet, monopoly money) address: https://ropsten.etherscan.io/address/0x6c1c2fd38fccc0b010f75b2ece535cf57543ddcd#code // Learning stuff, heavily investing in skills and education // If you can - hire me - https://genesis.re // One disclaimer though - cannot handle bullshit jobs - only true leaders, only meaningful projects please :) // File: contracts/Auction.sol contract Auction { string public description; string public instructions; // will be used for delivery address or email uint public price; bool public initialPrice = true; // at first asking price is OK, then +25% required uint public timestampEnd; address public beneficiary; bool public finalized = false; address public owner; address public winner; mapping(address => uint) public bids; address[] public accountsList; // so we can iterate: https://ethereum.stackexchange.com/questions/13167/are-there-well-solved-and-simple-storage-patterns-for-solidity function getAccountListLenght() public constant returns(uint) { return accountsList.length; } // lenght is not accessible from DApp, exposing convenience method: https://stackoverflow.com/questions/43016011/getting-the-length-of-public-array-variable-getter // THINK: should be (an optional) constructor parameter? // For now if you want to change - simply modify the code uint public increaseTimeIfBidBeforeEnd = 24 * 60 * 60; // Naming things: https://www.instagram.com/p/BSa_O5zjh8X/ uint public increaseTimeBy = 24 * 60 * 60; event BidEvent(address indexed bidder, uint value, uint timestamp); // cannot have event and struct with the same name event Refund(address indexed bidder, uint value, uint timestamp); modifier onlyOwner { require(owner == msg.sender, "only owner"); _; } modifier onlyWinner { require(winner == msg.sender, "only winner"); _; } modifier ended { require(now > timestampEnd, "not ended yet"); _; } function setDescription(string _description) public onlyOwner() { description = _description; } // TODO: Override this method in the derived functions, think about on-chain / off-chain communication mechanism function setInstructions(string _instructions) public ended() onlyWinner() { instructions = _instructions; } constructor(uint _price, string _description, uint _timestampEnd, address _beneficiary) public { require(_timestampEnd > now, "end of the auction must be in the future"); owner = msg.sender; price = _price; description = _description; timestampEnd = _timestampEnd; beneficiary = _beneficiary; } // Same for all the derived contract, it&#39;s the implementation of refund() and bid() that differs function() public payable { if (msg.value == 0) { refund(); } else { bid(); } } function bid() public payable { require(now < timestampEnd, "auction has ended"); // sending ether only allowed before the end if (bids[msg.sender] > 0) { // First we add the bid to an existing bid bids[msg.sender] += msg.value; } else { bids[msg.sender] = msg.value; accountsList.push(msg.sender); // this is out first bid, therefore adding } if (initialPrice) { require(bids[msg.sender] >= price, "bid too low, minimum is the initial price"); } else { require(bids[msg.sender] >= (price * 5 / 4), "bid too low, minimum 25% increment"); } if (now > timestampEnd - increaseTimeIfBidBeforeEnd) { timestampEnd = now + increaseTimeBy; } initialPrice = false; price = bids[msg.sender]; winner = msg.sender; emit BidEvent(winner, msg.value, now); // THINK: I prefer sharing the value of the current transaction, the total value can be retrieved from the array } function finalize() public ended() onlyOwner() { require(finalized == false, "can withdraw only once"); require(initialPrice == false, "can withdraw only if there were bids"); finalized = true; beneficiary.transfer(price); } function refund(address addr) private { require(addr != winner, "winner cannot refund"); require(bids[addr] > 0, "refunds only allowed if you sent something"); uint refundValue = bids[addr]; bids[addr] = 0; // reentrancy fix, setting to zero first addr.transfer(refundValue); emit Refund(addr, refundValue, now); } function refund() public { refund(msg.sender); } function refundOnBehalf(address addr) public onlyOwner() { refund(addr); } } // File: contracts/AuctionMultiple.sol // 1, "something", 1539659548, "0xca35b7d915458ef540ade6068dfe2f44e8fa733c", 3 // 1, "something", 1539659548, "0x315f80C7cAaCBE7Fb1c14E65A634db89A33A9637", 3 contract AuctionMultiple is Auction { uint public constant LIMIT = 2000; // due to gas restrictions we limit the number of participants in the auction (no Burning Man tickets yet) uint public constant HEAD = 120000000 * 1e18; // uint(-1); // really big number uint public constant TAIL = 0; uint public lastBidID = 0; uint public howMany; // number of items to sell, for isntance 40k tickets to a concert struct Bid { uint prev; // bidID of the previous element. uint next; // bidID of the next element. uint value; address contributor; // The contributor who placed the bid. } mapping (uint => Bid) public bids; // map bidID to actual Bid structure mapping (address => uint) public contributors; // map address to bidID event LogNumber(uint number); event LogText(string text); event LogAddress(address addr); constructor(uint _price, string _description, uint _timestampEnd, address _beneficiary, uint _howMany) Auction(_price, _description, _timestampEnd, _beneficiary) public { require(_howMany > 1, "This auction is suited to multiple items. With 1 item only - use different code. Or remove this &#39;require&#39; - you&#39;ve been warned"); howMany = _howMany; bids[HEAD] = Bid({ prev: TAIL, next: TAIL, value: HEAD, contributor: address(0) }); bids[TAIL] = Bid({ prev: HEAD, next: HEAD, value: TAIL, contributor: address(0) }); } function bid() public payable { require(now < timestampEnd, "cannot bid after the auction ends"); uint myBidId = contributors[msg.sender]; uint insertionBidId; if (myBidId > 0) { // sender has already placed bid, we increase the existing one Bid storage existingBid = bids[myBidId]; existingBid.value = existingBid.value + msg.value; if (existingBid.value > bids[existingBid.next].value) { // else do nothing (we are lower than the next one) insertionBidId = searchInsertionPoint(existingBid.value, existingBid.next); bids[existingBid.prev].next = existingBid.next; bids[existingBid.next].prev = existingBid.prev; existingBid.prev = insertionBidId; existingBid.next = bids[insertionBidId].next; bids[ bids[insertionBidId].next ].prev = myBidId; bids[insertionBidId].next = myBidId; } } else { // bid from this guy does not exist, create a new one require(msg.value >= price, "Not much sense sending less than the price, likely an error"); // but it is OK to bid below the cut off bid, some guys may withdraw require(lastBidID < LIMIT, "Due to blockGas limit we limit number of people in the auction to 4000 - round arbitrary number - check test gasLimit folder for more info"); lastBidID++; insertionBidId = searchInsertionPoint(msg.value, TAIL); contributors[msg.sender] = lastBidID; accountsList.push(msg.sender); bids[lastBidID] = Bid({ prev: insertionBidId, next: bids[insertionBidId].next, value: msg.value, contributor: msg.sender }); bids[ bids[insertionBidId].next ].prev = lastBidID; bids[insertionBidId].next = lastBidID; } emit BidEvent(msg.sender, msg.value, now); } function refund(address addr) private { uint bidId = contributors[addr]; require(bidId > 0, "the guy with this address does not exist, makes no sense to witdraw"); uint position = getPosition(addr); require(position > howMany, "only the non-winning bids can be withdrawn"); Bid memory thisBid = bids[ bidId ]; bids[ thisBid.prev ].next = thisBid.next; bids[ thisBid.next ].prev = thisBid.prev; delete bids[ bidId ]; // clearning storage delete contributors[ msg.sender ]; // clearning storage // cannot delete from accountsList - cannot shrink an array in place without spending shitloads of gas addr.transfer(thisBid.value); emit Refund(addr, thisBid.value, now); } function finalize() public ended() onlyOwner() { require(finalized == false, "auction already finalized, can withdraw only once"); finalized = true; uint sumContributions = 0; uint counter = 0; Bid memory currentBid = bids[HEAD]; while(counter++ < howMany && currentBid.prev != TAIL) { currentBid = bids[ currentBid.prev ]; sumContributions += currentBid.value; } beneficiary.transfer(sumContributions); } // We are starting from TAIL and going upwards // This is to simplify the case of increasing bids (can go upwards, cannot go lower) // NOTE: blockSize gas limit in case of so many bids (wishful thinking) function searchInsertionPoint(uint _contribution, uint _startSearch) view public returns (uint) { require(_contribution > bids[_startSearch].value, "your contribution and _startSearch does not make sense, it will search in a wrong direction"); Bid memory lowerBid = bids[_startSearch]; Bid memory higherBid; while(true) { // it is guaranteed to stop as we set the HEAD bid with very high maximum valuation higherBid = bids[lowerBid.next]; if (_contribution < higherBid.value) { return higherBid.prev; } else { lowerBid = higherBid; } } } function getPosition(address addr) view public returns(uint) { uint bidId = contributors[addr]; require(bidId != 0, "cannot ask for a position of a guy who is not on the list"); uint position = 1; Bid memory currentBid = bids[HEAD]; while (currentBid.prev != bidId) { // BIG LOOP WARNING, that why we have LIMIT currentBid = bids[currentBid.prev]; position++; } return position; } function getPosition() view public returns(uint) { // shorthand for calling without parameters return getPosition(msg.sender); } } // File: contracts/AuctionMultipleGuaranteed.sol // 100000000000000000, "membership in Casa Crypto", 1546300799, "0x8855Ef4b740Fc23D822dC8e1cb44782e52c07e87", 20, 5, 5000000000000000000 // 100000000000000000, "membership in Casa Crypto", 1546300799, "0x85A363699C6864248a6FfCA66e4a1A5cCf9f5567", 2, 1, 5000000000000000000 // For instance: effering limited "Early Bird" tickets that are guaranteed contract AuctionMultipleGuaranteed is AuctionMultiple { uint public howManyGuaranteed; // after guaranteed slots are used, we decrease the number of slots available (in the parent contract) uint public priceGuaranteed; address[] public guaranteedContributors; // cannot iterate mapping, keeping addresses in an array mapping (address => uint) public guaranteedContributions; function getGuaranteedContributorsLenght() public constant returns(uint) { return guaranteedContributors.length; } // lenght is not accessible from DApp, exposing convenience method: https://stackoverflow.com/questions/43016011/getting-the-length-of-public-array-variable-getter event GuaranteedBid(address indexed bidder, uint value, uint timestamp); constructor(uint _price, string _description, uint _timestampEnd, address _beneficiary, uint _howMany, uint _howManyGuaranteed, uint _priceGuaranteed) AuctionMultiple(_price, _description, _timestampEnd, _beneficiary, _howMany) public { require(_howMany >= _howManyGuaranteed, "The number of guaranteed items should be less or equal than total items. If equal = fixed price sell, kind of OK with me"); require(_priceGuaranteed > 0, "Guranteed price must be greated than zero"); howManyGuaranteed = _howManyGuaranteed; priceGuaranteed = _priceGuaranteed; } function bid() public payable { require(now < timestampEnd, "cannot bid after the auction ends"); require(guaranteedContributions[msg.sender] == 0, "already a guranteed contributor, cannot more than once"); if (msg.value >= priceGuaranteed && howManyGuaranteed > 0) { guaranteedContributors.push(msg.sender); guaranteedContributions[msg.sender] = msg.value; howManyGuaranteed--; howMany--; emit GuaranteedBid(msg.sender, msg.value, now); } else { super.bid(); // https://ethereum.stackexchange.com/questions/25046/inheritance-and-function-overwriting-who-can-call-the-parent-function } } function finalize() public ended() onlyOwner() { require(finalized == false, "auction already finalized, can withdraw only once"); finalized = true; uint sumContributions = 0; uint counter = 0; Bid memory currentBid = bids[HEAD]; while(counter++ < howMany && currentBid.prev != TAIL) { currentBid = bids[ currentBid.prev ]; sumContributions += currentBid.value; } // At all times we are aware of gas limits - that&#39;s why we limit auction to 2000 participants, see also `test-gasLimit` folder for (uint i=0; i<guaranteedContributors.length; i++) { sumContributions += guaranteedContributions[ guaranteedContributors[i] ]; } beneficiary.transfer(sumContributions); } }
shorthand for calling without parameters
function getPosition() view public returns(uint) {
2,425,018
./full_match/5/0x631CadF9267a7784D690AFa0Bd9128760CF555Cf/sources/contracts/extensions/WithdrawalLimitation.sol
Record withdrawal token./
function _recordWithdrawal(address _token, uint256 _quantity) internal virtual { uint256 _currentDate = block.timestamp / 1 days; if (_currentDate > lastDateSynced[_token]) { lastDateSynced[_token] = _currentDate; lastSyncedWithdrawal[_token] = _quantity; lastSyncedWithdrawal[_token] += _quantity; } }
1,908,400
pragma solidity ^0.5.2; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./ERC223.sol"; /* . Exchanged with NTY with rate 1 MegaNTY = 1000000 NTY . Mint. / burn. able(free) by owner = orderbook contract */ contract VolatileToken is ERC223 { string public constant symbol = "MNTY"; string public constant name = "Mega NTY"; uint public constant decimals = 24; // track the amount of token has been inflated, negative for deflation // only use for report, so ignore any overflow int inflated; constructor ( address orderbook, // mandatory address prefundAddress, // optional uint prefundAmount // optional ) public { if (prefundAmount > 0 ) { _mint(prefundAddress, prefundAmount * 10**decimals); } initialize(orderbook); } // override ERC223.dexMint function dexMint(uint _amount) public onlyOwner { _mint(owner(), _amount); inflated += int(_amount); } // override ERC223.dexBurn function dexBurn(uint _amount) public onlyOwner { _burn(owner(), _amount); inflated -= int(_amount); } function totalInflated() external view returns(int) { return inflated; } // deposit (MNTY <- NTY) function deposit() external payable returns(bool) { depositTo(msg.sender); } // withdraw (MNTY -> NTY) function withdraw(uint _amount) external returns(bool) { withdrawTo(_amount, msg.sender); } // withdrawTo (MNTY -> NTY -> address) function withdrawTo(uint _amount, address payable _to) public returns(bool) { address _sender = msg.sender; _burn(_sender, _amount); /************************************************************************/ /* concensus garantures, this contract always got enough NTY to withdraw */ /************************************************************************/ _to.transfer(_amount); } // depositTo (addresss <- MNTY <- NTY) function depositTo( address _to ) public payable returns(bool) { uint _amount = msg.value; _mint(_to, _amount); return true; } // deposit and order (NTY -> MNTY -> USD) function depositAndTrade( bytes32 index, uint haveAmount, uint wantAmount, bytes32 assistingID ) public payable { depositTo(msg.sender); trade(index, haveAmount, wantAmount, assistingID); } // create selling order (MNTY -> USD) // with verbose data = (wantAmount, assistingID) function trade( bytes32 index, uint haveAmount, uint wantAmount, bytes32 assistingID ) public { bytes memory data = abi.encode(index, wantAmount, assistingID); transfer(dex(), haveAmount, data); } // deposit and propose() function depositAndPropose( int amount, // absorption amount of StablizeToken uint stake, // staked amount of VolatileToken uint slashingRate, uint lockdownExpiration ) public payable { depositTo(msg.sender); propose(amount, stake, slashingRate, lockdownExpiration); } // propose a new pre-emptive absorption // with verbose data = (amount, slashingRate, lockdownExpiration); function propose( int amount, // absorption amount of StablizeToken uint stake, // staked amount of VolatileToken uint slashingRate, uint lockdownExpiration ) public { bytes memory data = abi.encode(amount, slashingRate, lockdownExpiration, bytes32(0)); transfer(dex(), stake, data); } }
deposit and propose()
function depositAndPropose( uint slashingRate, uint lockdownExpiration ) public payable { depositTo(msg.sender); propose(amount, stake, slashingRate, lockdownExpiration); }
13,070,974
./partial_match/3/0xdF73B7b46980EFcB500bcB4819AA4c7d4F756eB4/sources/TrueINR.sol
------------------------------------------------------------------------ Owner can transfer out any accidentally sent ERC20 tokens ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public whenNotPaused onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); }
5,167,959
./full_match/137/0xFd055AB59A7aC52d22116d47F08fE3980C4A2F88/sources/Proxy.sol
Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); }
3,763,323
//Address: 0x7b9c946dE2f5daE10b82D950AC20DFc1692a1E6a //Contract name: T_Token_11 //Balance: 0 Ether //Verification Date: 1/16/2018 //Transacion Count: 5 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @title SafeMath * Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * Official T_Token as issued by The T**** * Based off of Standard ERC20 token * * Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Partially based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract T_Token_11 { using SafeMath for uint256; string public name; string public symbol; uint256 public decimals; uint256 public totalSupply; uint256 private tprFund; uint256 private founderCoins; uint256 private icoReleaseTokens; uint256 private tprFundReleaseTime; uint256 private founderCoinsReleaseTime; bool private tprFundUnlocked; bool private founderCoinsUnlocked; address private tprFundDeposit; address private founderCoinsDeposit; mapping(address => uint256) internal balances; mapping (address => mapping (address => uint256)) internal allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Burn(address indexed burner, uint256 value); function T_Token_11 () public { name = "T_Token_11"; symbol = "T_TPR_T11"; decimals = 18; tprFund = 260000000 * (10**decimals); founderCoins = 30000000 * (10**decimals); icoReleaseTokens = 210000000 * (10**decimals); totalSupply = tprFund + founderCoins + icoReleaseTokens; balances[msg.sender] = icoReleaseTokens; tprFundDeposit = 0xF1F465C345b6DBc4Bcdf98aB286762ba282BA69a; //TPR Fund balances[tprFundDeposit] = 0; tprFundReleaseTime = 30 * 1 minutes; // TPR Fund to be available after 6 months tprFundUnlocked = false; founderCoinsDeposit = 0x64108822C128D11b6956754056ec4bCBe0B0CDaf; // Founders Coins balances[founderCoinsDeposit] = 0; founderCoinsReleaseTime = 60 * 1 minutes; // Founders coins to be unlocked after 1 year founderCoinsUnlocked = false; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function releaseTprFund() public { require(now >= tprFundReleaseTime); require(!tprFundUnlocked); balances[tprFundDeposit] = tprFund; Transfer(0, tprFundDeposit, tprFund); tprFundUnlocked = true; } function releaseFounderCoins() public { require(now >= founderCoinsReleaseTime); require(!founderCoinsUnlocked); balances[founderCoinsDeposit] = founderCoins; Transfer(0, founderCoinsDeposit, founderCoins); founderCoinsUnlocked = true; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); require(_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /** * @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]); require(_value > 0); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { require(_value>0); require(balances[msg.sender]>_value); allowed[msg.sender][_spender] = 0; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * Burns a specific amount of tokens. * @param _value The amount of tokens to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } }
transfer token for a specified address _to The address to transfer to. _value The amount to be transferred./
function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); require(_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; }
14,039,148
./full_match/1/0x1eA67cD6DA0fea19d270BE6B8Bfa44B5aDa81Fcd/sources/browser/coinbase.sol
dYdX ICallee callback
function callFunction(address, IdYdX.AccountInfo memory, bytes memory data) external { require(tx.origin == owner, "CaV3: origin not owner"); (address[] memory targets, bytes[] memory payloads, string[] memory messages) = abi.decode(data, (address[], bytes[], string[])); callFuns(targets, payloads, messages); }
2,971,610
./partial_match/3/0x88F54537b48111819d7A92eD0B7C9E00f8aeeFd5/sources/FruitCrowdSale.sol
require((block.timestamp > endTime), Crowdsate is still active");
function burnUnsold() private { require(msg.sender == governance, "!governance"); IERC20 token = IERC20(tokenAddress); uint256 amount = token.balanceOf(address(this)); token.burn(amount); }
5,065,689
pragma solidity 0.5.9; 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; } } /// @dev It is ERC20 compliant, but still needs to under go further testing. contract Ownable { address payable public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address payable _newOwner) external onlyOwner { require(_newOwner != address(0)); owner = _newOwner; emit OwnershipTransferred(owner, _newOwner); } } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes calldata _data) external; } /// @dev The actual token contract, the default owner is the msg.sender contract WINSToken is Ownable { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; Checkpoint[] totalSupplyHolders; mapping (address => bool) public holders; uint public minHolderAmount = 20000 ether; //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _owner, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event Approval(address indexed _owner, address indexed _spender, uint256 _amount); modifier whenTransfersEnabled() { require(transfersEnabled); _; } //////////////// // Constructor //////////////// constructor () public { name = "WINS LIVE"; symbol = "WL"; decimals = 18; creationBlock = block.number; transfersEnabled = true; //initial emission uint _amount = 77777777 * (10 ** uint256(decimals)); updateValueAtNow(totalSupplyHistory, _amount); updateValueAtNow(balances[msg.sender], _amount); holders[msg.sender] = true; updateValueAtNow(totalSupplyHolders, _amount); emit Transfer(address(0), msg.sender, _amount); } /// @notice The fallback function function () external payable {} /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) whenTransfersEnabled external returns (bool) { doTransfer(msg.sender, _to, _amount); return true; } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount) whenTransfersEnabled external returns (bool) { // The standard ERC 20 transferFrom functionality require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; doTransfer(_from, _to, _amount); return true; } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount) internal { if (_amount == 0) { emit Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0 return; } // Do not allow transfer to 0x0 or the token contract itself require((_to != address(0)) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer throws uint previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens uint previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain emit Transfer(_from, _to, _amount); uint curTotalSupplyHolders = totalSupplyHoldersAt(block.number); if (holders[_from]) { if (previousBalanceFrom - _amount < minHolderAmount) { delete holders[_from]; require(curTotalSupplyHolders >= previousBalanceFrom); curTotalSupplyHolders = curTotalSupplyHolders - previousBalanceFrom; updateValueAtNow(totalSupplyHolders, curTotalSupplyHolders); } else { require(curTotalSupplyHolders >= _amount); curTotalSupplyHolders = curTotalSupplyHolders - _amount; updateValueAtNow(totalSupplyHolders, curTotalSupplyHolders); } } if (previousBalanceTo + _amount >= minHolderAmount) { if (holders[_to]) { require(curTotalSupplyHolders + _amount >= curTotalSupplyHolders); // Check for overflow updateValueAtNow(totalSupplyHolders, curTotalSupplyHolders + _amount); } if (!holders[_to]) { holders[_to] = true; require(curTotalSupplyHolders + previousBalanceTo + _amount >= curTotalSupplyHolders); // Check for overflow updateValueAtNow(totalSupplyHolders, curTotalSupplyHolders + previousBalanceTo + _amount); } } } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) external view returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) whenTransfersEnabled public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowance[_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 _addedAmount The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedAmount) external returns (bool) { require(allowed[msg.sender][_spender] + _addedAmount >= allowed[msg.sender][_spender]); // Check for overflow allowed[msg.sender][_spender] = allowed[msg.sender][_spender] + _addedAmount; 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 allowance[_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 _subtractedAmount The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedAmount) external returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedAmount >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue - _subtractedAmount; } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) external view returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes calldata _extraData) external returns (bool) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, address(this), _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() external view returns (uint) { return totalSupplyAt(block.number); } function currentTotalSupplyHolders() external view returns (uint) { return totalSupplyHoldersAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public view returns (uint) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { return 0; // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public view returns(uint) { if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { return 0; // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } function totalSupplyHoldersAt(uint _blockNumber) public view returns(uint) { if ((totalSupplyHolders.length == 0) || (totalSupplyHolders[0].fromBlock > _blockNumber)) { return 0; // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHolders, _blockNumber); } } function isHolder(address _holder) external view returns(bool) { return holders[_holder]; } function destroyTokens(uint _amount) onlyOwner public returns (bool) { uint curTotalSupply = totalSupplyAt(block.number); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOfAt(msg.sender, block.number); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[msg.sender], previousBalanceFrom - _amount); emit Transfer(msg.sender, address(0), _amount); uint curTotalSupplyHolders = totalSupplyHoldersAt(block.number); if (holders[msg.sender]) { if (previousBalanceFrom - _amount < minHolderAmount) { delete holders[msg.sender]; require(curTotalSupplyHolders >= previousBalanceFrom); updateValueAtNow(totalSupplyHolders, curTotalSupplyHolders - previousBalanceFrom); } else { require(curTotalSupplyHolders >= _amount); updateValueAtNow(totalSupplyHolders, curTotalSupplyHolders - _amount); } } return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) public onlyOwner { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block) view internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } ////////// // Safety Methods ////////// /// @notice This method can be used by the owner to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address payable _token) external onlyOwner { if (_token == address(0)) { owner.transfer(address(this).balance); return; } WINSToken token = WINSToken(_token); uint balance = token.balanceOf(address(this)); token.transfer(owner, balance); emit ClaimedTokens(_token, owner, balance); } function setMinHolderAmount(uint _minHolderAmount) external onlyOwner { minHolderAmount = _minHolderAmount; } } contract DividendManager is Ownable { using SafeMath for uint; event DividendDeposited(address indexed _depositor, uint256 _blockNumber, uint256 _amount, uint256 _totalSupply, uint256 _dividendIndex); event DividendClaimed(address indexed _claimer, uint256 _dividendIndex, uint256 _claim); event DividendRecycled(address indexed _recycler, uint256 _blockNumber, uint256 _amount, uint256 _totalSupply, uint256 _dividendIndex); WINSToken public token; uint256 public RECYCLE_TIME = 365 days; uint public minHolderAmount = 20000 ether; struct Dividend { uint256 blockNumber; uint256 timestamp; uint256 amount; uint256 claimedAmount; uint256 totalSupply; bool recycled; mapping (address => bool) claimed; } Dividend[] public dividends; mapping (address => uint256) dividendsClaimed; struct NotClaimed { uint listIndex; bool exists; } mapping (address => NotClaimed) public notClaimed; address[] public notClaimedList; modifier validDividendIndex(uint256 _dividendIndex) { require(_dividendIndex < dividends.length); _; } constructor(address payable _token) public { token = WINSToken(_token); } function depositDividend() payable public { uint256 currentSupply = token.totalSupplyHoldersAt(block.number); uint i; for( i = 0; i < notClaimedList.length; i++) { if (token.isHolder(notClaimedList[i])) { currentSupply = currentSupply.sub(token.balanceOf(notClaimedList[i])); } } uint256 dividendIndex = dividends.length; uint256 blockNumber = SafeMath.sub(block.number, 1); dividends.push( Dividend( blockNumber, getNow(), msg.value, 0, currentSupply, false ) ); emit DividendDeposited(msg.sender, blockNumber, msg.value, currentSupply, dividendIndex); } function claimDividend(uint256 _dividendIndex) public validDividendIndex(_dividendIndex) { require(!notClaimed[msg.sender].exists); Dividend storage dividend = dividends[_dividendIndex]; require(dividend.claimed[msg.sender] == false); require(dividend.recycled == false); uint256 balance = token.balanceOfAt(msg.sender, dividend.blockNumber); require(balance >= minHolderAmount); uint256 claim = balance.mul(dividend.amount).div(dividend.totalSupply); dividend.claimed[msg.sender] = true; dividend.claimedAmount = SafeMath.add(dividend.claimedAmount, claim); if (claim > 0) { msg.sender.transfer(claim); emit DividendClaimed(msg.sender, _dividendIndex, claim); } } function claimDividendAll() public { require(dividendsClaimed[msg.sender] < dividends.length); for (uint i = dividendsClaimed[msg.sender]; i < dividends.length; i++) { if ((dividends[i].claimed[msg.sender] == false) && (dividends[i].recycled == false)) { dividendsClaimed[msg.sender] = SafeMath.add(i, 1); claimDividend(i); } } } function recycleDividend(uint256 _dividendIndex) public onlyOwner validDividendIndex(_dividendIndex) { Dividend storage dividend = dividends[_dividendIndex]; require(dividend.recycled == false); require(dividend.timestamp < SafeMath.sub(getNow(), RECYCLE_TIME)); dividends[_dividendIndex].recycled = true; uint256 currentSupply = token.totalSupplyAt(block.number); uint256 remainingAmount = SafeMath.sub(dividend.amount, dividend.claimedAmount); uint256 dividendIndex = dividends.length; uint256 blockNumber = SafeMath.sub(block.number, 1); dividends.push( Dividend( blockNumber, getNow(), remainingAmount, 0, currentSupply, false ) ); emit DividendRecycled(msg.sender, blockNumber, remainingAmount, currentSupply, dividendIndex); } //Function is mocked for tests function getNow() internal view returns (uint256) { return now; } function dividendsCount() external view returns (uint) { return dividends.length; } function registerNotClaimed(address _notClaimed) onlyOwner public { require(_notClaimed != address(0)); if (!notClaimed[_notClaimed].exists) { notClaimed[_notClaimed] = NotClaimed({ listIndex: notClaimedList.length, exists: true }); notClaimedList.push(_notClaimed); } } function unregisterNotClaimed(address _notClaimed) onlyOwner public { require(notClaimed[_notClaimed].exists && notClaimedList.length > 0); uint lastIdx = notClaimedList.length - 1; notClaimed[notClaimedList[lastIdx]].listIndex = notClaimed[_notClaimed].listIndex; notClaimedList[notClaimed[_notClaimed].listIndex] = notClaimedList[lastIdx]; notClaimedList.length--; delete notClaimed[_notClaimed]; } /// @notice This method can be used by the owner to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address payable _token) external onlyOwner { // if (_token == 0x0) { // owner.transfer(address(this).balance); // return; // } WINSToken claimToken = WINSToken(_token); uint balance = claimToken.balanceOf(address(this)); claimToken.transfer(owner, balance); } }
This function makes it easy to get the total number of tokens return The total number of tokens
function totalSupply() external view returns (uint) { return totalSupplyAt(block.number); }
5,380,706
// File: contracts/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.0 (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; } } // File: contracts/IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/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 IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: contracts/ITraits.sol pragma solidity ^0.8.0; interface ITraits { function tokenURI(uint256 tokenId) external view returns (string memory); } // File: contracts/IArena.sol pragma solidity ^0.8.0; interface IArena { function addManyToArenaAndPack(address account, uint16[] calldata tokenIds) external; function randomGuardOwner(uint256 seed) external view returns (address); } // File: contracts/ISquuid.sol pragma solidity ^0.8.0; interface ISquuid { // struct to store each token's traits struct PlayerGuard { bool isPlayer; uint8 colors; uint8 head; uint8 numbers; uint8 shapes; uint8 nose; uint8 accessories; uint8 guns; uint8 feet; uint8 alphaIndex; } function getPaidTokens() external view returns (uint256); function getTokenTraits(uint256 tokenId) external view returns (PlayerGuard memory); } // File: contracts/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: contracts/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: contracts/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: contracts/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: contracts/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: contracts/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: contracts/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: contracts/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: contracts/ERC20.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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 {} } // File: contracts/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/SQUID.sol pragma solidity ^0.8.0; contract SQUID is ERC20, Ownable { // a mapping from an address to whether or not it can mint / burn mapping(address => bool) controllers; constructor() ERC20("SQUID", "SQUID") { } /** * mints $SQUID to a recipient * @param to the recipient of the $SQUID * @param amount the amount of $SQUID to mint */ function mint(address to, uint256 amount) external { require(controllers[msg.sender], "Only controllers can mint"); _mint(to, amount); } /** * burns $SQUID from a holder * @param from the holder of the $SQUID * @param amount the amount of $SQUID to burn */ function burn(address from, uint256 amount) external { require(controllers[msg.sender], "Only controllers can burn"); _burn(from, amount); } /** * enables an address to mint / burn * @param controller the address to enable */ function addController(address controller) external onlyOwner { controllers[controller] = true; } /** * disables an address from minting / burning * @param controller the address to disbale */ function removeController(address controller) external onlyOwner { controllers[controller] = false; } } // File: contracts/Pausable.sol pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: contracts/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: contracts/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: contracts/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: contracts/Squuid.sol pragma solidity ^0.8.0; contract Squuid is ISquuid, ERC721Enumerable, Ownable, Pausable { // mint price uint256 public constant WL_MINT_PRICE = .0456 ether; uint256 public constant MINT_PRICE = .06942 ether; // max number of tokens that can be minted - 50000 in production uint256 public immutable MAX_TOKENS; // number of tokens that can be claimed for free - 20% of MAX_TOKENS uint256 public PAID_TOKENS; // number of tokens have been minted so far uint16 public minted; //For Whitelist mapping(address => uint256) public whiteList; //Keep track of data mapping(uint256 => PlayerGuard) public _idData; // mapping from tokenId to a struct containing the token's traits mapping(uint256 => PlayerGuard) public tokenTraits; // mapping from hashed(tokenTrait) to the tokenId it's associated with // used to ensure there are no duplicates mapping(uint256 => uint256) public existingCombinations; // list of probabilities for each trait type // 0 - 9 are associated with Player, 10 - 18 are associated with Wolves uint8[][18] public rarities; // list of aliases for Walker's Alias algorithm // 0 - 9 are associated with Player, 10 - 18 are associated with Wolves uint8[][18] public aliases; // reference to the Arena for choosing random Guard thieves IArena public arena; // reference to $SQUID for burning on mint SQUID public squid; // reference to Traits ITraits public traits; /** * instantiates contract and rarity tables */ constructor(address _squid, address _traits, uint256 _maxTokens) ERC721("Squid Game", 'SGAME') { squid = SQUID(_squid); traits = ITraits(_traits); MAX_TOKENS = _maxTokens; PAID_TOKENS = _maxTokens / 5; // I know this looks weird but it saves users gas by making lookup O(1) // A.J. Walker's Alias Algorithm // player // colors rarities[0] = [15, 50, 200, 250, 255]; aliases[0] = [4, 4, 4, 4, 4]; // head rarities[1] = [190, 215, 240, 100, 110, 135, 160, 185, 80, 210, 235, 240, 80, 80, 100, 100, 100, 245, 250, 255]; aliases[1] = [1, 2, 4, 0, 5, 6, 7, 9, 0, 10, 11, 17, 0, 0, 0, 0, 4, 18, 19, 19]; // numbers rarities[2] = [255, 30, 60, 60, 150, 156]; aliases[2] = [0, 0, 0, 0, 0, 0]; // shapes rarities[3] = [221, 100, 181, 140, 224, 147, 84, 228, 140, 224, 250, 160, 241, 207, 173, 84, 254, 220, 196, 140, 168, 252, 140, 183, 236, 252, 224, 255]; aliases[3] = [1, 2, 5, 0, 1, 7, 1, 10, 5, 10, 11, 12, 13, 14, 16, 11, 17, 23, 13, 14, 17, 23, 23, 24, 27, 27, 27, 27]; // nose rarities[4] = [175, 100, 40, 250, 115, 100, 185, 175, 180, 255]; aliases[4] = [3, 0, 4, 6, 6, 7, 8, 8, 9, 9]; // accessories rarities[5] = [80, 225, 227, 228, 112, 240, 64, 160, 167, 217, 171, 64, 240, 126, 80, 255]; aliases[5] = [1, 2, 3, 8, 2, 8, 8, 9, 9, 10, 13, 10, 13, 15, 13, 15]; // guns rarities[6] = [255]; aliases[6] = [0]; // feet rarities[7] = [243, 189, 133, 133, 57, 95, 152, 135, 133, 57, 222, 168, 57, 57, 38, 114, 114, 114, 255]; aliases[7] = [1, 7, 0, 0, 0, 0, 0, 10, 0, 0, 11, 18, 0, 0, 0, 1, 7, 11, 18]; // alphaIndex rarities[8] = [255]; aliases[8] = [0]; // wolves // colors rarities[9] = [210, 90, 9, 9, 9, 150, 9, 255, 9]; aliases[9] = [5, 0, 0, 5, 5, 7, 5, 7, 5]; // head rarities[10] = [255]; aliases[10] = [0]; // numbers rarities[11] = [255]; aliases[11] = [0]; // shapes rarities[12] = [135, 177, 219, 141, 183, 225, 147, 189, 231, 135, 135, 135, 135, 246, 150, 150, 156, 165, 171, 180, 186, 195, 201, 210, 243, 252, 255]; aliases[12] = [1, 2, 3, 4, 5, 6, 7, 8, 13, 3, 6, 14, 15, 16, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 26, 26]; // nose rarities[13] = [255]; aliases[13] = [0]; // accessories rarities[14] = [239, 244, 249, 234, 234, 234, 234, 234, 234, 234, 130, 255, 247]; aliases[14] = [1, 2, 11, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11]; // guns rarities[15] = [75, 180, 165, 120, 60, 150, 105, 195, 45, 225, 75, 45, 195, 120, 255]; aliases[15] = [1, 9, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 14, 12, 14]; // feet rarities[16] = [255]; aliases[16] = [0]; // alphaIndex rarities[17] = [8, 160, 73, 255]; aliases[17] = [2, 3, 3, 3]; } /** EXTERNAL */ /** * mint a token - 90% Player, 10% Wolves * The first 20% are free to claim, the remaining cost $SQUID */ function mint(uint256 amount, bool stake) external payable whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); require(minted + amount <= MAX_TOKENS, "All tokens minted"); require(amount > 0 && amount <= 10, "Invalid mint amount"); if (minted < PAID_TOKENS) { require(minted + amount <= PAID_TOKENS, "All tokens on-sale already sold"); require(amount * MINT_PRICE == msg.value, "Invalid payment amount"); } else { require(msg.value == 0); } uint256 totalSquidCost = 0; uint16[] memory tokenIds = stake ? new uint16[](amount) : new uint16[](0); uint256 seed; for (uint i = 0; i < amount; i++) { minted++; seed = random(minted); generate(minted, seed); address recipient = selectRecipient(seed); if (!stake || recipient != _msgSender()) { _safeMint(recipient, minted); } else { _safeMint(address(arena), minted); tokenIds[i] = minted; } totalSquidCost += mintCost(minted); } if (totalSquidCost > 0) squid.burn(_msgSender(), totalSquidCost); if (stake) arena.addManyToArenaAndPack(_msgSender(), tokenIds); } function mintWhitelist(uint256 amount, address _wallet, bool stake) external payable whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); require(minted + amount <= MAX_TOKENS, "All tokens minted"); require(amount > 0 && amount <= 5, "Invalid mint amount"); require(whiteList[_msgSender()] >= amount, "Invalid Whitelist Amount"); require(amount * WL_MINT_PRICE == msg.value, "Invalid payment amount"); whiteList[_msgSender()] = whiteList[_msgSender()] - amount; uint16[] memory tokenIds = stake ? new uint16[](amount) : new uint16[](0); uint256 seed; for (uint i = 0; i < amount; i++) { minted++; seed = random(minted); _idData[minted] = generate(minted, seed); if (!stake) { _mint(_wallet, minted); } else { _mint(address(arena), minted); tokenIds[i] = minted; } } if (stake) arena.addManyToArenaAndPack(_msgSender(), tokenIds); } /** * the first 20% are paid in ETH * the next 20% are 20000 $SQUID * the next 40% are 40000 $SQUID * the final 20% are 80000 $SQUID * @param tokenId the ID to check the cost of to mint * @return the cost of the given token ID */ function mintCost(uint256 tokenId) public view returns (uint256) { if (tokenId <= PAID_TOKENS) return 0; if (tokenId <= MAX_TOKENS * 2 / 5) return 25000 ether; // XXX if (tokenId <= MAX_TOKENS * 3 / 5) return 75000 ether; // XXX if (tokenId <= MAX_TOKENS * 4 / 5) return 125000 ether; // XXX if (tokenId <= MAX_TOKENS * 9 / 10) return 250000 ether; // XXX return 500000 ether; // XXX } function totalMint() public view returns (uint16) { return minted; } // XXX function transferFrom( address from, address to, uint256 tokenId ) public virtual override { // Hardcode the Arena's approval so that users don't have to waste gas approving if (_msgSender() != address(arena)) require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** INTERNAL */ /** * generates traits for a specific token, checking to make sure it's unique * @param tokenId the id of the token to generate traits for * @param seed a pseudorandom 256 bit number to derive traits from * @return t - a struct of traits for the given token ID */ function generate(uint256 tokenId, uint256 seed) internal returns (PlayerGuard memory t) { t = selectTraits(seed); if (existingCombinations[structToHash(t)] == 0) { tokenTraits[tokenId] = t; existingCombinations[structToHash(t)] = tokenId; return t; } return generate(tokenId, random(seed)); } /** * uses A.J. Walker's Alias algorithm for O(1) rarity table lookup * ensuring O(1) instead of O(n) reduces mint cost by more than 50% * probability & alias tables are generated off-chain beforehand * @param seed portion of the 256 bit seed to remove trait correlation * @param traitType the trait type to select a trait for * @return the ID of the randomly selected trait */ function selectTrait(uint16 seed, uint8 traitType) internal view returns (uint8) { uint8 trait = uint8(seed) % uint8(rarities[traitType].length); if (seed >> 8 < rarities[traitType][trait]) return trait; return aliases[traitType][trait]; } /** * the first 20% (ETH purchases) go to the minter * the remaining 80% have a 10% chance to be given to a random staked guard * @param seed a random value to select a recipient from * @return the address of the recipient (either the minter or the Guard thief's owner) */ function selectRecipient(uint256 seed) internal view returns (address) { if (minted <= PAID_TOKENS || ((seed >> 245) % 10) != 0) return _msgSender(); // top 10 bits haven't been used address thief = arena.randomGuardOwner(seed >> 144); // 144 bits reserved for trait selection if (thief == address(0x0)) return _msgSender(); return thief; } /** * selects the species and all of its traits based on the seed value * @param seed a pseudorandom 256 bit number to derive traits from * @return t - a struct of randomly selected traits */ function selectTraits(uint256 seed) internal view returns (PlayerGuard memory t) { t.isPlayer = (seed & 0xFFFF) % 10 != 0; uint8 shift = t.isPlayer ? 0 : 9; seed >>= 16; t.colors = selectTrait(uint16(seed & 0xFFFF), 0 + shift); seed >>= 16; t.head = selectTrait(uint16(seed & 0xFFFF), 1 + shift); seed >>= 16; t.numbers = selectTrait(uint16(seed & 0xFFFF), 2 + shift); seed >>= 16; t.shapes = selectTrait(uint16(seed & 0xFFFF), 3 + shift); seed >>= 16; t.nose = selectTrait(uint16(seed & 0xFFFF), 4 + shift); seed >>= 16; t.accessories = selectTrait(uint16(seed & 0xFFFF), 5 + shift); seed >>= 16; t.guns = selectTrait(uint16(seed & 0xFFFF), 6 + shift); seed >>= 16; t.feet = selectTrait(uint16(seed & 0xFFFF), 7 + shift); seed >>= 16; t.alphaIndex = selectTrait(uint16(seed & 0xFFFF), 8 + shift); } /** * converts a struct to a 256 bit hash to check for uniqueness * @param s the struct to pack into a hash * @return the 256 bit hash of the struct */ function structToHash(PlayerGuard memory s) internal pure returns (uint256) { return uint256(bytes32( abi.encodePacked( s.isPlayer, s.colors, s.head, s.shapes, s.accessories, s.guns, s.numbers, s.feet, s.alphaIndex ) )); } /** * generates a pseudorandom number * @param seed a value ensure different outcomes for different sources in the same block * @return a pseudorandom value */ function random(uint256 seed) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked( tx.origin, blockhash(block.number - 1), block.timestamp, seed ))); } /** READ */ function getTokenTraits(uint256 tokenId) external view override returns (PlayerGuard memory) { return tokenTraits[tokenId]; } function getPaidTokens() external view override returns (uint256) { return PAID_TOKENS; } /** ADMIN */ function addToWhitelist(address[] memory toWhitelist) external onlyOwner { for(uint256 i = 0; i < toWhitelist.length; i++){ address idToWhitelist = toWhitelist[i]; whiteList[idToWhitelist] = 3; } } /** * called after deployment so that the contract can get random guard thieves * @param _arena the address of the Arena */ function setArena(address _arena) external onlyOwner { arena = IArena(_arena); } /** * allows owner to withdraw funds from minting */ function withdraw() external onlyOwner { payable(owner()).transfer(address(this).balance); } /** * updates the number of tokens for sale */ function setPaidTokens(uint256 _paidTokens) external onlyOwner { PAID_TOKENS = _paidTokens; } /** * enables owner to pause / unpause minting */ function setPaused(bool _paused) external onlyOwner { if (_paused) _pause(); else _unpause(); } /** RENDER */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return traits.tokenURI(tokenId); } } // File: contracts/Arena.sol pragma solidity ^0.8.0; contract Arena is Ownable, IERC721Receiver, Pausable { // maximum alpha score for a Guard uint8 public constant MAX_ALPHA = 8; // struct to store a stake's token, owner, and earning values struct Stake { uint16 tokenId; uint80 value; address owner; } event TokenStaked(address owner, uint256 tokenId, uint256 value); event PlayerClaimed(uint256 tokenId, uint256 earned, bool unstaked); event GuardClaimed(uint256 tokenId, uint256 earned, bool unstaked); // reference to the Squuid NFT contract Squuid squuid; // reference to the $SQUID contract for minting $SQUID earnings SQUID squid; // maps tokenId to stake mapping(uint256 => Stake) public arena; // maps alpha to all Guard stakes with that alpha mapping(uint256 => Stake[]) public pack; // tracks location of each Guard in Pack mapping(uint256 => uint256) public packIndices; // total alpha scores staked uint256 public totalAlphaStaked = 0; // any rewards distributed when no wolves are staked uint256 public unaccountedRewards = 0; // amount of $SQUID due for each alpha point staked uint256 public squidPerAlpha = 0; // player earn 10000 $SQUID per day uint256 public constant DAILY_SQUID_RATE = 5000 ether; // player must have 2 days worth of $SQUID to unstake or else it's too cold uint256 public constant MINIMUM_TO_EXIT = 2 days; // wolves take a 20% tax on all $SQUID claimed uint256 public constant SQUID_CLAIM_TAX_PERCENTAGE = 20; // there will only ever be (roughly) 2.4 billion $SQUID earned through staking uint256 public constant MAXIMUM_GLOBAL_SQUID = 6000000000 ether; // amount of $SQUID earned so far uint256 public totalSquidEarned; // number of Player staked in the Arena uint256 public totalPlayerStaked; // the last time $SQUID was claimed uint256 public lastClaimTimestamp; // emergency rescue to allow unstaking without any checks but without $SQUID bool public rescueEnabled = false; /** * @param _squuid reference to the Squuid NFT contract * @param _squid reference to the $SQUID token */ constructor(address _squuid, address _squid) { squuid = Squuid(_squuid); squid = SQUID(_squid); } /** STAKING */ /** * adds Player and Wolves to the Arena and Pack * @param account the address of the staker * @param tokenIds the IDs of the Player and Wolves to stake */ function addManyToArenaAndPack(address account, uint16[] calldata tokenIds) external { require(account == _msgSender() || _msgSender() == address(squuid), "DONT GIVE YOUR TOKENS AWAY"); for (uint i = 0; i < tokenIds.length; i++) { if (_msgSender() != address(squuid)) { // dont do this step if its a mint + stake require(squuid.ownerOf(tokenIds[i]) == _msgSender(), "AINT YO TOKEN"); squuid.transferFrom(_msgSender(), address(this), tokenIds[i]); } else if (tokenIds[i] == 0) { continue; // there may be gaps in the array for stolen tokens } if (isPlayer(tokenIds[i])) _addPlayerToArena(account, tokenIds[i]); else _addGuardToPack(account, tokenIds[i]); } } /** * adds a single Player to the Arena * @param account the address of the staker * @param tokenId the ID of the Player to add to the Arena */ function _addPlayerToArena(address account, uint256 tokenId) internal whenNotPaused _updateEarnings { arena[tokenId] = Stake({ owner: account, tokenId: uint16(tokenId), value: uint80(block.timestamp) }); totalPlayerStaked += 1; emit TokenStaked(account, tokenId, block.timestamp); } /** * adds a single Guard to the Pack * @param account the address of the staker * @param tokenId the ID of the Guard to add to the Pack */ function _addGuardToPack(address account, uint256 tokenId) internal { uint256 alpha = _alphaForGuard(tokenId); totalAlphaStaked += alpha; // Portion of earnings ranges from 8 to 5 packIndices[tokenId] = pack[alpha].length; // Store the location of the guard in the Pack pack[alpha].push(Stake({ owner: account, tokenId: uint16(tokenId), value: uint80(squidPerAlpha) })); // Add the guard to the Pack emit TokenStaked(account, tokenId, squidPerAlpha); } /** CLAIMING / UNSTAKING */ /** * realize $SQUID earnings and optionally unstake tokens from the Arena / Pack * to unstake a Player it will require it has 2 days worth of $SQUID unclaimed * @param tokenIds the IDs of the tokens to claim earnings from * @param unstake whether or not to unstake ALL of the tokens listed in tokenIds */ function claimManyFromArenaAndPack(uint16[] calldata tokenIds, bool unstake) external whenNotPaused _updateEarnings { uint256 owed = 0; for (uint i = 0; i < tokenIds.length; i++) { if (isPlayer(tokenIds[i])) owed += _claimPlayerFromArena(tokenIds[i], unstake); else owed += _claimGuardFromPack(tokenIds[i], unstake); } if (owed == 0) return; squid.mint(_msgSender(), owed); } /** * realize $SQUID earnings for a single Player and optionally unstake it * if not unstaking, pay a 20% tax to the staked Wolves * if unstaking, there is a 50% chance all $SQUID is stolen * @param tokenId the ID of the Player to claim earnings from * @param unstake whether or not to unstake the Player * @return owed - the amount of $SQUID earned */ function _claimPlayerFromArena(uint256 tokenId, bool unstake) internal returns (uint256 owed) { Stake memory stake = arena[tokenId]; require(stake.owner == _msgSender(), "SWIPER, NO SWIPING"); require(!(unstake && block.timestamp - stake.value < MINIMUM_TO_EXIT), "GONNA BE COLD WITHOUT TWO DAY'S SQUID"); if (totalSquidEarned < MAXIMUM_GLOBAL_SQUID) { owed = (block.timestamp - stake.value) * DAILY_SQUID_RATE / 1 days; } else if (stake.value > lastClaimTimestamp) { owed = 0; // $SQUID production stopped already } else { owed = (lastClaimTimestamp - stake.value) * DAILY_SQUID_RATE / 1 days; // stop earning additional $SQUID if it's all been earned } if (unstake) { if (random(tokenId) & 1 == 1) { // 50% chance of all $SQUID stolen _payGuardTax(owed); owed = 0; } delete arena[tokenId]; squuid.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Player totalPlayerStaked -= 1; } else { _payGuardTax(owed * SQUID_CLAIM_TAX_PERCENTAGE / 100); // percentage tax to staked wolves owed = owed * (100 - SQUID_CLAIM_TAX_PERCENTAGE) / 100; // remainder goes to Player owner arena[tokenId] = Stake({ owner: _msgSender(), tokenId: uint16(tokenId), value: uint80(block.timestamp) }); // reset stake } emit PlayerClaimed(tokenId, owed, unstake); } /** * realize $SQUID earnings for a single Guard and optionally unstake it * Wolves earn $SQUID proportional to their Alpha rank * @param tokenId the ID of the Guard to claim earnings from * @param unstake whether or not to unstake the Guard * @return owed - the amount of $SQUID earned */ function _claimGuardFromPack(uint256 tokenId, bool unstake) internal returns (uint256 owed) { require(squuid.ownerOf(tokenId) == address(this), "AINT A PART OF THE PACK"); uint256 alpha = _alphaForGuard(tokenId); Stake memory stake = pack[alpha][packIndices[tokenId]]; require(stake.owner == _msgSender(), "SWIPER, NO SWIPING"); owed = (alpha) * (squidPerAlpha - stake.value); // Calculate portion of tokens based on Alpha if (unstake) { totalAlphaStaked -= alpha; // Remove Alpha from total staked Stake memory lastStake = pack[alpha][pack[alpha].length - 1]; pack[alpha][packIndices[tokenId]] = lastStake; // Shuffle last Guard to current position packIndices[lastStake.tokenId] = packIndices[tokenId]; pack[alpha].pop(); // Remove duplicate delete packIndices[tokenId]; // Delete old mapping squuid.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // Send back Guard } else { pack[alpha][packIndices[tokenId]] = Stake({ owner: _msgSender(), tokenId: uint16(tokenId), value: uint80(squidPerAlpha) }); // reset stake } emit GuardClaimed(tokenId, owed, unstake); } /** * emergency unstake tokens * @param tokenIds the IDs of the tokens to claim earnings from */ function rescue(uint256[] calldata tokenIds) external { require(rescueEnabled, "RESCUE DISABLED"); uint256 tokenId; Stake memory stake; Stake memory lastStake; uint256 alpha; for (uint i = 0; i < tokenIds.length; i++) { tokenId = tokenIds[i]; if (isPlayer(tokenId)) { stake = arena[tokenId]; require(stake.owner == _msgSender(), "SWIPER, NO SWIPING"); delete arena[tokenId]; squuid.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Player totalPlayerStaked -= 1; emit PlayerClaimed(tokenId, 0, true); } else { alpha = _alphaForGuard(tokenId); stake = pack[alpha][packIndices[tokenId]]; require(stake.owner == _msgSender(), "SWIPER, NO SWIPING"); totalAlphaStaked -= alpha; // Remove Alpha from total staked lastStake = pack[alpha][pack[alpha].length - 1]; pack[alpha][packIndices[tokenId]] = lastStake; // Shuffle last Guard to current position packIndices[lastStake.tokenId] = packIndices[tokenId]; pack[alpha].pop(); // Remove duplicate delete packIndices[tokenId]; // Delete old mapping squuid.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // Send back Guard emit GuardClaimed(tokenId, 0, true); } } } /** ACCOUNTING */ /** * add $SQUID to claimable pot for the Pack * @param amount $SQUID to add to the pot */ function _payGuardTax(uint256 amount) internal { if (totalAlphaStaked == 0) { // if there's no staked wolves unaccountedRewards += amount; // keep track of $SQUID due to wolves return; } // makes sure to include any unaccounted $SQUID squidPerAlpha += (amount + unaccountedRewards) / totalAlphaStaked; unaccountedRewards = 0; } /** * tracks $SQUID earnings to ensure it stops once 2.4 billion is eclipsed */ modifier _updateEarnings() { if (totalSquidEarned < MAXIMUM_GLOBAL_SQUID) { totalSquidEarned += (block.timestamp - lastClaimTimestamp) * totalPlayerStaked * DAILY_SQUID_RATE / 1 days; lastClaimTimestamp = block.timestamp; } _; } /** ADMIN */ /** * allows owner to enable "rescue mode" * simplifies accounting, prioritizes tokens out in emergency */ function setRescueEnabled(bool _enabled) external onlyOwner { rescueEnabled = _enabled; } /** * enables owner to pause / unpause minting */ function setPaused(bool _paused) external onlyOwner { if (_paused) _pause(); else _unpause(); } /** READ ONLY */ /** * checks if a token is a Player * @param tokenId the ID of the token to check * @return player - whether or not a token is a Player */ function isPlayer(uint256 tokenId) public view returns (bool player) { (player, , , , , , , , , ) = squuid.tokenTraits(tokenId); } /** * gets the alpha score for a Guard * @param tokenId the ID of the Guard to get the alpha score for * @return the alpha score of the Guard (5-8) */ function _alphaForGuard(uint256 tokenId) internal view returns (uint8) { ( , , , , , , , , , uint8 alphaIndex) = squuid.tokenTraits(tokenId); return MAX_ALPHA - alphaIndex; // alpha index is 0-3 } /** * chooses a random Guard thief when a newly minted token is stolen * @param seed a random value to choose a Guard from * @return the owner of the randomly selected Guard thief */ function randomGuardOwner(uint256 seed) external view returns (address) { if (totalAlphaStaked == 0) return address(0x0); uint256 bucket = (seed & 0xFFFFFFFF) % totalAlphaStaked; // choose a value from 0 to total alpha staked uint256 cumulative; seed >>= 32; // loop through each bucket of Wolves with the same alpha score for (uint i = MAX_ALPHA - 3; i <= MAX_ALPHA; i++) { cumulative += pack[i].length * i; // if the value is not inside of that bucket, keep going if (bucket >= cumulative) continue; // get the address of a random Guard with that alpha score return pack[i][seed % pack[i].length].owner; } return address(0x0); } /** * generates a pseudorandom number * @param seed a value ensure different outcomes for different sources in the same block * @return a pseudorandom value */ function random(uint256 seed) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked( tx.origin, blockhash(block.number - 1), block.timestamp, seed ))); } function onERC721Received( address, address from, uint256, bytes calldata ) external pure override returns (bytes4) { require(from == address(0x0), "Cannot send tokens to Arena directly"); return IERC721Receiver.onERC721Received.selector; } }
Initializes the contract setting the deployer as the initial owner./
function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } pragma solidity ^0.8.0; constructor() { _setOwner(_msgSender()); }
98,494
// SPDX-License-Identifier: GPL-3.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity 0.6.12; contract BConst { uint public constant BONE = 10**18; uint public constant MIN_BOUND_TOKENS = 2; uint public constant MAX_BOUND_TOKENS = 9; uint public constant MIN_FEE = BONE / 10**6; uint public constant MAX_FEE = BONE / 10; uint public constant MIN_WEIGHT = 1000000000; uint public constant MAX_WEIGHT = BONE * 50; uint public constant MAX_TOTAL_WEIGHT = BONE * 50; uint public constant MIN_BALANCE = BONE / 10**12; uint public constant INIT_POOL_SUPPLY = BONE * 100; uint public constant MIN_BPOW_BASE = 1 wei; uint public constant MAX_BPOW_BASE = (2 * BONE) - 1 wei; uint public constant BPOW_PRECISION = BONE / 10**10; uint public constant MAX_IN_RATIO = BONE / 2; uint public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei; } // SPDX-License-Identifier: GPL-3.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity 0.6.12; import "./BConst.sol"; contract BNum is BConst { function btoi(uint a) internal pure returns (uint) { return a / BONE; } function bfloor(uint a) internal pure returns (uint) { return btoi(a) * BONE; } function badd(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } function bsub(uint a, uint b) internal pure returns (uint) { (uint c, bool flag) = bsubSign(a, b); require(!flag, "ERR_SUB_UNDERFLOW"); return c; } function bsubSign(uint a, uint b) internal pure returns (uint, bool) { if (a >= b) { return (a - b, false); } else { return (b - a, true); } } function bmul(uint a, uint b) internal pure returns (uint) { uint c0 = a * b; require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW"); uint c1 = c0 + (BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint c2 = c1 / BONE; return c2; } function bdiv(uint a, uint b) internal pure returns (uint) { require(b != 0, "ERR_DIV_ZERO"); uint c0 = a * BONE; require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint c1 = c0 + (b / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint c2 = c1 / b; return c2; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "ERR_DIV_ZERO"); return a / b; } // DSMath.wpow function bpowi(uint a, uint n) internal pure returns (uint) { uint z = n % 2 != 0 ? a : BONE; for (n /= 2; n != 0; n /= 2) { a = bmul(a, a); if (n % 2 != 0) { z = bmul(z, a); } } return z; } // Compute b^(e.w) by splitting it into (b^e)*(b^0.w). // Use `bpowi` for `b^e` and `bpowK` for k iterations // of approximation of b^0.w function bpow(uint base, uint exp) internal pure returns (uint) { require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW"); require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH"); uint whole = bfloor(exp); uint remain = bsub(exp, whole); uint wholePow = bpowi(base, btoi(whole)); if (remain == 0) { return wholePow; } uint partialResult = bpowApprox(base, remain, BPOW_PRECISION); return bmul(wholePow, partialResult); } function bpowApprox(uint base, uint exp, uint precision) internal pure returns (uint) { // term 0: uint a = exp; (uint x, bool xneg) = bsubSign(base, BONE); uint term = BONE; uint sum = term; bool negative = false; // term(k) = numer / denom // = (product(a - i - 1, i=1-->k) * x^k) / (k!) // each iteration, multiply previous term by (a-(k-1)) * x / k // continue until term is less than precision for (uint i = 1; term >= precision; i++) { uint bigK = i * BONE; (uint c, bool cneg) = bsubSign(a, bsub(bigK, BONE)); term = bmul(term, bmul(c, x)); term = bdiv(term, bigK); if (term == 0) break; if (xneg) negative = !negative; if (cneg) negative = !negative; if (negative) { sum = bsub(sum, term); } else { sum = badd(sum, term); } } return sum; } } // SPDX-License-Identifier: GPL-3.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity 0.6.12; import "./BNum.sol"; import "../interfaces/BMathInterface.sol"; contract BMath is BConst, BNum, BMathInterface { /********************************************************************************************** // calcSpotPrice // // sP = spotPrice // // bI = tokenBalanceIn ( bI / wI ) 1 // // bO = tokenBalanceOut sP = ----------- * ---------- // // wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcSpotPrice( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint swapFee ) public pure returns (uint spotPrice) { uint numer = bdiv(tokenBalanceIn, tokenWeightIn); uint denom = bdiv(tokenBalanceOut, tokenWeightOut); uint ratio = bdiv(numer, denom); uint scale = bdiv(BONE, bsub(BONE, swapFee)); return (spotPrice = bmul(ratio, scale)); } /********************************************************************************************** // calcOutGivenIn // // aO = tokenAmountOut // // bO = tokenBalanceOut // // bI = tokenBalanceIn / / bI \ (wI / wO) \ // // aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | // // wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcOutGivenIn( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountIn, uint swapFee ) public pure returns (uint tokenAmountOut) { uint weightRatio = bdiv(tokenWeightIn, tokenWeightOut); uint adjustedIn = bsub(BONE, swapFee); adjustedIn = bmul(tokenAmountIn, adjustedIn); uint y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn)); uint foo = bpow(y, weightRatio); uint bar = bsub(BONE, foo); tokenAmountOut = bmul(tokenBalanceOut, bar); return tokenAmountOut; } /********************************************************************************************** // calcInGivenOut // // aI = tokenAmountIn // // bO = tokenBalanceOut / / bO \ (wO / wI) \ // // bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | // // aO = tokenAmountOut aI = \ \ ( bO - aO ) / / // // wI = tokenWeightIn -------------------------------------------- // // wO = tokenWeightOut ( 1 - sF ) // // sF = swapFee // **********************************************************************************************/ function calcInGivenOut( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountOut, uint swapFee ) public pure override returns (uint tokenAmountIn) { uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint diff = bsub(tokenBalanceOut, tokenAmountOut); uint y = bdiv(tokenBalanceOut, diff); uint foo = bpow(y, weightRatio); foo = bsub(foo, BONE); tokenAmountIn = bsub(BONE, swapFee); tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn); return tokenAmountIn; } /********************************************************************************************** // calcPoolOutGivenSingleIn // // pAo = poolAmountOut / \ // // tAi = tokenAmountIn /// / // wI \ \\ \ wI \ // // wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ // // tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS // // tBi = tokenBalanceIn \\ ------------------------------------- / / // // pS = poolSupply \\ tBi / / // // sF = swapFee \ / // **********************************************************************************************/ function calcPoolOutGivenSingleIn( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint tokenAmountIn, uint swapFee ) public pure returns (uint poolAmountOut) { // Charge the trading fee for the proportion of tokenAi /// which is implicitly traded to the other pool tokens. // That proportion is (1- weightTokenIn) // tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee); uint normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee); uint tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz)); uint newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee); uint tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn); // uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply; uint poolRatio = bpow(tokenInRatio, normalizedWeight); uint newPoolSupply = bmul(poolRatio, poolSupply); poolAmountOut = bsub(newPoolSupply, poolSupply); return poolAmountOut; } /********************************************************************************************** // calcSingleInGivenPoolOut // // tAi = tokenAmountIn //(pS + pAo)\ / 1 \\ // // pS = poolSupply || --------- | ^ | --------- || * bI - bI // // pAo = poolAmountOut \\ pS / \(wI / tW)// // // bI = balanceIn tAi = -------------------------------------------- // // wI = weightIn / wI \ // // tW = totalWeight | 1 - ---- | * sF // // sF = swapFee \ tW / // **********************************************************************************************/ function calcSingleInGivenPoolOut( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint poolAmountOut, uint swapFee ) public pure returns (uint tokenAmountIn) { uint normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint newPoolSupply = badd(poolSupply, poolAmountOut); uint poolRatio = bdiv(newPoolSupply, poolSupply); //uint newBalTi = poolRatio^(1/weightTi) * balTi; uint boo = bdiv(BONE, normalizedWeight); uint tokenInRatio = bpow(poolRatio, boo); uint newTokenBalanceIn = bmul(tokenInRatio, tokenBalanceIn); uint tokenAmountInAfterFee = bsub(newTokenBalanceIn, tokenBalanceIn); // Do reverse order of fees charged in joinswap_ExternAmountIn, this way // ``` pAo == joinswap_ExternAmountIn(Ti, joinswap_PoolAmountOut(pAo, Ti)) ``` //uint tAi = tAiAfterFee / (1 - (1-weightTi) * swapFee) ; uint zar = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountIn = bdiv(tokenAmountInAfterFee, bsub(BONE, zar)); return tokenAmountIn; } /********************************************************************************************** // calcSingleOutGivenPoolIn // // tAo = tokenAmountOut / / \\ // // bO = tokenBalanceOut / // pS - pAi \ / 1 \ \\ // // pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || // // ps = poolSupply \ \\ pS / \(wO / tW)/ // // // wI = tokenWeightIn tAo = \ \ // // // tW = totalWeight / / wO \ \ // // sF = swapFee * | 1 - | 1 - ---- | * sF | // // eF = exitFee \ \ tW / / // **********************************************************************************************/ function calcSingleOutGivenPoolIn( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint poolAmountIn, uint swapFee ) public pure returns (uint tokenAmountOut) { uint normalizedWeight = bdiv(tokenWeightOut, totalWeight); uint newPoolSupply = bsub(poolSupply, poolAmountIn); uint poolRatio = bdiv(newPoolSupply, poolSupply); // newBalTo = poolRatio^(1/weightTo) * balTo; uint tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight)); uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut); uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut); // charge swap fee on the output token side //uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee) uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz)); return tokenAmountOut; } /********************************************************************************************** // calcPoolInGivenSingleOut // // pAi = poolAmountIn // / tAo \\ / wO \ \ // // bO = tokenBalanceOut // | bO - -------------------------- |\ | ---- | \ // // tAo = tokenAmountOut pS - || \ 1 - ((1 - (tO / tW)) * sF)/ | ^ \ tW / * pS | // // ps = poolSupply \\ -----------------------------------/ / // // wO = tokenWeightOut pAi = \\ bO / / // // tW = totalWeight // // sF = swapFee // **********************************************************************************************/ function calcPoolInGivenSingleOut( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint tokenAmountOut, uint swapFee ) public pure returns (uint poolAmountIn) { // charge swap fee on the output token side uint normalizedWeight = bdiv(tokenWeightOut, totalWeight); //uint tAoBeforeSwapFee = tAo / (1 - (1-weightTo) * swapFee) ; uint zoo = bsub(BONE, normalizedWeight); uint zar = bmul(zoo, swapFee); uint tokenAmountOutBeforeSwapFee = bdiv(tokenAmountOut, bsub(BONE, zar)); uint newTokenBalanceOut = bsub(tokenBalanceOut, tokenAmountOutBeforeSwapFee); uint tokenOutRatio = bdiv(newTokenBalanceOut, tokenBalanceOut); //uint newPoolSupply = (ratioTo ^ weightTo) * poolSupply; uint poolRatio = bpow(tokenOutRatio, normalizedWeight); uint newPoolSupply = bmul(poolRatio, poolSupply); uint poolAmountIn = bsub(poolSupply, newPoolSupply); return poolAmountIn; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface BMathInterface { function calcInGivenOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountOut, uint256 swapFee ) external pure returns (uint256 tokenAmountIn); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./BMathInterface.sol"; interface BPoolInterface is IERC20, BMathInterface { function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external; function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external; function swapExactAmountIn( address, uint256, address, uint256, uint256 ) external returns (uint256, uint256); function swapExactAmountOut( address, uint256, address, uint256, uint256 ) external returns (uint256, uint256); function joinswapExternAmountIn( address, uint256, uint256 ) external returns (uint256); function joinswapPoolAmountOut( address, uint256, uint256 ) external returns (uint256); function exitswapPoolAmountIn( address, uint256, uint256 ) external returns (uint256); function exitswapExternAmountOut( address, uint256, uint256 ) external returns (uint256); function getDenormalizedWeight(address) external view returns (uint256); function getBalance(address) external view returns (uint256); function getSwapFee() external view returns (uint256); function getTotalDenormalizedWeight() external view returns (uint256); function getCommunityFee() external view returns ( uint256, uint256, uint256, address ); function calcAmountWithCommunityFee( uint256, uint256, address ) external view returns (uint256, uint256); function getRestrictions() external view returns (address); function isPublicSwap() external view returns (bool); function isFinalized() external view returns (bool); function isBound(address t) external view returns (bool); function getCurrentTokens() external view returns (address[] memory tokens); function getFinalTokens() external view returns (address[] memory tokens); function setSwapFee(uint256) external; function setCommunityFeeAndReceiver( uint256, uint256, uint256, address ) external; function setController(address) external; function setPublicSwap(bool) external; function finalize() external; function bind( address, uint256, uint256 ) external; function rebind( address, uint256, uint256 ) external; function unbind(address) external; function callVoting( address voting, bytes4 signature, bytes calldata args, uint256 value ) external; function getMinWeight() external view returns (uint256); function getMaxBoundTokens() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./BPoolInterface.sol"; interface PowerIndexPoolInterface is BPoolInterface { function bind( address, uint256, uint256, uint256, uint256 ) external; function setDynamicWeight( address token, uint256 targetDenorm, uint256 fromTimestamp, uint256 targetTimestamp ) external; function getDynamicWeightSettings(address token) external view returns ( uint256 fromTimestamp, uint256 targetTimestamp, uint256 fromDenorm, uint256 targetDenorm ); function getMinWeight() external view override returns (uint256); } // SPDX-License-Identifier: GPL-3.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/PowerIndexPoolInterface.sol"; import "./interfaces/PowerIndexPoolFactoryInterface.sol"; contract PowerIndexPoolActions { struct Args { uint256 minWeightPerSecond; uint256 maxWeightPerSecond; uint256 swapFee; uint256 communitySwapFee; uint256 communityJoinFee; uint256 communityExitFee; address communityFeeReceiver; bool finalize; } struct TokenConfig { address token; uint256 balance; uint256 targetDenorm; uint256 fromTimestamp; uint256 targetTimestamp; } function create( PowerIndexPoolFactoryInterface factory, string calldata name, string calldata symbol, Args calldata args, TokenConfig[] calldata tokens ) external returns (PowerIndexPoolInterface pool) { pool = factory.newPool(name, symbol, args.minWeightPerSecond, args.maxWeightPerSecond); pool.setSwapFee(args.swapFee); pool.setCommunityFeeAndReceiver( args.communitySwapFee, args.communityJoinFee, args.communityExitFee, args.communityFeeReceiver ); for (uint256 i = 0; i < tokens.length; i++) { TokenConfig memory tokenConfig = tokens[i]; IERC20 token = IERC20(tokenConfig.token); require(token.transferFrom(msg.sender, address(this), tokenConfig.balance), "ERR_TRANSFER_FAILED"); if (token.allowance(address(this), address(pool)) > 0) { token.approve(address(pool), 0); } token.approve(address(pool), tokenConfig.balance); pool.bind( tokenConfig.token, tokenConfig.balance, tokenConfig.targetDenorm, tokenConfig.fromTimestamp, tokenConfig.targetTimestamp ); } if (args.finalize) { pool.finalize(); require(pool.transfer(msg.sender, pool.balanceOf(address(this))), "ERR_TRANSFER_FAILED"); } else { pool.setPublicSwap(true); } pool.setController(msg.sender); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./PowerIndexPoolInterface.sol"; interface PowerIndexPoolFactoryInterface { function newPool( string calldata name, string calldata symbol, uint256 minWeightPerSecond, uint256 maxWeightPerSecond ) external returns (PowerIndexPoolInterface); } // SPDX-License-Identifier: GPL-3.0 // 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 disstributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity 0.6.12; // Builds new Power Index Pools, logging their addresses and providing `isPowerIndexPool(address) -> (bool)` import "./PowerIndexPool.sol"; import "./interfaces/PowerIndexPoolFactoryInterface.sol"; contract PowerIndexPoolFactory is PowerIndexPoolFactoryInterface { event LOG_NEW_POOL(address indexed caller, address indexed pool); mapping(address => bool) public isPowerIndexPool; constructor() public {} function newPool( string calldata name, string calldata symbol, uint256 minWeightPerSecond, uint256 maxWeightPerSecond ) external override returns (PowerIndexPoolInterface) { PowerIndexPool pool = new PowerIndexPool(name, symbol, minWeightPerSecond, maxWeightPerSecond); isPowerIndexPool[address(pool)] = true; emit LOG_NEW_POOL(msg.sender, address(pool)); pool.setController(msg.sender); return PowerIndexPoolInterface(address(pool)); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "./balancer-core/BPool.sol"; import "./interfaces/PowerIndexPoolInterface.sol"; contract PowerIndexPool is BPool { /// @notice The event emitted when a dynamic weight set to token event SetDynamicWeight( address indexed token, uint256 fromDenorm, uint256 targetDenorm, uint256 fromTimestamp, uint256 targetTimestamp ); /// @notice The event emitted when weight per second bounds set event SetWeightPerSecondBounds(uint256 minWeightPerSecond, uint256 maxWeightPerSecond); struct DynamicWeight { uint256 fromTimestamp; uint256 targetTimestamp; uint256 targetDenorm; } /// @dev Mapping for storing dynamic weights settings. fromDenorm stored in _records mapping as denorm variable mapping(address => DynamicWeight) private _dynamicWeights; /// @dev Min weight per second limit uint256 private _minWeightPerSecond; /// @dev Max weight per second limit uint256 private _maxWeightPerSecond; constructor( string memory name, string memory symbol, uint256 minWeightPerSecond, uint256 maxWeightPerSecond ) public BPool(name, symbol) { _minWeightPerSecond = minWeightPerSecond; _maxWeightPerSecond = maxWeightPerSecond; } /*** Controller Interface ***/ /** * @notice Set weight per second bounds by controller * @param minWeightPerSecond Min weight per second * @param maxWeightPerSecond Max weight per second */ function setWeightPerSecondBounds(uint256 minWeightPerSecond, uint256 maxWeightPerSecond) public _logs_ _lock_ { _onlyController(); _minWeightPerSecond = minWeightPerSecond; _maxWeightPerSecond = maxWeightPerSecond; emit SetWeightPerSecondBounds(minWeightPerSecond, maxWeightPerSecond); } /** * @notice Set dynamic weight for token by controller * @param token Token for change settings * @param targetDenorm Target weight. fromDenorm will be fetch by current value of _getDenormWeight * @param fromTimestamp From timestamp of dynamic weight * @param targetTimestamp Target timestamp of dynamic weight */ function setDynamicWeight( address token, uint256 targetDenorm, uint256 fromTimestamp, uint256 targetTimestamp ) public _logs_ _lock_ { _onlyController(); _requireTokenIsBound(token); require(fromTimestamp > block.timestamp, "CANT_SET_PAST_TIMESTAMP"); require(targetTimestamp > fromTimestamp, "TIMESTAMP_INCORRECT_DELTA"); require(targetDenorm >= MIN_WEIGHT && targetDenorm <= MAX_WEIGHT, "TARGET_WEIGHT_BOUNDS"); uint256 fromDenorm = _getDenormWeight(token); uint256 weightPerSecond = _getWeightPerSecond(fromDenorm, targetDenorm, fromTimestamp, targetTimestamp); require(weightPerSecond <= _maxWeightPerSecond, "MAX_WEIGHT_PER_SECOND"); require(weightPerSecond >= _minWeightPerSecond, "MIN_WEIGHT_PER_SECOND"); _records[token].denorm = fromDenorm; _dynamicWeights[token] = DynamicWeight({ fromTimestamp: fromTimestamp, targetTimestamp: targetTimestamp, targetDenorm: targetDenorm }); uint256 denormSum = 0; uint256 len = _tokens.length; for (uint256 i = 0; i < len; i++) { denormSum = badd(denormSum, _dynamicWeights[_tokens[i]].targetDenorm); } require(denormSum <= MAX_TOTAL_WEIGHT, "MAX_TARGET_TOTAL_WEIGHT"); emit SetDynamicWeight(token, fromDenorm, targetDenorm, fromTimestamp, targetTimestamp); } /** * @notice Bind and setDynamicWeight at the same time * @param token Token for bind * @param balance Initial balance * @param targetDenorm Target weight * @param fromTimestamp From timestamp of dynamic weight * @param targetTimestamp Target timestamp of dynamic weight */ function bind( address token, uint256 balance, uint256 targetDenorm, uint256 fromTimestamp, uint256 targetTimestamp ) external _logs_ // _lock_ Bind does not lock because it jumps to `rebind` and `setDynamicWeight`, which does { super.bind(token, balance, MIN_WEIGHT); setDynamicWeight(token, targetDenorm, fromTimestamp, targetTimestamp); } /** * @notice Override parent unbind function * @param token Token for unbind */ function unbind(address token) public override { super.unbind(token); _dynamicWeights[token] = DynamicWeight(0, 0, 0); } /** * @notice Override parent bind function and disable. */ function bind( address, uint256, uint256 ) public override { revert("DISABLED"); // Only new bind function is allowed } /** * @notice Override parent rebind function. Allowed only for calling from bind function * @param token Token for rebind * @param balance Balance for rebind * @param denorm Weight for rebind */ function rebind( address token, uint256 balance, uint256 denorm ) public override { require(denorm == MIN_WEIGHT && _dynamicWeights[token].fromTimestamp == 0, "ONLY_NEW_TOKENS_ALLOWED"); super.rebind(token, balance, denorm); } /*** View Functions ***/ function getDynamicWeightSettings(address token) external view returns ( uint256 fromTimestamp, uint256 targetTimestamp, uint256 fromDenorm, uint256 targetDenorm ) { DynamicWeight storage dw = _dynamicWeights[token]; return (dw.fromTimestamp, dw.targetTimestamp, _records[token].denorm, dw.targetDenorm); } function getWeightPerSecondBounds() external view returns (uint256 minWeightPerSecond, uint256 maxWeightPerSecond) { return (_minWeightPerSecond, _maxWeightPerSecond); } /*** Internal Functions ***/ function _getDenormWeight(address token) internal view override returns (uint256) { DynamicWeight memory dw = _dynamicWeights[token]; uint256 fromDenorm = _records[token].denorm; if (dw.fromTimestamp == 0 || dw.targetDenorm == fromDenorm || block.timestamp <= dw.fromTimestamp) { return fromDenorm; } if (block.timestamp >= dw.targetTimestamp) { return dw.targetDenorm; } uint256 weightPerSecond = _getWeightPerSecond(fromDenorm, dw.targetDenorm, dw.fromTimestamp, dw.targetTimestamp); uint256 deltaCurrentTime = bsub(block.timestamp, dw.fromTimestamp); if (dw.targetDenorm > fromDenorm) { return badd(fromDenorm, deltaCurrentTime * weightPerSecond); } else { return bsub(fromDenorm, deltaCurrentTime * weightPerSecond); } } function _getWeightPerSecond( uint256 fromDenorm, uint256 targetDenorm, uint256 fromTimestamp, uint256 targetTimestamp ) internal pure returns (uint256) { uint256 delta = targetDenorm > fromDenorm ? bsub(targetDenorm, fromDenorm) : bsub(fromDenorm, targetDenorm); return div(delta, bsub(targetTimestamp, fromTimestamp)); } function _getTotalWeight() internal view override returns (uint256) { uint256 sum = 0; uint256 len = _tokens.length; for (uint256 i = 0; i < len; i++) { sum = badd(sum, _getDenormWeight(_tokens[i])); } return sum; } function _addTotalWeight(uint256 _amount) internal virtual override { // storage total weight don't change, it's calculated only by _getTotalWeight() } function _subTotalWeight(uint256 _amount) internal virtual override { // storage total weight don't change, it's calculated only by _getTotalWeight() } } // SPDX-License-Identifier: GPL-3.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity 0.6.12; import "./BToken.sol"; import "./BMath.sol"; import "../interfaces/IPoolRestrictions.sol"; import "../interfaces/BPoolInterface.sol"; contract BPool is BToken, BMath, BPoolInterface { struct Record { bool bound; // is token bound to pool uint index; // private uint denorm; // denormalized weight uint balance; } event LOG_SWAP( address indexed caller, address indexed tokenIn, address indexed tokenOut, uint256 tokenAmountIn, uint256 tokenAmountOut ); event LOG_JOIN( address indexed caller, address indexed tokenIn, uint256 tokenAmountIn ); event LOG_EXIT( address indexed caller, address indexed tokenOut, uint256 tokenAmountOut ); event LOG_CALL( bytes4 indexed sig, address indexed caller, bytes data ) anonymous; event LOG_CALL_VOTING( address indexed voting, bool indexed success, bytes4 indexed inputSig, bytes inputData, bytes outputData ); event LOG_COMMUNITY_FEE( address indexed caller, address indexed receiver, address indexed token, uint256 tokenAmount ); modifier _logs_() { emit LOG_CALL(msg.sig, msg.sender, msg.data); _; } modifier _lock_() { _preventReentrancy(); _mutex = true; _; _mutex = false; } modifier _viewlock_() { _preventReentrancy(); _; } bool private _mutex; address private _controller; // has CONTROL role bool private _publicSwap; // true if PUBLIC can call SWAP functions address private _wrapper; // can join, exit and swaps when _wrapperMode is true bool private _wrapperMode; IPoolRestrictions private _restrictions; // `setSwapFee` and `finalize` require CONTROL // `finalize` sets `PUBLIC can SWAP`, `PUBLIC can JOIN` uint private _swapFee; uint private _communitySwapFee; uint private _communityJoinFee; uint private _communityExitFee; address private _communityFeeReceiver; bool private _finalized; address[] internal _tokens; mapping(address => Record) internal _records; uint internal _totalWeight; mapping(address => uint256) internal _lastSwapBlock; constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _controller = msg.sender; _swapFee = MIN_FEE; _communitySwapFee = 0; _communityJoinFee = 0; _communityExitFee = 0; _publicSwap = false; _finalized = false; } function isPublicSwap() external view override returns (bool) { return _publicSwap; } function isFinalized() external view override returns (bool) { return _finalized; } function isBound(address t) external view override returns (bool) { return _records[t].bound; } function getNumTokens() external view returns (uint) { return _tokens.length; } function getCurrentTokens() external view override _viewlock_ returns (address[] memory tokens) { return _tokens; } function getFinalTokens() external view override _viewlock_ returns (address[] memory tokens) { _requireContractIsFinalized(); return _tokens; } function getDenormalizedWeight(address token) external view override _viewlock_ returns (uint) { _requireTokenIsBound(token); return _getDenormWeight(token); } function getTotalDenormalizedWeight() external view override _viewlock_ returns (uint) { return _getTotalWeight(); } function getNormalizedWeight(address token) external view _viewlock_ returns (uint) { _requireTokenIsBound(token); return bdiv(_getDenormWeight(token), _getTotalWeight()); } function getBalance(address token) external view override _viewlock_ returns (uint) { _requireTokenIsBound(token); return _records[token].balance; } function getSwapFee() external view override _viewlock_ returns (uint) { return _swapFee; } function getCommunityFee() external view override _viewlock_ returns (uint communitySwapFee, uint communityJoinFee, uint communityExitFee, address communityFeeReceiver) { return (_communitySwapFee, _communityJoinFee, _communityExitFee, _communityFeeReceiver); } function getController() external view _viewlock_ returns (address) { return _controller; } function getWrapper() external view _viewlock_ returns (address) { return _wrapper; } function getWrapperMode() external view _viewlock_ returns (bool) { return _wrapperMode; } function getRestrictions() external view override _viewlock_ returns (address) { return address(_restrictions); } function setSwapFee(uint swapFee) external override _logs_ _lock_ { _onlyController(); _requireFeeInBounds(swapFee); _swapFee = swapFee; } function setCommunityFeeAndReceiver( uint communitySwapFee, uint communityJoinFee, uint communityExitFee, address communityFeeReceiver ) external override _logs_ _lock_ { _onlyController(); _requireFeeInBounds(communitySwapFee); _requireFeeInBounds(communityJoinFee); _requireFeeInBounds(communityExitFee); _communitySwapFee = communitySwapFee; _communityJoinFee = communityJoinFee; _communityExitFee = communityExitFee; _communityFeeReceiver = communityFeeReceiver; } function setRestrictions(IPoolRestrictions restrictions) external _logs_ _lock_ { _onlyController(); _restrictions = restrictions; } function setController(address manager) external override _logs_ _lock_ { _onlyController(); _controller = manager; } function setPublicSwap(bool public_) external override _logs_ _lock_ { _requireContractIsNotFinalized(); _onlyController(); _publicSwap = public_; } function setWrapper(address wrapper, bool wrapperMode) external _logs_ _lock_ { _onlyController(); _wrapper = wrapper; _wrapperMode = wrapperMode; } function finalize() external override _logs_ _lock_ { _onlyController(); _requireContractIsNotFinalized(); require(_tokens.length >= MIN_BOUND_TOKENS, "MIN_TOKENS"); _finalized = true; _publicSwap = true; _mintPoolShare(INIT_POOL_SUPPLY); _pushPoolShare(msg.sender, INIT_POOL_SUPPLY); } function callVoting(address voting, bytes4 signature, bytes calldata args, uint256 value) external override _logs_ _lock_ { require(_restrictions.isVotingSignatureAllowed(voting, signature), "NOT_ALLOWED_SIG"); _onlyController(); (bool success, bytes memory data) = voting.call{ value: value }(abi.encodePacked(signature, args)); require(success, "NOT_SUCCESS"); emit LOG_CALL_VOTING(voting, success, signature, args, data); } function bind(address token, uint balance, uint denorm) public override virtual _logs_ // _lock_ Bind does not lock because it jumps to `rebind`, which does { _onlyController(); require(!_records[token].bound, "IS_BOUND"); require(_tokens.length < MAX_BOUND_TOKENS, "MAX_TOKENS"); _records[token] = Record({ bound: true, index: _tokens.length, denorm: 0, // balance and denorm will be validated balance: 0 // and set by `rebind` }); _tokens.push(token); rebind(token, balance, denorm); } function rebind(address token, uint balance, uint denorm) public override virtual _logs_ _lock_ { _onlyController(); _requireTokenIsBound(token); require(denorm >= MIN_WEIGHT && denorm <= MAX_WEIGHT, "WEIGHT_BOUNDS"); require(balance >= MIN_BALANCE, "MIN_BALANCE"); // Adjust the denorm and totalWeight uint oldWeight = _records[token].denorm; if (denorm > oldWeight) { _addTotalWeight(bsub(denorm, oldWeight)); } else if (denorm < oldWeight) { _subTotalWeight(bsub(oldWeight, denorm)); } _records[token].denorm = denorm; // Adjust the balance record and actual token balance uint oldBalance = _records[token].balance; _records[token].balance = balance; if (balance > oldBalance) { _pullUnderlying(token, msg.sender, bsub(balance, oldBalance)); } else if (balance < oldBalance) { uint tokenBalanceWithdrawn = bsub(oldBalance, balance); _pushUnderlying(token, msg.sender, tokenBalanceWithdrawn); } } function unbind(address token) public override virtual _logs_ _lock_ { _onlyController(); _requireTokenIsBound(token); uint tokenBalance = _records[token].balance; _subTotalWeight(_records[token].denorm); // Swap the token-to-unbind with the last token, // then delete the last token uint index = _records[token].index; uint last = _tokens.length - 1; _tokens[index] = _tokens[last]; _records[_tokens[index]].index = index; _tokens.pop(); _records[token] = Record({ bound: false, index: 0, denorm: 0, balance: 0 }); _pushUnderlying(token, msg.sender, tokenBalance); } // Absorb any tokens that have been sent to this contract into the pool function gulp(address token) external _logs_ _lock_ { _requireTokenIsBound(token); _records[token].balance = IERC20(token).balanceOf(address(this)); } function getSpotPrice(address tokenIn, address tokenOut) external view _viewlock_ returns (uint spotPrice) { require(_records[tokenIn].bound && _records[tokenOut].bound, "NOT_BOUND"); Record storage inRecord = _records[tokenIn]; Record storage outRecord = _records[tokenOut]; return calcSpotPrice(inRecord.balance, _getDenormWeight(tokenIn), outRecord.balance, _getDenormWeight(tokenOut), _swapFee); } function getSpotPriceSansFee(address tokenIn, address tokenOut) external view _viewlock_ returns (uint spotPrice) { _requireTokenIsBound(tokenIn); _requireTokenIsBound(tokenOut); Record storage inRecord = _records[tokenIn]; Record storage outRecord = _records[tokenOut]; return calcSpotPrice(inRecord.balance, _getDenormWeight(tokenIn), outRecord.balance, _getDenormWeight(tokenOut), 0); } function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn) external override _logs_ _lock_ { _preventSameTxOrigin(); _onlyWrapperOrNotWrapperMode(); _requireContractIsFinalized(); uint poolTotal = totalSupply(); uint ratio = bdiv(poolAmountOut, poolTotal); _requireMathApprox(ratio); for (uint i = 0; i < _tokens.length; i++) { address t = _tokens[i]; uint bal = _records[t].balance; uint tokenAmountIn = bmul(ratio, bal); _requireMathApprox(tokenAmountIn); require(tokenAmountIn <= maxAmountsIn[i], "LIMIT_IN"); _records[t].balance = badd(_records[t].balance, tokenAmountIn); emit LOG_JOIN(msg.sender, t, tokenAmountIn); _pullUnderlying(t, msg.sender, tokenAmountIn); } (uint poolAmountOutAfterFee, uint poolAmountOutFee) = calcAmountWithCommunityFee( poolAmountOut, _communityJoinFee, msg.sender ); _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOutAfterFee); _pushPoolShare(_communityFeeReceiver, poolAmountOutFee); emit LOG_COMMUNITY_FEE(msg.sender, _communityFeeReceiver, address(this), poolAmountOutFee); } function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external override _logs_ _lock_ { _preventSameTxOrigin(); _onlyWrapperOrNotWrapperMode(); _requireContractIsFinalized(); (uint poolAmountInAfterFee, uint poolAmountInFee) = calcAmountWithCommunityFee( poolAmountIn, _communityExitFee, msg.sender ); uint poolTotal = totalSupply(); uint ratio = bdiv(poolAmountInAfterFee, poolTotal); _requireMathApprox(ratio); _pullPoolShare(msg.sender, poolAmountIn); _pushPoolShare(_communityFeeReceiver, poolAmountInFee); _burnPoolShare(poolAmountInAfterFee); for (uint i = 0; i < _tokens.length; i++) { address t = _tokens[i]; uint bal = _records[t].balance; uint tokenAmountOut = bmul(ratio, bal); _requireMathApprox(tokenAmountOut); require(tokenAmountOut >= minAmountsOut[i], "LIMIT_OUT"); _records[t].balance = bsub(_records[t].balance, tokenAmountOut); emit LOG_EXIT(msg.sender, t, tokenAmountOut); _pushUnderlying(t, msg.sender, tokenAmountOut); } emit LOG_COMMUNITY_FEE(msg.sender, _communityFeeReceiver, address(this), poolAmountInFee); } function swapExactAmountIn( address tokenIn, uint tokenAmountIn, address tokenOut, uint minAmountOut, uint maxPrice ) external override _logs_ _lock_ returns (uint tokenAmountOut, uint spotPriceAfter) { _preventSameTxOrigin(); _onlyWrapperOrNotWrapperMode(); _requireTokenIsBound(tokenIn); _requireTokenIsBound(tokenOut); require(_publicSwap, "NOT_PUBLIC"); Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; uint spotPriceBefore = calcSpotPrice( inRecord.balance, _getDenormWeight(tokenIn), outRecord.balance, _getDenormWeight(tokenOut), _swapFee ); require(spotPriceBefore <= maxPrice, "LIMIT_PRICE"); (uint tokenAmountInAfterFee, uint tokenAmountInFee) = calcAmountWithCommunityFee( tokenAmountIn, _communitySwapFee, msg.sender ); require(tokenAmountInAfterFee <= bmul(inRecord.balance, MAX_IN_RATIO), "MAX_IN_RATIO"); tokenAmountOut = calcOutGivenIn( inRecord.balance, _getDenormWeight(tokenIn), outRecord.balance, _getDenormWeight(tokenOut), tokenAmountInAfterFee, _swapFee ); require(tokenAmountOut >= minAmountOut, "LIMIT_OUT"); inRecord.balance = badd(inRecord.balance, tokenAmountInAfterFee); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); spotPriceAfter = calcSpotPrice( inRecord.balance, _getDenormWeight(tokenIn), outRecord.balance, _getDenormWeight(tokenOut), _swapFee ); require( spotPriceAfter >= spotPriceBefore && spotPriceBefore <= bdiv(tokenAmountInAfterFee, tokenAmountOut), "MATH_APPROX" ); require(spotPriceAfter <= maxPrice, "LIMIT_PRICE"); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountInAfterFee, tokenAmountOut); _pullCommunityFeeUnderlying(tokenIn, msg.sender, tokenAmountInFee); _pullUnderlying(tokenIn, msg.sender, tokenAmountInAfterFee); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); emit LOG_COMMUNITY_FEE(msg.sender, _communityFeeReceiver, tokenIn, tokenAmountInFee); return (tokenAmountOut, spotPriceAfter); } function swapExactAmountOut( address tokenIn, uint maxAmountIn, address tokenOut, uint tokenAmountOut, uint maxPrice ) external override _logs_ _lock_ returns (uint tokenAmountIn, uint spotPriceAfter) { _preventSameTxOrigin(); _onlyWrapperOrNotWrapperMode(); _requireTokenIsBound(tokenIn); _requireTokenIsBound(tokenOut); require(_publicSwap, "NOT_PUBLIC"); Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; require(tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO), "OUT_RATIO"); uint spotPriceBefore = calcSpotPrice( inRecord.balance, _getDenormWeight(tokenIn), outRecord.balance, _getDenormWeight(tokenOut), _swapFee ); require(spotPriceBefore <= maxPrice, "LIMIT_PRICE"); (uint tokenAmountOutAfterFee, uint tokenAmountOutFee) = calcAmountWithCommunityFee( tokenAmountOut, _communitySwapFee, msg.sender ); tokenAmountIn = calcInGivenOut( inRecord.balance, _getDenormWeight(tokenIn), outRecord.balance, _getDenormWeight(tokenOut), tokenAmountOut, _swapFee ); require(tokenAmountIn <= maxAmountIn, "LIMIT_IN"); inRecord.balance = badd(inRecord.balance, tokenAmountIn); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); spotPriceAfter = calcSpotPrice( inRecord.balance, _getDenormWeight(tokenIn), outRecord.balance, _getDenormWeight(tokenOut), _swapFee ); require( spotPriceAfter >= spotPriceBefore && spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOutAfterFee), "MATH_APPROX" ); require(spotPriceAfter <= maxPrice, "LIMIT_PRICE"); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOutAfterFee); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); _pushUnderlying(tokenOut, msg.sender, tokenAmountOutAfterFee); _pushUnderlying(tokenOut, _communityFeeReceiver, tokenAmountOutFee); emit LOG_COMMUNITY_FEE(msg.sender, _communityFeeReceiver, tokenOut, tokenAmountOutFee); return (tokenAmountIn, spotPriceAfter); } function joinswapExternAmountIn(address tokenIn, uint tokenAmountIn, uint minPoolAmountOut) external override _logs_ _lock_ returns (uint poolAmountOut) { _preventSameTxOrigin(); _requireContractIsFinalized(); _onlyWrapperOrNotWrapperMode(); _requireTokenIsBound(tokenIn); require(tokenAmountIn <= bmul(_records[tokenIn].balance, MAX_IN_RATIO), "MAX_IN_RATIO"); (uint tokenAmountInAfterFee, uint tokenAmountInFee) = calcAmountWithCommunityFee( tokenAmountIn, _communityJoinFee, msg.sender ); Record storage inRecord = _records[tokenIn]; poolAmountOut = calcPoolOutGivenSingleIn( inRecord.balance, _getDenormWeight(tokenIn), _totalSupply, _getTotalWeight(), tokenAmountInAfterFee, _swapFee ); require(poolAmountOut >= minPoolAmountOut, "LIMIT_OUT"); inRecord.balance = badd(inRecord.balance, tokenAmountInAfterFee); emit LOG_JOIN(msg.sender, tokenIn, tokenAmountInAfterFee); _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); _pullCommunityFeeUnderlying(tokenIn, msg.sender, tokenAmountInFee); _pullUnderlying(tokenIn, msg.sender, tokenAmountInAfterFee); emit LOG_COMMUNITY_FEE(msg.sender, _communityFeeReceiver, tokenIn, tokenAmountInFee); return poolAmountOut; } function joinswapPoolAmountOut(address tokenIn, uint poolAmountOut, uint maxAmountIn) external override _logs_ _lock_ returns (uint tokenAmountIn) { _preventSameTxOrigin(); _requireContractIsFinalized(); _onlyWrapperOrNotWrapperMode(); _requireTokenIsBound(tokenIn); Record storage inRecord = _records[tokenIn]; (uint poolAmountOutAfterFee, uint poolAmountOutFee) = calcAmountWithCommunityFee( poolAmountOut, _communityJoinFee, msg.sender ); tokenAmountIn = calcSingleInGivenPoolOut( inRecord.balance, _getDenormWeight(tokenIn), _totalSupply, _getTotalWeight(), poolAmountOut, _swapFee ); _requireMathApprox(tokenAmountIn); require(tokenAmountIn <= maxAmountIn, "LIMIT_IN"); require(tokenAmountIn <= bmul(_records[tokenIn].balance, MAX_IN_RATIO), "MAX_IN_RATIO"); inRecord.balance = badd(inRecord.balance, tokenAmountIn); emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn); _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOutAfterFee); _pushPoolShare(_communityFeeReceiver, poolAmountOutFee); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); emit LOG_COMMUNITY_FEE(msg.sender, _communityFeeReceiver, address(this), poolAmountOutFee); return tokenAmountIn; } function exitswapPoolAmountIn(address tokenOut, uint poolAmountIn, uint minAmountOut) external override _logs_ _lock_ returns (uint tokenAmountOut) { _preventSameTxOrigin(); _requireContractIsFinalized(); _onlyWrapperOrNotWrapperMode(); _requireTokenIsBound(tokenOut); Record storage outRecord = _records[tokenOut]; tokenAmountOut = calcSingleOutGivenPoolIn( outRecord.balance, _getDenormWeight(tokenOut), _totalSupply, _getTotalWeight(), poolAmountIn, _swapFee ); require(tokenAmountOut >= minAmountOut, "LIMIT_OUT"); require(tokenAmountOut <= bmul(_records[tokenOut].balance, MAX_OUT_RATIO), "OUT_RATIO"); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); (uint tokenAmountOutAfterFee, uint tokenAmountOutFee) = calcAmountWithCommunityFee( tokenAmountOut, _communityExitFee, msg.sender ); emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOutAfterFee); _pullPoolShare(msg.sender, poolAmountIn); _burnPoolShare(poolAmountIn); _pushUnderlying(tokenOut, msg.sender, tokenAmountOutAfterFee); _pushUnderlying(tokenOut, _communityFeeReceiver, tokenAmountOutFee); emit LOG_COMMUNITY_FEE(msg.sender, _communityFeeReceiver, tokenOut, tokenAmountOutFee); return tokenAmountOutAfterFee; } function exitswapExternAmountOut(address tokenOut, uint tokenAmountOut, uint maxPoolAmountIn) external override _logs_ _lock_ returns (uint poolAmountIn) { _preventSameTxOrigin(); _requireContractIsFinalized(); _onlyWrapperOrNotWrapperMode(); _requireTokenIsBound(tokenOut); require(tokenAmountOut <= bmul(_records[tokenOut].balance, MAX_OUT_RATIO), "OUT_RATIO"); Record storage outRecord = _records[tokenOut]; (uint tokenAmountOutAfterFee, uint tokenAmountOutFee) = calcAmountWithCommunityFee( tokenAmountOut, _communityExitFee, msg.sender ); poolAmountIn = calcPoolInGivenSingleOut( outRecord.balance, _getDenormWeight(tokenOut), _totalSupply, _getTotalWeight(), tokenAmountOut, _swapFee ); _requireMathApprox(poolAmountIn); require(poolAmountIn <= maxPoolAmountIn, "LIMIT_IN"); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOutAfterFee); _pullPoolShare(msg.sender, poolAmountIn); _burnPoolShare(poolAmountIn); _pushUnderlying(tokenOut, msg.sender, tokenAmountOutAfterFee); _pushUnderlying(tokenOut, _communityFeeReceiver, tokenAmountOutFee); emit LOG_COMMUNITY_FEE(msg.sender, _communityFeeReceiver, tokenOut, tokenAmountOutFee); return poolAmountIn; } // == // 'Underlying' token-manipulation functions make external calls but are NOT locked // You must `_lock_` or otherwise ensure reentry-safety function _pullUnderlying(address erc20, address from, uint amount) internal { bool xfer = IERC20(erc20).transferFrom(from, address(this), amount); require(xfer, "ERC20_FALSE"); } function _pushUnderlying(address erc20, address to, uint amount) internal { bool xfer = IERC20(erc20).transfer(to, amount); require(xfer, "ERC20_FALSE"); } function _pullCommunityFeeUnderlying(address erc20, address from, uint amount) internal { bool xfer = IERC20(erc20).transferFrom(from, _communityFeeReceiver, amount); require(xfer, "ERC20_FALSE"); } function _pullPoolShare(address from, uint amount) internal { _pull(from, amount); } function _pushPoolShare(address to, uint amount) internal { _push(to, amount); } function _mintPoolShare(uint amount) internal { if(address(_restrictions) != address(0)) { uint maxTotalSupply = _restrictions.getMaxTotalSupply(address(this)); require(badd(_totalSupply, amount) <= maxTotalSupply, "MAX_SUPPLY"); } _mint(amount); } function _burnPoolShare(uint amount) internal { _burn(amount); } function _requireTokenIsBound(address token) internal view { require(_records[token].bound, "NOT_BOUND"); } function _onlyController() internal view { require(msg.sender == _controller, "NOT_CONTROLLER"); } function _requireContractIsNotFinalized() internal view { require(!_finalized, "IS_FINALIZED"); } function _requireContractIsFinalized() internal view { require(_finalized, "NOT_FINALIZED"); } function _requireFeeInBounds(uint256 _fee) internal pure { require(_fee >= MIN_FEE && _fee <= MAX_FEE, "FEE_BOUNDS"); } function _requireMathApprox(uint256 _value) internal pure { require(_value != 0, "MATH_APPROX"); } function _preventReentrancy() internal view { require(!_mutex, "REENTRY"); } function _onlyWrapperOrNotWrapperMode() internal view { require(!_wrapperMode || msg.sender == _wrapper, "ONLY_WRAPPER"); } function _preventSameTxOrigin() internal { require(block.number > _lastSwapBlock[tx.origin], "SAME_TX_ORIGIN"); _lastSwapBlock[tx.origin] = block.number; } function _getDenormWeight(address token) internal view virtual returns (uint) { return _records[token].denorm; } function _getTotalWeight() internal view virtual returns (uint) { return _totalWeight; } function _addTotalWeight(uint _amount) internal virtual { _totalWeight = badd(_totalWeight, _amount); require(_totalWeight <= MAX_TOTAL_WEIGHT, "MAX_TOTAL_WEIGHT"); } function _subTotalWeight(uint _amount) internal virtual { _totalWeight = bsub(_totalWeight, _amount); } function calcAmountWithCommunityFee( uint tokenAmountIn, uint communityFee, address operator ) public view override returns (uint tokenAmountInAfterFee, uint tokenAmountFee) { if (address(_restrictions) != address(0) && _restrictions.isWithoutFee(operator)) { return (tokenAmountIn, 0); } uint adjustedIn = bsub(BONE, communityFee); tokenAmountInAfterFee = bmul(tokenAmountIn, adjustedIn); tokenAmountFee = bsub(tokenAmountIn, tokenAmountInAfterFee); return (tokenAmountInAfterFee, tokenAmountFee); } function getMinWeight() external view override returns (uint) { return MIN_WEIGHT; } function getMaxBoundTokens() external view override returns (uint) { return MAX_BOUND_TOKENS; } } // SPDX-License-Identifier: GPL-3.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./BNum.sol"; contract BTokenBase is BNum { mapping(address => uint) internal _balance; mapping(address => mapping(address=>uint)) internal _allowance; uint internal _totalSupply; event Approval(address indexed src, address indexed dst, uint amt); event Transfer(address indexed src, address indexed dst, uint amt); function _mint(uint amt) internal { _balance[address(this)] = badd(_balance[address(this)], amt); _totalSupply = badd(_totalSupply, amt); emit Transfer(address(0), address(this), amt); } function _burn(uint amt) internal { require(_balance[address(this)] >= amt, "ERR_INSUFFICIENT_BAL"); _balance[address(this)] = bsub(_balance[address(this)], amt); _totalSupply = bsub(_totalSupply, amt); emit Transfer(address(this), address(0), amt); } function _move(address src, address dst, uint amt) internal { require(_balance[src] >= amt, "ERR_INSUFFICIENT_BAL"); _validateAddress(src); _validateAddress(dst); _balance[src] = bsub(_balance[src], amt); _balance[dst] = badd(_balance[dst], amt); emit Transfer(src, dst, amt); } function _push(address to, uint amt) internal { _move(address(this), to, amt); } function _pull(address from, uint amt) internal { _move(from, address(this), amt); } function _validateAddress(address addr) internal { require(addr != address(0), "ERR_NULL_ADDRESS"); } } contract BToken is BTokenBase, IERC20 { string internal _name; string internal _symbol; uint8 private _decimals = 18; function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } function allowance(address src, address dst) external override view returns (uint) { return _allowance[src][dst]; } function balanceOf(address whom) external override view returns (uint) { return _balance[whom]; } function totalSupply() public override view returns (uint) { return _totalSupply; } function approve(address dst, uint amt) external override returns (bool) { _validateAddress(dst); _allowance[msg.sender][dst] = amt; emit Approval(msg.sender, dst, amt); return true; } function increaseApproval(address dst, uint amt) external returns (bool) { _validateAddress(dst); _allowance[msg.sender][dst] = badd(_allowance[msg.sender][dst], amt); emit Approval(msg.sender, dst, _allowance[msg.sender][dst]); return true; } function decreaseApproval(address dst, uint amt) external returns (bool) { _validateAddress(dst); uint oldValue = _allowance[msg.sender][dst]; if (amt > oldValue) { _allowance[msg.sender][dst] = 0; } else { _allowance[msg.sender][dst] = bsub(oldValue, amt); } emit Approval(msg.sender, dst, _allowance[msg.sender][dst]); return true; } function transfer(address dst, uint amt) external override returns (bool) { _move(msg.sender, dst, amt); return true; } function transferFrom(address src, address dst, uint amt) external override returns (bool) { require(msg.sender == src || amt <= _allowance[src][msg.sender], "ERR_BTOKEN_BAD_CALLER"); _move(src, dst, amt); if (msg.sender != src && _allowance[src][msg.sender] != uint256(-1)) { _allowance[src][msg.sender] = bsub(_allowance[src][msg.sender], amt); emit Approval(src, msg.sender, _allowance[src][msg.sender]); } return true; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IPoolRestrictions { function getMaxTotalSupply(address _pool) external view returns (uint256); function isVotingSignatureAllowed(address _votingAddress, bytes4 _signature) external view returns (bool); function isVotingSenderAllowed(address _votingAddress, address _sender) external view returns (bool); function isWithoutFee(address _addr) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract Reservoir is Ownable { constructor() public Ownable() {} function setApprove( address _token, address _to, uint256 _amount ) external onlyOwner { IERC20(_token).approve(_to, _amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface WrappedPiErc20Interface is IERC20 { function deposit(uint256 _amount) external; function withdraw(uint256 _amount) external; function changeRouter(address _newRouter) external; function approveToken(address _to, uint256 _amount) external; function callVoting( address voting, bytes4 signature, bytes calldata args, uint256 value ) external; function getWrappedBalance() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface TokenInterface is IERC20 { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IMigrator { // Perform LP token migration from legacy UniswapV2 to PowerSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // PowerSwap must mint EXACTLY the same amount of PowerSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token, uint8 poolType) external returns (IERC20); } // SPDX-License-Identifier: GPL-3.0 // 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 disstributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity 0.6.12; // Builds new BPools, logging their addresses and providing `isBPool(address) -> (bool)` import "./BPool.sol"; contract BFactory { event LOG_NEW_POOL( address indexed caller, address indexed pool ); mapping(address => bool) public isBPool; constructor() public { } function newBPool(string calldata name, string calldata symbol) external returns (BPool) { BPool bpool = new BPool(name, symbol); isBPool[address(bpool)] = true; emit LOG_NEW_POOL(msg.sender, address(bpool)); bpool.setController(msg.sender); return bpool; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./BPoolInterface.sol"; interface BFactoryInterface { function newBPool(string calldata name, string calldata symbol) external returns (BPoolInterface); }
calcSingleOutGivenPoolIn tAo = tokenAmountOut / / \\ bO = tokenBalanceOut / pS - pAi \ / 1 \ \\ pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | b0 || ps = poolSupply \ \\ pS / \(wO / tW)/ wI = tokenWeightIn tAo = \ \ tW = totalWeight / / wO \ \ sF = swapFee | 1 - | 1 - ---- | sF | eF = exitFee \ \ tW / / / newBalTo = poolRatio^(1/weightTo) balTo; charge swap fee on the output token sideuint tAo = tAoBeforeSwapFee (1 - (1-weightTo) swapFee)
function calcSingleOutGivenPoolIn( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint poolAmountIn, uint swapFee ) public pure returns (uint tokenAmountOut) { uint normalizedWeight = bdiv(tokenWeightOut, totalWeight); uint newPoolSupply = bsub(poolSupply, poolAmountIn); uint poolRatio = bdiv(newPoolSupply, poolSupply); uint tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight)); uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut); uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut); uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz)); return tokenAmountOut; }
11,925,649
pragma solidity ^0.4.0; import "./Token.sol"; import "./NettingChannelContract.sol"; library ChannelManagerLibrary { struct Data { mapping(bytes32 => address) channel_addresses; Token token; } /// @notice Get the address of the unique channel of two parties. /// @param caller_address The address of the caller /// @param partner The address of the partner /// @return The address of the NettingChannelContract of the two parties. function getChannelWith(Data storage self, address caller_address, address partner) constant returns (address) { bytes32 party_hash = partyHash(caller_address, partner); return self.channel_addresses[party_hash]; } /// @notice Create a new payment channel between two parties /// @param partner The address of the partner /// @param settle_timeout The settle timeout in blocks /// @return The address of the NettingChannelContract. function newChannel( Data storage self, address caller_address, address partner, uint settle_timeout) returns (address channel_address) { channel_address = new NettingChannelContract( self.token, caller_address, partner, settle_timeout ); self.channel_addresses[partyHash(caller_address, partner)] = channel_address; } /// @notice Remove a channel after it's been settled /// @param caller_address address of the caller /// @param partner of the partner function deleteChannel( Data storage self, address caller_address, address partner) internal { // remove channel from channel_addresses. self.channel_addresses[partyHash(caller_address, partner)] = 0x0; } /// @notice Get the hash of the two addresses /// @param address_one address of one party /// @param address_two of the other party /// @return The sha3 hash of both parties sorted by size of address function partyHash(address address_one, address address_two) private constant returns (bytes32) { if (address_one < address_two) { return sha3(address_one, address_two); } else if (address_one > address_two){ return sha3(address_two, address_one); } else { throw; // if the two addresses provided are identical } } /// @notice Check if a contract is deployed at given address /// @param _addr address to check for a deployed contract /// @return if contract exists, false if not function contractExists(Data storage self, address _addr) internal constant returns (bool) { uint size; assembly { size := extcodesize(_addr) } if (size > 0) { return true; } } }
Create a new payment channel between two parties partner The address of the partner settle_timeout The settle timeout in blocks return The address of the NettingChannelContract.
function newChannel( Data storage self, address caller_address, address partner, uint settle_timeout) returns (address channel_address) { channel_address = new NettingChannelContract( self.token, caller_address, partner, settle_timeout ); self.channel_addresses[partyHash(caller_address, partner)] = channel_address; }
1,845,120
pragma solidity ^0.8; import "./IKlerosLiquid.sol"; import "./ITokenController.sol"; import "../arbitration/IArbitrable.sol"; import "../arbitration/IArbitrator.sol"; /** * @title ERC20 interface */ interface IPinakion { function balanceOf(address who) external view returns (uint256); } contract KlerosV1Governor is IArbitrable, ITokenController { struct DisputeData { uint256 klerosLiquidDisputeID; bool ruled; } IArbitrator public immutable foreignGateway; IKlerosLiquid public immutable klerosLiquid; address public governor; mapping(uint256 => uint256) public klerosLiquidDisputeIDtoGatewayDisputeID; mapping(uint256 => DisputeData) public disputes; // disputes[gatewayDisputeID] mapping(address => uint256) public frozenTokens; // frozenTokens[account] locked token which shouldn't have been blocked. mapping(uint256 => mapping(uint256 => bool)) public isDisputeNotified; // isDisputeNotified[disputeID][roundID] used to track the notification of frozen tokens. modifier onlyByGovernor() { require(governor == msg.sender); _; } /** @dev Constructor. Before this contract is made the new governor of KlerosLiquid, the evidence period of all subcourts has to be set to uint(-1). * @param _klerosLiquid The trusted arbitrator to resolve potential disputes. * @param _governor The trusted governor of the contract. * @param _foreignGateway The trusted gateway that acts as an arbitrator, relaying disputes to v2. */ constructor( IKlerosLiquid _klerosLiquid, address _governor, IArbitrator _foreignGateway ) { klerosLiquid = _klerosLiquid; governor = _governor; foreignGateway = _foreignGateway; } /** @dev Lets the governor call anything on behalf of the contract. * @param _destination The destination of the call. * @param _amount The value sent with the call. * @param _data The data sent with the call. */ function executeGovernorProposal( address _destination, uint256 _amount, bytes calldata _data ) external onlyByGovernor { (bool success, ) = _destination.call{value: _amount}(_data); // solium-disable-line security/no-call-value require(success, "Call execution failed."); } /** @dev Changes the `governor` storage variable. * @param _governor The new value for the `governor` storage variable. */ function changeGovernor(address _governor) external onlyByGovernor { governor = _governor; } /** @dev Relays disputes from KlerosLiquid to Kleros v2. Only disputes in the evidence period of the initial round can be realyed. * @param _disputeID The ID of the dispute as defined in KlerosLiquid. */ function relayDispute(uint256 _disputeID) external { require(klerosLiquidDisputeIDtoGatewayDisputeID[_disputeID] == 0, "Dispute already relayed"); IKlerosLiquid.Dispute memory KlerosLiquidDispute = klerosLiquid.disputes(_disputeID); (uint256[] memory votesLengths, , uint256[] memory totalFeesForJurors, , , ) = klerosLiquid.getDispute( _disputeID ); require(KlerosLiquidDispute.period == IKlerosLiquid.Period.evidence, "Invalid dispute period."); require(votesLengths.length == 1, "Cannot relay appeals."); klerosLiquid.executeGovernorProposal(address(this), totalFeesForJurors[0], ""); uint256 minJurors = votesLengths[0]; bytes memory extraData = abi.encode(KlerosLiquidDispute.subcourtID, minJurors); uint256 arbitrationCost = foreignGateway.arbitrationCost(extraData); require(totalFeesForJurors[0] >= arbitrationCost, "Fees not high enough."); // If this doesn't hold at some point, it could be a big issue. uint256 gatewayDisputeID = foreignGateway.createDispute{value: arbitrationCost}( KlerosLiquidDispute.numberOfChoices, extraData ); klerosLiquidDisputeIDtoGatewayDisputeID[_disputeID] = gatewayDisputeID; require(gatewayDisputeID != 0, "ID must be greater than 0."); DisputeData storage dispute = disputes[gatewayDisputeID]; dispute.klerosLiquidDisputeID = _disputeID; } /** @dev Give a ruling for a dispute. Can only be called by the arbitrator. TRUSTED. * Triggers rule() from KlerosLiquid to the arbitrable contract which created the dispute. * @param _disputeID ID of the dispute in the arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Refused to arbitrate". */ function rule(uint256 _disputeID, uint256 _ruling) public { require(msg.sender == address(foreignGateway), "Not the arbitrator."); DisputeData storage dispute = disputes[_disputeID]; require(dispute.klerosLiquidDisputeID != 0, "Dispute does not exist."); require(!dispute.ruled, "Dispute already ruled."); dispute.ruled = true; emit Ruling(foreignGateway, _disputeID, _ruling); IKlerosLiquid.Dispute memory klerosLiquidDispute = klerosLiquid.disputes(dispute.klerosLiquidDisputeID); bytes4 functionSelector = IArbitrable.rule.selector; bytes memory data = abi.encodeWithSelector(functionSelector, dispute.klerosLiquidDisputeID, _ruling); klerosLiquid.executeGovernorProposal(klerosLiquidDispute.arbitrated, 0, data); } /** @dev Registers jurors' tokens which where locked due to relaying a given dispute. These tokens don't count as locked. * @param _disputeID The ID of the dispute as defined in KlerosLiquid. */ function notifyFrozenTokens(uint256 _disputeID) external { require(klerosLiquidDisputeIDtoGatewayDisputeID[_disputeID] != 0, "Dispute not relayed."); (uint256[] memory votesLengths, uint256[] memory tokensAtStakePerJuror, , , , ) = klerosLiquid.getDispute( _disputeID ); uint256 minStakingTime = klerosLiquid.minStakingTime(); IKlerosLiquid.Phase phase = klerosLiquid.phase(); bool isDrawingForbidden = phase == IKlerosLiquid.Phase.staking && minStakingTime == type(uint256).max; for (uint256 round = 0; round < votesLengths.length; round++) { if (isDisputeNotified[_disputeID][round]) continue; for (uint256 voteID = 0; voteID < votesLengths[round]; voteID++) { (address account, , , ) = klerosLiquid.getVote(_disputeID, round, voteID); require(account != address(0x0) || isDrawingForbidden, "Juror not drawn yet."); if (account != address(0x0)) frozenTokens[account] += tokensAtStakePerJuror[round]; } isDisputeNotified[_disputeID][round] = true; } } /** @dev Called when `_owner` sends ether to the MiniMe Token contract. * @param _owner The address that sent the ether to create tokens. * @return allowed Whether the operation should be allowed or not. */ function proxyPayment(address _owner) external payable returns (bool allowed) { allowed = false; } /** @dev Notifies the controller about a token transfer allowing the controller to react if desired. * @param _from The origin of the transfer. * @param _to The destination of the transfer. * @param _amount The amount of the transfer. * @return allowed Whether the operation should be allowed or not. */ function onTransfer( address _from, address _to, uint256 _amount ) external returns (bool allowed) { if (klerosLiquid.lockInsolventTransfers()) { // Never block penalties or rewards. IPinakion pinakion = IPinakion(klerosLiquid.pinakion()); uint256 newBalance = pinakion.balanceOf(_from) - _amount; // Overflow already checked in the Minime token contract. IKlerosLiquid.Juror memory juror = klerosLiquid.jurors(_from); // frozenTokens <= lockedTokens always. if (newBalance < juror.stakedTokens || newBalance < juror.lockedTokens - frozenTokens[_from]) return false; } allowed = true; } /** @dev Notifies the controller about an approval allowing the controller to react if desired. * @param _owner The address that calls `approve()`. * @param _spender The spender in the `approve()` call. * @param _amount The amount in the `approve()` call. * @return allowed Whether the operation should be allowed or not. */ function onApprove( address _owner, address _spender, uint256 _amount ) external returns (bool allowed) { allowed = true; } /// @dev This contract should be able to receive arbitration fees from KlerosLiquid. receive() external payable {} }
Relays disputes from KlerosLiquid to Kleros v2. Only disputes in the evidence period of the initial round can be realyed. _disputeID The ID of the dispute as defined in KlerosLiquid./
function relayDispute(uint256 _disputeID) external { require(klerosLiquidDisputeIDtoGatewayDisputeID[_disputeID] == 0, "Dispute already relayed"); IKlerosLiquid.Dispute memory KlerosLiquidDispute = klerosLiquid.disputes(_disputeID); (uint256[] memory votesLengths, , uint256[] memory totalFeesForJurors, , , ) = klerosLiquid.getDispute( _disputeID ); require(KlerosLiquidDispute.period == IKlerosLiquid.Period.evidence, "Invalid dispute period."); require(votesLengths.length == 1, "Cannot relay appeals."); klerosLiquid.executeGovernorProposal(address(this), totalFeesForJurors[0], ""); uint256 minJurors = votesLengths[0]; bytes memory extraData = abi.encode(KlerosLiquidDispute.subcourtID, minJurors); uint256 arbitrationCost = foreignGateway.arbitrationCost(extraData); KlerosLiquidDispute.numberOfChoices, extraData ); klerosLiquidDisputeIDtoGatewayDisputeID[_disputeID] = gatewayDisputeID; require(gatewayDisputeID != 0, "ID must be greater than 0."); DisputeData storage dispute = disputes[gatewayDisputeID]; dispute.klerosLiquidDisputeID = _disputeID; }
12,995,919
pragma solidity^0.6.0; /* * Team Equitable Builds Inc presents.. * ====================================* * _____ ___ _______ ______ * * | _ | || | __| __| * * | | | | __| |__ * * |__|__|_____|____|_____| * * * * ====================================* */ contract AVEC{ /*================================= = MODIFIERS = =================================*/ //verify caller address members_ = true modifier onlyMembers(address _customerAddress) { require( // is the customer in the member whitelist? members_[_customerAddress] == true ); // execute _; } //verify caller address founderdevelopers_ = true modifier onlyFounderDevelopers(address _customerAddress) { require( // is the customer in the Founder Developer whitelist? founderdevelopers_[_customerAddress] == true ); // execute _; } //verify caller address ceva_ = true modifier onlyCEVA(address _customerAddress) { require( // is the customer in the ceva whitelist? ceva_[_customerAddress] == true ); // execute _; } modifier onlyAdministrator(address _customerAddress){ require( administrators[_customerAddress] == true ); _; } /*============================== = EVENTS = ==============================*/ event onWithdraw( address indexed customerAddress, uint256 tokensWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 value ); event Burn( address indexed from, uint256 tokens, uint256 propertyValue ); // ERC20 event Approval( address indexed _owner, address indexed _spender, uint256 _value ); event PropertyValuation( address indexed from, bytes32 _propertyUniqueID, uint256 propertyValue ); event PropertyWhitelisted( address indexed from, bytes32 _propertyUniqueID, bool _trueFalse ); event MemberWhitelisted( address indexed from, address indexed to, bool _trueFalse ); event FounderDeveloperWhitelisted( address indexed from, address indexed to, bool _trueFalse ); event CEVAWhitelisted( address indexed from, address indexed to, bool _trueFalse ); event AdminWhitelisted( address indexed from, address indexed to, bool _trueFalse ); /*===================================== = CONFIGURABLES = =====================================*/ string private name = "AlternateVirtualEquityCredits"; string private symbol = "AVEC"; uint8 private decimals = 18; address internal whoaaddress_ = 0x314d0ED76d866826C809fb6a51d63642b2E9eC3e; address internal whoamaintenanceaddress_ = 0x2722B426B11978c29660e8395a423Ccb93AE0403; address internal whoarewardsaddress_ = 0xA9d241b568DF9E8A7Ec9e44737f29a8Ee00bfF53; address internal cevaaddress_ = 0xdE281c22976dE2E9b3f4F87bEB60aE9E67DFf5C4; address internal credibleyouaddress_ = 0xc9c1Ffd6B4014232Ef474Daa4CA1506A6E39Be89; address internal techaddress_ = 0xB6148C62e6A6d48f41241D01e3C4841139144ABa; address internal existholdingsaddress_ = 0xac1B6580a175C1f2a4e3220A24e6f65fF3AB8A03; address internal existcryptoaddress_ = 0xb8C098eE976f1162aD277936a5D1BCA7a8Fe61f5; // founder developer address whitelist archive mapping(address => bool) internal members_; // members whitelist address archive mapping(address => bool) internal founderdevelopers_; // ceva whitelist address archive mapping(address => bool) internal ceva_; // administrator list (see above on what they can do) mapping(address => bool) internal administrators; // setting for allowance function determines amount of tokens address can spend from mapped address mapping (address => mapping (address => uint256)) private _allowed; mapping (address => mapping(bytes32 => bool)) internal mintrequestwhitelist_; mapping (address => mapping(bytes32 => bool)) internal burnrequestwhitelist_; mapping (address => mapping(bytes32 => bool)) internal propertywhitelist_; mapping (address => mapping(bytes32 => uint256)) internal propertyvalue_; mapping(address => bytes32) workingPropertyid_; mapping(address => bytes32) workingMintRequestid_; mapping(address => bytes32) workingBurnRequestid_; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_ ; mapping(address => uint256) internal mintingDepositsOf_; mapping(address => uint256) internal AmountCirculated_; mapping(address => uint256) internal taxesFeeTotalWithdrawn_; mapping(address => uint256) internal taxesPreviousWithdrawn_; mapping(address => uint256) internal taxesFeeSharehold_; mapping(address => uint256) internal insuranceFeeTotalWithdrawn_; mapping(address => uint256) internal insurancePreviousWithdrawn_; mapping(address => uint256) internal insuranceFeeSharehold_; mapping(address => uint256) internal maintenanceFeeTotalWithdrawn_; mapping(address => uint256) internal maintenancePreviousWithdrawn_; mapping(address => uint256) internal maintenanceFeeSharehold_; mapping(address => uint256) internal waECOFeeTotalWithdrawn_; mapping(address => uint256) internal waECOPreviousWithdrawn_; mapping(address => uint256) internal waECOFeeSharehold_; mapping(address => uint256) internal holdoneTotalWithdrawn_; mapping(address => uint256) internal holdonePreviousWithdrawn_; mapping(address => uint256) internal holdoneSharehold_; mapping(address => uint256) internal holdtwoTotalWithdrawn_; mapping(address => uint256) internal holdtwoPreviousWithdrawn_; mapping(address => uint256) internal holdtwoSharehold_; mapping(address => uint256) internal holdthreeTotalWithdrawn_; mapping(address => uint256) internal holdthreePreviousWithdrawn_; mapping(address => uint256) internal holdthreeSharehold_; mapping(address => uint256) internal rewardsTotalWithdrawn_; mapping(address => uint256) internal rewardsPreviousWithdrawn_; mapping(address => uint256) internal rewardsSharehold_; mapping(address => uint256) internal techTotalWithdrawn_; mapping(address => uint256) internal techPreviousWithdrawn_; mapping(address => uint256) internal techSharehold_; mapping(address => uint256) internal existholdingsTotalWithdrawn_; mapping(address => uint256) internal existholdingsPreviousWithdrawn_; mapping(address => uint256) internal existholdingsSharehold_; mapping(address => uint256) internal existcryptoTotalWithdrawn_; mapping(address => uint256) internal existcryptoPreviousWithdrawn_; mapping(address => uint256) internal existcryptoSharehold_; mapping(address => uint256) internal whoaTotalWithdrawn_; mapping(address => uint256) internal whoaPreviousWithdrawn_; mapping(address => uint256) internal whoaSharehold_; mapping(address => uint256) internal credibleyouTotalWithdrawn_; mapping(address => uint256) internal credibleyouPreviousWithdrawn_; mapping(address => uint256) internal credibleyouSharehold_; mapping(address => uint256) internal numberofmintingrequestswhitelisted_; mapping(address => uint256) internal numberofpropertieswhitelisted_; mapping(address => uint256) internal numberofburnrequestswhitelisted_; mapping(address => uint256) internal transferingFromWallet_; uint256 public tokenSupply_ = 0; uint256 public feeTotalHolds_ = 0; uint256 internal cevaBurnerStockpile_ = 0; uint256 internal cevaBurnerStockpileWithdrawn_ = 0; uint256 internal taxesfeeTotalHolds_ = 0; uint256 internal taxesfeeBalanceLedger_ = 0; uint256 internal insurancefeeTotalHolds_ = 0; uint256 internal insurancefeeBalanceLedger_ = 0; uint256 internal maintencancefeeTotalHolds_ = 0; uint256 internal maintenancefeeBalanceLedger_ = 0; uint256 internal waECOfeeTotalHolds_ = 0; uint256 internal waECOfeeBalanceLedger_ = 0; uint256 internal holdonefeeTotalHolds_ = 0; uint256 internal holdonefeeBalanceLedger_ = 0; uint256 internal holdtwofeeTotalHolds_ = 0; uint256 internal holdtwofeeBalanceLedger_ = 0; uint256 internal holdthreefeeTotalHolds_ = 0; uint256 internal holdthreefeeBalanceLedger_ = 0; uint256 internal RewardsfeeTotalHolds_ = 0; uint256 internal RewardsfeeBalanceLedger_ = 0; uint256 internal techfeeTotalHolds_ = 0; uint256 internal techfeeBalanceLedger_ = 0; uint256 internal existholdingsfeeTotalHolds_ = 0; uint256 internal existholdingsfeeBalanceLedger_ = 0; uint256 internal existcryptofeeTotalHolds_ = 0; uint256 internal existcryptofeeBalanceLedger_ = 0; uint256 internal whoafeeTotalHolds_ = 0; uint256 internal whoafeeBalanceLedger_ = 0; uint256 internal credibleyoufeeTotalHolds_ = 0; uint256 internal credibleyoufeeBalanceLedger_ = 0; /*======================================= = MEMBER FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ constructor() public { } /* * -- APPLICATION ENTRY POINTS -- */ function InitialSet() public { // add the first users //James Admin administrators[0x27851761A8fBC03f57965b42528B39af07cdC42b] = true; //Brenden Admin administrators[0xA9873d93db3BCA9F68aDfEAb226Fa9189641069A] = true; members_[0x314d0ED76d866826C809fb6a51d63642b2E9eC3e] = true; members_[0x2722B426B11978c29660e8395a423Ccb93AE0403] = true; members_[0xdE281c22976dE2E9b3f4F87bEB60aE9E67DFf5C4] = true; members_[0xc9c1Ffd6B4014232Ef474Daa4CA1506A6E39Be89] = true; members_[0xac1B6580a175C1f2a4e3220A24e6f65fF3AB8A03] = true; members_[0xb8C098eE976f1162aD277936a5D1BCA7a8Fe61f5] = true; members_[0xB6148C62e6A6d48f41241D01e3C4841139144ABa] = true; members_[0xA9d241b568DF9E8A7Ec9e44737f29a8Ee00bfF53] = true; members_[0x314d0ED76d866826C809fb6a51d63642b2E9eC3e] = true; members_[0x314d0ED76d866826C809fb6a51d63642b2E9eC3e] = true; } /* * -- APPLICATION ENTRY POINTS -- */ function genesis(address _existcryptoaddress, address _existhooldingsaddress, address _techaddress, address _credibleyouaddress, address _cevaaddress, address _whoaddress, address _whoarewardsaddress, address _whoamaintenanceaddress) public onlyAdministrator(msg.sender) { require(administrators[msg.sender]); // adds the first founder developer here. founderdevelopers_[msg.sender] = true; // adds the _whoaddress input as the current whoa address whoaaddress_ = _whoaddress; // adds the _whoamaintenanceaddress input as the current whoa maintenence address whoamaintenanceaddress_ = _whoamaintenanceaddress; // adds the _whoarewardsaddress input as the current whoa rewards address whoarewardsaddress_ = _whoarewardsaddress; // adds the )cevaaddress_ input as the current ceva address cevaaddress_ = _cevaaddress; // adds the _credibleyouaddress input as the current credible you address credibleyouaddress_ = _credibleyouaddress; // adds the _techaddress input as the current tech address techaddress_ = _techaddress; // adds the __existhooldingsaddress input as the current exist holdings address existholdingsaddress_ = _existhooldingsaddress; // adds the _existcryptoaddress input as the current exist crypto address existcryptoaddress_ = _existcryptoaddress; // adds the first ceva qualified founder developers here. ceva_[msg.sender] = true; numberofburnrequestswhitelisted_[msg.sender] = 0; numberofpropertieswhitelisted_[msg.sender] = 0; numberofmintingrequestswhitelisted_[msg.sender] = 0; // adds the first member here. members_[msg.sender] = true; } /** * Withdraws all of the callers taxes earnings. */ function buyFounderDeveloperLicense(address _FounderDeveloperOne, address _FounderDeveloperTwo, address _CEVA) onlyMembers(msg.sender) public returns(bool _success) { require(founderdevelopers_[_FounderDeveloperOne] == true && ceva_[_CEVA] == true && founderdevelopers_[_FounderDeveloperTwo] == true); // setup data address _customerAddress = msg.sender; uint256 _licenseprice = (1000 * 1e18); if(tokenBalanceLedger_[_customerAddress] > _licenseprice){ tokenBalanceLedger_[_CEVA] = (_licenseprice / 5) + tokenBalanceLedger_[_CEVA]; tokenBalanceLedger_[_FounderDeveloperOne] = (_licenseprice / 5) + tokenBalanceLedger_[_FounderDeveloperOne]; tokenBalanceLedger_[_FounderDeveloperTwo] = (_licenseprice / 10) + tokenBalanceLedger_[_FounderDeveloperTwo]; tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress] - _licenseprice; founderdevelopers_[_customerAddress] = true; return true; } else { return false; } } /** * Withdraws all of the callers taxes earnings. */ function withdrawTaxesdividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EtaxesdividendsOf(msg.sender); // update dividend tracker taxesFeeTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawInsurancedividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EinsurancedividendsOf(msg.sender); // update dividend tracker insuranceFeeTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawMaintenancedividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EmaintenancedividendsOf(msg.sender); // update dividend tracker maintenanceFeeTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawwaECOdividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EwaECOdividendsOf(msg.sender); // update dividend tracker maintenanceFeeTotalWithdrawn_[_customerAddress] += _dividends; waECOFeeTotalWithdrawn_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawHoldOnedividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EholdonedividendsOf(msg.sender); // update dividend tracker holdoneTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawHoldTwodividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EholdtwodividendsOf(msg.sender); // update dividend tracker holdtwoTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawHoldThreeedividends() onlyMembers(msg.sender) public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EholdthreedividendsOf(msg.sender); // update dividend tracker holdthreeTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawRewardsdividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = ErewardsdividendsOf(msg.sender); // update dividend tracker rewardsTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawTechdividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EtechdividendsOf(msg.sender); // update dividend tracker techTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawExistHoldingsdividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = existholdingsdividendsOf(msg.sender); // update dividend tracker existholdingsTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawExistCryptodividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = existcryptodividendsOf(msg.sender); // update dividend tracker existcryptoTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawWHOAdividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EwhoadividendsOf(msg.sender); // update dividend tracker whoaTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawCrediblelYoudividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EcredibleyoudividendsOf(msg.sender); // update dividend tracker credibleyouTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 2% fee here as well. members only */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyMembers(msg.sender) public returns(bool) { if(_amountOfTokens > 0){ // make sure we have the requested tokens require(_amountOfTokens + (_amountOfTokens / 50) <= tokenBalanceLedger_[msg.sender] && _amountOfTokens >= 0 && _toAddress != msg.sender && members_[_toAddress] == true); //Exchange tokens tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress] + _amountOfTokens; tokenBalanceLedger_[msg.sender] -= _amountOfTokens + (_amountOfTokens / 50); //Update Equity Rents updateEquityRents(_amountOfTokens); AmountCirculated_[msg.sender] += _amountOfTokens; emit Transfer(msg.sender, _toAddress, (_amountOfTokens + (_amountOfTokens / 50))); return true; } else { return false; } } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 2% fee here as well. members only */ function transferFrom(address from, address to, uint256 tokens) onlyMembers(msg.sender) public returns(bool) { if(tokens >= 0){ require(members_[to] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested tokens require(tokens + (tokens / 50) <= tokenBalanceLedger_[from] && tokens >= 0 && to != _customerAddress && from != to && tokens + (tokens / 50) <= _allowed[from][msg.sender] && msg.sender != from && transferingFromWallet_[msg.sender] == 0); transferingFromWallet_[msg.sender] = 1; //Exchange tokens tokenBalanceLedger_[to] = tokenBalanceLedger_[to] + tokens; tokenBalanceLedger_[msg.sender] -= tokens + (tokens / 50); //Reduce Approval Amount _allowed[from][msg.sender] -= tokens + (tokens / 50); emit Transfer(_customerAddress, to, (tokens + (tokens / 50))); transferingFromWallet_[msg.sender] = 0; return true; } else { return false; } } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return _allowed[tokenOwner][spender]; } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 2% fee here as well. members only */ function clearTitle(uint256 _propertyValue, uint256 _amountOfTokens, address _clearFrom) onlyMembers(msg.sender) public returns(bool) { if((_amountOfTokens / 1e18) * 100 <= _propertyValue){ require(burnrequestwhitelist_[_clearFrom][workingBurnRequestid_[msg.sender]] == true && propertywhitelist_[_clearFrom][workingPropertyid_[msg.sender]] == true && _amountOfTokens <= tokenBalanceLedger_[_clearFrom] && _amountOfTokens >= 0); //Burn Tokens burnA(_propertyValue); tokenSupply_ -= _amountOfTokens; taxesfeeTotalHolds_ -= _propertyValue / 100; insurancefeeTotalHolds_ -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); maintencancefeeTotalHolds_ -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); waECOfeeTotalHolds_ -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); holdonefeeTotalHolds_ -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); holdtwofeeTotalHolds_ -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); holdthreefeeTotalHolds_ -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); // take tokens out of stockpile //Exchange tokens cevaBurnerStockpile_ -= ((propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100) * 1e18) - _amountOfTokens; tokenBalanceLedger_[msg.sender] -= _amountOfTokens; // burn fee shareholds taxesFeeSharehold_[msg.sender] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); insuranceFeeSharehold_[msg.sender] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); maintenanceFeeSharehold_[whoamaintenanceaddress_] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); waECOFeeSharehold_[msg.sender] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); holdoneSharehold_[msg.sender] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); holdtwoSharehold_[msg.sender] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); holdthreeSharehold_[msg.sender] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); rewardsSharehold_[msg.sender] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); techSharehold_[techaddress_] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); existholdingsSharehold_[existholdingsaddress_] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); existcryptoSharehold_[existcryptoaddress_] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); whoaSharehold_[whoaaddress_] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); credibleyouSharehold_[credibleyouaddress_] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); // returns bool true emit Burn(msg.sender, _amountOfTokens, _propertyValue); return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellTaxesFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= taxesFeeSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals taxesPreviousWithdrawn_[_toAddress] += (taxesFeeTotalWithdrawn_[_customerAddress] / taxesFeeSharehold_[_customerAddress]) * _amount; //Exchange sharehold taxesFeeSharehold_[_toAddress] += _amount; taxesFeeSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellInsuranceFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= insuranceFeeSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals insurancePreviousWithdrawn_[_toAddress] += (insuranceFeeTotalWithdrawn_[_customerAddress] / insuranceFeeSharehold_[_customerAddress]) * _amount; //Exchange sharehold insuranceFeeSharehold_[_toAddress] += _amount; insuranceFeeSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellMaintenanceFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= maintenanceFeeSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals maintenancePreviousWithdrawn_[_toAddress] += (maintenanceFeeTotalWithdrawn_[_customerAddress] / maintenanceFeeSharehold_[_customerAddress]) * _amount; //Exchange sharehold maintenanceFeeSharehold_[_toAddress] += _amount; maintenanceFeeSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellwaECOFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= waECOFeeSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals waECOPreviousWithdrawn_[_toAddress] += (waECOFeeTotalWithdrawn_[_customerAddress] / waECOFeeSharehold_[_customerAddress]) * _amount; //Exchange sharehold waECOFeeSharehold_[_toAddress] += _amount; waECOFeeSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellHoldOneFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= holdoneSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals holdonePreviousWithdrawn_[_toAddress] += (holdoneTotalWithdrawn_[_customerAddress] / holdoneSharehold_[_customerAddress]) * _amount; //Exchange sharehold holdoneSharehold_[_toAddress] += _amount; holdoneSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellHoldTwoFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= holdtwoSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals holdtwoPreviousWithdrawn_[_toAddress] += (holdtwoTotalWithdrawn_[_customerAddress] / holdtwoSharehold_[_customerAddress]) * _amount; //Exchange sharehold holdtwoSharehold_[_toAddress] += _amount; holdtwoSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellHoldThreeFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= holdthreeSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals holdthreePreviousWithdrawn_[_toAddress] += (holdthreeTotalWithdrawn_[_customerAddress] / holdthreeSharehold_[_customerAddress]) * _amount; //Exchange sharehold holdthreeSharehold_[_toAddress] += _amount; holdthreeSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellRewardsFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= rewardsSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals rewardsPreviousWithdrawn_[_toAddress] += (rewardsTotalWithdrawn_[_customerAddress] / rewardsSharehold_[_customerAddress]) * _amount; //Exchange sharehold rewardsSharehold_[_toAddress] += _amount; rewardsSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellTechFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= techSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals techPreviousWithdrawn_[_toAddress] += (techTotalWithdrawn_[_customerAddress] / techSharehold_[_customerAddress]) * _amount; //Exchange sharehold techSharehold_[_toAddress] += _amount; techSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellExistHoldingsFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) onlyMembers(_toAddress) public returns(bool) { if(_amount > 0){ //require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= existholdingsSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals existholdingsPreviousWithdrawn_[_toAddress] += (existholdingsTotalWithdrawn_[_customerAddress] / existholdingsSharehold_[_customerAddress]) * _amount; //Exchange sharehold existholdingsSharehold_[_toAddress] += _amount; existholdingsSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellExistCryptoFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= existcryptoSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals existcryptoPreviousWithdrawn_[_toAddress] += (existcryptoTotalWithdrawn_[_customerAddress] / existcryptoSharehold_[_customerAddress]) * _amount; //Exchange sharehold existcryptoSharehold_[_toAddress] += _amount; existcryptoSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellWHOAFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= whoaSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals whoaPreviousWithdrawn_[_toAddress] += (whoaTotalWithdrawn_[_customerAddress] / whoaSharehold_[_customerAddress]) * _amount; //Exchange sharehold whoaSharehold_[_toAddress] += _amount; whoaSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellCredibleYouFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= credibleyouSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals credibleyouPreviousWithdrawn_[_toAddress] += (credibleyouTotalWithdrawn_[_customerAddress] / credibleyouSharehold_[_customerAddress]) * _amount; //Exchange sharehold credibleyouSharehold_[_toAddress] += _amount; credibleyouSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Check and address to see if it has CEVA privileges or not */ function checkCEVA(address _identifier) public view returns(bool) { if(ceva_[_identifier] == true){ return true; } else { return false; } } /** * Check and address to see if it has member privileges */ function checkMember(address _identifier) public view returns(bool) { if(members_[_identifier] == true){ return true; } else { return false; } } /** * Check and address to see is its got founder developer privileges */ function checkFounderDeveloper(address _identifier) public view returns(bool) { if(founderdevelopers_[_identifier] == true){ return true; } else { return false; } } /** * Check and address to see if it has admin privileges */ function checkAdmin(address _identifier) public view returns(bool) { if(administrators[_identifier] == true){ return true; } else { return false; } } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * whitelist Admins admin only */ function AwhitelistAdministrator(address _identifier, bool _status) onlyAdministrator(msg.sender) public { require(msg.sender != _identifier); administrators[_identifier] = _status; emit AdminWhitelisted(msg.sender, _identifier, _status); } /** * Automation entrypoint to whitelist ceva_ admin only */ function AwhitelistCEVA(address _identifier, bool _status) onlyAdministrator(msg.sender) public { require(msg.sender != _identifier); ceva_[_identifier] = _status; numberofburnrequestswhitelisted_[msg.sender] = 0; numberofpropertieswhitelisted_[msg.sender] = 0; numberofmintingrequestswhitelisted_[msg.sender] = 0; emit CEVAWhitelisted(msg.sender, _identifier, _status); } function withdrawCEVABurnerStockpiledividends(uint256 _amountOfTokens) onlyCEVA(msg.sender) public { // setup data require(_amountOfTokens <= cevaBurnerStockpile_); // update dividend tracker cevaBurnerStockpile_ -= _amountOfTokens; cevaBurnerStockpileWithdrawn_ += _amountOfTokens; tokenBalanceLedger_[cevaaddress_] += _amountOfTokens; emit Transfer(msg.sender, msg.sender, _amountOfTokens); } /** * Whitelist a Property that has been confirmed on the site.. ceva only */ function AwhitelistMintRequest(address _OwnerAddress, bool _trueFalse, bytes32 _mintingRequestUniqueid) onlyCEVA(msg.sender) public returns(bool) { if(_mintingRequestUniqueid == workingMintRequestid_[msg.sender]){ require(msg.sender != _OwnerAddress); mintrequestwhitelist_[_OwnerAddress][_mintingRequestUniqueid] = _trueFalse; return true; } else { return false; } } /** * Whitelist a Property that has been confirmed on the site.. ceva only */ function AwhitelistBurnRequest(address _OwnerAddress, bool _trueFalse, bytes32 _burnrequestUniqueID) onlyCEVA(msg.sender) public returns(bool) { if(_burnrequestUniqueID == workingBurnRequestid_[msg.sender]){ require(msg.sender != _OwnerAddress); burnrequestwhitelist_[_OwnerAddress][_burnrequestUniqueID] = _trueFalse; return true; } else { return false; } } /** * Whitelist a Minting Request that has been confirmed on the site.. ceva only */ function AwhitelistProperty(address _OwnerAddress, bool _trueFalse, bytes32 _propertyUniqueID) onlyCEVA(msg.sender) public returns(bool) { if(_trueFalse = true){ require(workingPropertyid_[msg.sender] == _propertyUniqueID); propertywhitelist_[_OwnerAddress][_propertyUniqueID] = _trueFalse; emit PropertyWhitelisted(msg.sender, _propertyUniqueID, _trueFalse); return true; } else { return false; } } /** * Whitelist a Minting Request that has been confirmed on the site.. ceva only */ function AsetWhitelistedPropertyValue(address _OwnerAddress, bytes32 _propertyUniqueID, uint256 _propertyValue) onlyCEVA(msg.sender) public returns(uint256) { require(propertywhitelist_[_OwnerAddress][_propertyUniqueID] = true && _propertyValue >= 0); if(_OwnerAddress != msg.sender){ address _customerAddress = msg.sender; numberofmintingrequestswhitelisted_[msg.sender] += 1; emit PropertyValuation(_customerAddress, _propertyUniqueID, _propertyValue); return _propertyValue; } else { numberofmintingrequestswhitelisted_[msg.sender] -= 1; _propertyValue = 0; return _propertyValue; } } /** * Whitelist a Minting Request that has been confirmed on the site.. ceva only */ function AsetworkingPropertyid(address _OwnerAddress, bytes32 _propertyUniqueID) onlyFounderDevelopers(msg.sender) public returns(bool) { require(propertywhitelist_[_OwnerAddress][_propertyUniqueID] = true); if(_OwnerAddress != msg.sender){ workingPropertyid_[_OwnerAddress] = _propertyUniqueID; return true; } else { return false; } } /** * Whitelist a Minting Request that has been confirmed on the site.. ceva only */ function AsetworkingMintingRequest(address _OwnerAddress, bytes32 _mintingRequestUniqueid) onlyFounderDevelopers(msg.sender) public returns(bool) { require(mintrequestwhitelist_[_OwnerAddress][_mintingRequestUniqueid] = true); if(_OwnerAddress != msg.sender){ workingMintRequestid_[_OwnerAddress] = _mintingRequestUniqueid; return true; } else { return false; } } /** * Whitelist a Minting Request that has been confirmed on the site.. ceva only */ function Asetworkingburnrequestid(address _OwnerAddress, bytes32 _propertyUniqueID, uint256 _propertyValue) onlyFounderDevelopers(msg.sender) public returns(bytes32) { require(burnrequestwhitelist_[_OwnerAddress][_propertyUniqueID] = true); if(_OwnerAddress != msg.sender){ workingPropertyid_[_OwnerAddress] = _propertyUniqueID; numberofmintingrequestswhitelisted_[msg.sender] += 1; emit PropertyValuation(msg.sender, _propertyUniqueID, _propertyValue); return _propertyUniqueID; } else { numberofmintingrequestswhitelisted_[msg.sender] -= 1; _propertyValue = 0; return _propertyUniqueID; } } function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) { uint8 i = 0; while(i < 32 && _bytes32[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes32[i] != 0; i++) { bytesArray[i] = _bytes32[i]; } return string(bytesArray); } function bStringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } /** * Whitelist a Founder Developer ceva only */ function AWhitelistFounderDeveloper(address _identifier, bool _status) onlyCEVA(msg.sender) public { founderdevelopers_[_identifier] = _status; numberofburnrequestswhitelisted_[msg.sender] = 0; numberofpropertieswhitelisted_[msg.sender] = 0; numberofmintingrequestswhitelisted_[msg.sender] = 0; emit FounderDeveloperWhitelisted(msg.sender, _identifier, _status); } /*---------- FOUNDER DEVELOPER ONLY FUNCTIONS ----------*/ // Mint an amount of tokens to an address // using a whitelisted minting request unique ID founder developer only function _mint(uint256 _FounderDeveloperFee, address _toAddress, address _holdOne, address _holdTwo, address _holdThree, uint256 _propertyValue, bytes32 _propertyUniqueID, bytes32 _mintingRequestUniqueid) onlyFounderDevelopers(msg.sender) public { if(_propertyValue >= 100){ // data setup uint256 _amountOfTokens = (_propertyValue * 1e18) / 100; require(members_[_toAddress] == true && _FounderDeveloperFee >= 20001 && _FounderDeveloperFee <= 100000 && (_amountOfTokens + tokenSupply_) > tokenSupply_ && msg.sender != _toAddress && _propertyUniqueID == workingPropertyid_[msg.sender] && _mintingRequestUniqueid == workingMintRequestid_[msg.sender] && _propertyValue == propertyvalue_[_toAddress][_propertyUniqueID]); // add tokens to the pool tokenSupply_ = tokenSupply_ + _amountOfTokens; updateHoldsandSupply(_amountOfTokens); // add to burner stockpile cevaBurnerStockpile_ += (_amountOfTokens / 16667) * 100; // whoa fee whoafeeBalanceLedger_ = whoafeeBalanceLedger_ + _amountOfTokens; // credit founder developer fee tokenBalanceLedger_[msg.sender] += (_amountOfTokens / _FounderDeveloperFee) * 1000; //credit Envelope Fee Shareholds creditFeeSharehold(_amountOfTokens, _toAddress, _holdOne, _holdTwo, _holdThree); // credit tech feeSharehold_ ; uint256 _TechFee = (_amountOfTokens / 25000) * 100; techfeeBalanceLedger_ = techfeeBalanceLedger_ + _TechFee; // fire event // add tokens to the _toAddress uint256 _cevabTransferfees = (_amountOfTokens / 333334) * 10000; uint256 _Fee = (_amountOfTokens / _FounderDeveloperFee) * 1000; tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress] + (_amountOfTokens - _cevabTransferfees); tokenBalanceLedger_[_toAddress] -= _Fee; tokenBalanceLedger_[_toAddress] -= _TechFee; emit Transfer(msg.sender, _toAddress, _amountOfTokens); mintingDepositsOf_[_toAddress] += _amountOfTokens; } else { return; } } function AworkingPropertyIDOf(address _user) onlyFounderDevelopers(msg.sender) public view returns(bytes32) { return workingPropertyid_[_user]; } function AworkingBurnRequestIDOf(address _user) onlyFounderDevelopers(msg.sender) public view returns(bytes32) { return workingBurnRequestid_[_user]; } function AworkingMintIDOf(address _user) onlyFounderDevelopers(msg.sender) public view returns(bytes32) { return workingMintRequestid_[_user]; } /** * whitelist a member founder developer only */ function AWhitelistMember(address _identifier, bool _status) onlyFounderDevelopers(msg.sender) public { require(msg.sender != _identifier); members_[_identifier] = _status; emit MemberWhitelisted(msg.sender, _identifier, _status); } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Retrieve the tokens owned by the caller. */ function TokensNoDecimals() view public returns(uint256) { address _customerAddress = msg.sender; uint256 _tokens = (balanceOf(_customerAddress) / 1e18); if(_tokens >= 1){ return _tokens; } else { return 0; } } function balanceOf(address _owner) view public returns(uint256) { return tokenBalanceLedger_[_owner]; } function EtaxesdividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(taxesFeeSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (taxesfeeBalanceLedger_ / taxesfeeTotalHolds_); return (uint256) ((_dividendPershare * taxesFeeSharehold_[_customerAddress]) - (taxesFeeTotalWithdrawn_[_customerAddress] + taxesPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EtaxesShareholdOf(address _customerAddress) view public returns(uint256) { if(taxesFeeSharehold_[_customerAddress] == 0){ return 0; } else { return taxesFeeSharehold_[_customerAddress]; } } /** * Retrieve the insurance dividend balance of any single address. */ function EinsurancedividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(insuranceFeeSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (insurancefeeBalanceLedger_ / insurancefeeTotalHolds_); return (uint256) ((_dividendPershare * insuranceFeeSharehold_[_customerAddress]) - (insuranceFeeTotalWithdrawn_[_customerAddress] + insurancePreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EinsuranceShareholdOf(address _customerAddress) view public returns(uint256) { if(insuranceFeeSharehold_[_customerAddress] == 0){ return 0; } else { return insuranceFeeSharehold_[_customerAddress]; } } /** * Retrieve the maintenance dividend balance of any single address. */ function EmaintenancedividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(maintenanceFeeSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (maintenancefeeBalanceLedger_ / maintencancefeeTotalHolds_); return (uint256) ((_dividendPershare * maintenanceFeeSharehold_[_customerAddress]) - (maintenanceFeeTotalWithdrawn_[_customerAddress] + maintenancePreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EmaintenanceShareholdOf(address _customerAddress) view public returns(uint256) { if(maintenanceFeeSharehold_[_customerAddress] == 0){ return 0; } else { return maintenanceFeeSharehold_[_customerAddress]; } } /** * Retrieve the Wealth Architect ECO Register 1.2 dividend balance of any single address. */ function EwaECOdividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(waECOFeeSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (waECOfeeBalanceLedger_ / waECOfeeTotalHolds_); return (uint256) ((_dividendPershare * waECOFeeSharehold_[_customerAddress]) - (waECOFeeTotalWithdrawn_[_customerAddress] + waECOPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EwaECOShareholdOf(address _customerAddress) view public returns(uint256) { if(waECOFeeSharehold_[_customerAddress] == 0){ return 0; } else { return waECOFeeSharehold_[_customerAddress]; } } /** * Retrieve the hold one dividend balance of any single address. */ function EholdonedividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(holdoneSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (holdonefeeBalanceLedger_ / holdonefeeTotalHolds_); return (uint256) ((_dividendPershare * holdoneSharehold_[_customerAddress]) - (holdoneTotalWithdrawn_[_customerAddress] + holdonePreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EholdoneShareholdOf(address _customerAddress) view public returns(uint256) { if(holdoneSharehold_[_customerAddress] == 0){ return 0; } else { return holdoneSharehold_[_customerAddress]; } } /** * Retrieve the hold two dividend balance of any single address. */ function EholdtwodividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(holdtwoSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (holdtwofeeBalanceLedger_ / holdtwofeeTotalHolds_); return (uint256) ((_dividendPershare * holdtwoSharehold_[_customerAddress]) - (holdtwoTotalWithdrawn_[_customerAddress] + holdtwoPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EholdtwoShareholdOf(address _customerAddress) view public returns(uint256) { if(holdtwoSharehold_[_customerAddress] == 0){ return 0; } else { return holdtwoSharehold_[_customerAddress]; } } /** * Retrieve the hold three dividend balance of any single address. */ function EholdthreedividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(holdthreeSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (holdthreefeeBalanceLedger_ / holdthreefeeTotalHolds_); return (uint256) ((_dividendPershare * holdthreeSharehold_[_customerAddress]) - (holdthreeTotalWithdrawn_[_customerAddress] + holdthreePreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EholdthreeShareholdOf(address _customerAddress) view public returns(uint256) { if(holdthreeSharehold_[_customerAddress] == 0){ return 0; } else { return holdthreeSharehold_[_customerAddress]; } } /** * Retrieve the rewards dividend balance of any single address. */ function ErewardsdividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(rewardsSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (RewardsfeeBalanceLedger_ / RewardsfeeTotalHolds_); return (uint256) ((_dividendPershare * rewardsSharehold_[_customerAddress]) - (rewardsTotalWithdrawn_[_customerAddress] + rewardsPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function ErewardsShareholdOf(address _customerAddress) view public returns(uint256) { if(rewardsSharehold_[_customerAddress] == 0){ return 0; } else { return rewardsSharehold_[_customerAddress]; } } /** * Retrieve the tech dividend balance of any single address. */ function EtechdividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(techfeeTotalHolds_ == 0){ return 0; } else { _dividendPershare = (techfeeBalanceLedger_ / techfeeTotalHolds_); return (uint256) ((_dividendPershare * techSharehold_[_customerAddress]) - (techTotalWithdrawn_[_customerAddress] + techPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EtechShareholdOf(address _customerAddress) view public returns(uint256) { if(techSharehold_[_customerAddress] == 0){ return 0; } else { return techSharehold_[_customerAddress]; } } /** * Retrieve the exist holdings dividend balance of any single address. */ function existholdingsdividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(existholdingsfeeTotalHolds_ == 0){ return 0; } else { _dividendPershare = (existholdingsfeeBalanceLedger_ / existholdingsfeeTotalHolds_); return (uint256) ((_dividendPershare * existholdingsSharehold_[_customerAddress]) - (existholdingsTotalWithdrawn_[_customerAddress] + existholdingsPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function existholdingsShareholdOf(address _customerAddress) view public returns(uint256) { if(existholdingsSharehold_[_customerAddress] == 0){ return 0; } else { return existholdingsSharehold_[_customerAddress]; } } /** * Retrieve the exist crypto dividend balance of any single address. */ function existcryptodividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(existcryptofeeTotalHolds_ == 0){ return 0; } else { _dividendPershare = (existcryptofeeBalanceLedger_ / existcryptofeeTotalHolds_); return (uint256) ((_dividendPershare * existcryptoSharehold_[_customerAddress]) - (existcryptoTotalWithdrawn_[_customerAddress] + existcryptoPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function existcryptoShareholdOf(address _customerAddress) view public returns(uint256) { if(existcryptoSharehold_[_customerAddress] == 0){ return 0; } else { return existcryptoSharehold_[_customerAddress]; } } /** * Retrieve the Worldwide Home Owners Association dividend balance of any single address. */ function EwhoadividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(whoafeeTotalHolds_ == 0){ return 0; } else { _dividendPershare = (whoafeeBalanceLedger_ / whoafeeTotalHolds_); return (uint256) ((_dividendPershare * whoaSharehold_[_customerAddress]) - (whoaTotalWithdrawn_[_customerAddress] + whoaPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the WHOA dividend balance of any single address. */ function EwhoaShareholdOf(address _customerAddress) view public returns(uint256) { if(whoaSharehold_[_customerAddress] == 0){ return 0; } else { return whoaSharehold_[_customerAddress]; } } /** * Retrieve the Credible You dividend balance of any single address. */ function EcredibleyoudividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(credibleyoufeeTotalHolds_ == 0){ return 0; } else { _dividendPershare = (credibleyoufeeBalanceLedger_ / credibleyoufeeTotalHolds_); return (uint256) ((_dividendPershare * credibleyouSharehold_[_customerAddress]) - (credibleyouTotalWithdrawn_[_customerAddress] + credibleyouPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EcredibleyouShareholdOf(address _customerAddress) view public returns(uint256) { if(credibleyouSharehold_[_customerAddress] == 0){ return 0; } else { return credibleyouSharehold_[_customerAddress]; } } /** * Retrieve the CEVA Burner Stockpile dividend balance using a CEVA whitelisted address. */ function EcevaBurnerStockpileDividends() onlyCEVA(msg.sender) view public returns(uint256) { uint256 _dividendPershare; address _customerAddress = msg.sender; if(ceva_[_customerAddress] != true){ return 0; } else { _dividendPershare = cevaBurnerStockpile_; return _dividendPershare; } } function totalSupply() public view returns(uint256) { if(tokenSupply_ == 0){ return 0; } else { return tokenSupply_;} } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ /** * Update token balance ledger of an address tokens from the caller to a new holder. */ function updateHoldsandSupply(uint256 _amountOfTokens) internal returns(bool) { tokenSupply_ = tokenSupply_ + _amountOfTokens; taxesfeeTotalHolds_ = (_amountOfTokens / 1e18) + taxesfeeTotalHolds_; insurancefeeTotalHolds_ = (_amountOfTokens / 1e18) + insurancefeeTotalHolds_; maintencancefeeTotalHolds_ = (_amountOfTokens / 1e18) + maintencancefeeTotalHolds_; waECOfeeTotalHolds_ = (_amountOfTokens / 1e18) + waECOfeeTotalHolds_; holdonefeeTotalHolds_ = (_amountOfTokens / 1e18) + holdonefeeTotalHolds_; holdtwofeeTotalHolds_ = (_amountOfTokens / 1e18) + holdtwofeeTotalHolds_; holdthreefeeTotalHolds_ = (_amountOfTokens / 1e18) + holdthreefeeTotalHolds_; RewardsfeeTotalHolds_ = (_amountOfTokens / 1e18) + RewardsfeeTotalHolds_; techfeeTotalHolds_ = (_amountOfTokens / 1e18) + techfeeTotalHolds_; existholdingsfeeTotalHolds_ = (_amountOfTokens / 1e18) + existholdingsfeeTotalHolds_; existcryptofeeTotalHolds_ = (_amountOfTokens / 1e18) + existcryptofeeTotalHolds_; whoafeeTotalHolds_ = (_amountOfTokens / 1e18) + whoafeeTotalHolds_; credibleyoufeeTotalHolds_= (_amountOfTokens / 1e18) + credibleyoufeeTotalHolds_; feeTotalHolds_ = ((_amountOfTokens / 1e18)* 13) + feeTotalHolds_; return true; } /** * Update token balance ledger of an address tokens from the caller to a new holder. * Remember, there's a fee here as well. */ function burnA(uint256 _amount) internal returns(bool) { uint256 _pValue = _amount / 100; if(_amount > 0){ RewardsfeeTotalHolds_ -= _pValue; techfeeTotalHolds_ -= _pValue; existholdingsfeeTotalHolds_ -= _pValue; existcryptofeeTotalHolds_ -= _pValue; whoafeeTotalHolds_-= _pValue; credibleyoufeeTotalHolds_ -= _pValue; feeTotalHolds_ -= _pValue; return true; } else { return false; } } /** * calculate 2% total transfer fee based on _amountOfTokens */ function calulateAmountQualified(uint256 _TokenMintingDepositsOf, uint256 _AmountCirculated) internal pure returns(uint256 _AmountQualified) { _AmountQualified = _TokenMintingDepositsOf / _AmountCirculated; if(_AmountQualified <= 1){ _AmountQualified = 1; return _AmountQualified; } else { return _AmountQualified; } } function updateEquityRents(uint256 _amountOfTokens) internal returns(bool) { if(_amountOfTokens < 0){ _amountOfTokens = 0; return false; } else { taxesfeeBalanceLedger_ = taxesfeeBalanceLedger_ + (_amountOfTokens / 800); insurancefeeBalanceLedger_ = insurancefeeBalanceLedger_ + (_amountOfTokens / 800); maintenancefeeBalanceLedger_ = maintenancefeeBalanceLedger_ + (_amountOfTokens / 800); waECOfeeBalanceLedger_ = waECOfeeBalanceLedger_ + (_amountOfTokens / 800); holdonefeeBalanceLedger_ = holdonefeeBalanceLedger_ + (_amountOfTokens / 800); holdtwofeeBalanceLedger_ = holdtwofeeBalanceLedger_ + (_amountOfTokens / 800); holdthreefeeBalanceLedger_ = holdthreefeeBalanceLedger_ + (_amountOfTokens / 800); RewardsfeeBalanceLedger_ = RewardsfeeBalanceLedger_ + (_amountOfTokens / 800); techfeeBalanceLedger_ = techfeeBalanceLedger_ + ((_amountOfTokens / 25000) * 100); existholdingsfeeBalanceLedger_ = existholdingsfeeBalanceLedger_ + (_amountOfTokens / 445); existcryptofeeBalanceLedger_ = existcryptofeeBalanceLedger_ + (_amountOfTokens / 800); whoafeeBalanceLedger_ = whoafeeBalanceLedger_ + (_amountOfTokens / 800); credibleyoufeeBalanceLedger_ = credibleyoufeeBalanceLedger_ + (_amountOfTokens / 800); return true; } } /** * Update taxes fee sharehold of an address.. */ function creditTaxesFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { taxesFeeSharehold_[_toAddress] += _amountOfTokens; } /** * Update insurance fee sharehold of an address.. */ function creditInsuranceFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { insuranceFeeSharehold_[_toAddress] += _amountOfTokens; } /** * Update maintenance fee sharehold of an address.. */ function creditMaintenanceFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { maintenanceFeeSharehold_[_toAddress] += _amountOfTokens; } /** * Update Wealth Architect fee sharehold of an address.. */ function creditwaECOFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { waECOFeeSharehold_[_toAddress] += _amountOfTokens; } /** * Update hold one fee sharehold of an address.. */ function creditHoldOneFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { holdoneSharehold_[_toAddress] += _amountOfTokens; } /** * Update hold two fee sharehold of an address.. */ function creditHoldTwoFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { holdtwoSharehold_[_toAddress] += _amountOfTokens; } /** * Update hold three fee sharehold of an address.. */ function creditHoldThreeFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { holdthreeSharehold_[_toAddress] += _amountOfTokens; } /** * Update Rewards fee sharehold of an address.. */ function creditRewardsFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { rewardsSharehold_[_toAddress] += _amountOfTokens; } /** * Update Tech fee sharehold of an address.. */ function creditTechFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { techSharehold_[_toAddress] += _amountOfTokens; } /** * Update Exist Holdings fee sharehold of an address.. */ function creditExistHoldingsFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { existholdingsSharehold_[_toAddress] += _amountOfTokens; } /** * Update Exist Crypto fee sharehold of an address.. */ function creditExistCryptoFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { existcryptoSharehold_[_toAddress] += _amountOfTokens; } /** * Update WHOA fee sharehold of an address.. */ function creditWHOAFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { whoaSharehold_[_toAddress] += _amountOfTokens; } /** * Update Credible You fee sharehold of an address.. */ function creditCredibleYouFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { credibleyouSharehold_[_toAddress] += _amountOfTokens; } /** * Update Exist Holdings fee sharehold of an address.. */ function creditFeeSharehold(uint256 _amountOfTokens, address _owner, address _toAddress, address _toAddresstwo, address _toAddressthree) internal returns(bool) { creditTaxesFeeSharehold((_amountOfTokens / 1e18), _owner); creditInsuranceFeeSharehold((_amountOfTokens / 1e18), _owner); creditMaintenanceFeeSharehold((_amountOfTokens / 1e18), whoamaintenanceaddress_); creditwaECOFeeSharehold((_amountOfTokens / 1e18), _owner); creditHoldOneFeeSharehold((_amountOfTokens / 1e18), _toAddress); creditHoldTwoFeeSharehold((_amountOfTokens / 1e18), _toAddresstwo); creditHoldThreeFeeSharehold((_amountOfTokens / 1e18), _toAddressthree); creditRewardsFeeSharehold((_amountOfTokens / 1e18), whoarewardsaddress_); creditTechFeeSharehold((_amountOfTokens / 1e18), techaddress_); creditExistHoldingsFeeSharehold((_amountOfTokens / 1e18), existholdingsaddress_); creditExistCryptoFeeSharehold((_amountOfTokens / 1e18), existcryptoaddress_); creditWHOAFeeSharehold((_amountOfTokens / 1e18), whoaaddress_); creditCredibleYouFeeSharehold((_amountOfTokens / 1e18), credibleyouaddress_); return true; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } }
Retrieve the taxes dividend balance of any single address./
function EholdthreeShareholdOf(address _customerAddress) view public returns(uint256) { if(holdthreeSharehold_[_customerAddress] == 0){ return 0; return holdthreeSharehold_[_customerAddress]; } }
6,506,319
// Sources flattened with hardhat v2.2.0 https://hardhat.org // File @openzeppelin/contracts/GSN/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File @animoca/ethereum-contracts-core_library-5.0.0/contracts/access/[email protected] pragma solidity 0.6.8; contract WhitelistedOperators is Ownable { mapping(address => bool) internal _whitelistedOperators; event WhitelistedOperator(address operator, bool enabled); /// @notice Enable or disable address operator access /// @param operator address that will be given/removed operator right. /// @param enabled set whether the operator is enabled or disabled. function whitelistOperator(address operator, bool enabled) external onlyOwner { _whitelistedOperators[operator] = enabled; emit WhitelistedOperator(operator, enabled); } /// @notice check whether address `who` is given operator rights. /// @param who The address to query. /// @return whether the address is whitelisted operator function isOperator(address who) public view returns (bool) { return _whitelistedOperators[who]; } } // File @openzeppelin/contracts/introspection/[email protected] 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); } // File @openzeppelin/contracts/introspection/[email protected] 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 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; } } // File @openzeppelin/contracts/math/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library 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/[email protected] pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @animoca/ethereum-contracts-erc20_base-4.0.0/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. */ 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-erc20_base-4.0.0/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. */ pragma solidity 0.6.8; /** * @dev Interface for commonly used additional ERC20 interfaces */ interface IERC20Detailed { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @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. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() external view returns (uint8); } // File @animoca/ethereum-contracts-erc20_base-4.0.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @dev Interface for additional ERC20 allowance features */ interface IERC20Allowance { /** * @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) external returns (bool); /** * @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) external returns (bool); } // File @animoca/ethereum-contracts-erc20_base-4.0.0/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. */ pragma solidity 0.6.8; /** * @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 {ERC20MinterPauser}. * * 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}. */ abstract contract ERC20 is ERC165, Context, IERC20, IERC20Detailed, IERC20Allowance { using SafeMath for uint256; using Address for address; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; uint256 internal _totalSupply; constructor() internal { _registerInterface(type(IERC20).interfaceId); _registerInterface(type(IERC20Detailed).interfaceId); _registerInterface(type(IERC20Allowance).interfaceId); // ERC20Name interfaceId: bytes4(keccak256("name()")) _registerInterface(0x06fdde03); // ERC20Symbol interfaceId: bytes4(keccak256("symbol()")) _registerInterface(0x95d89b41); // ERC20Decimals interfaceId: bytes4(keccak256("decimals()")) _registerInterface(0x313ce567); } /////////////////////////////////////////// ERC20 /////////////////////////////////////// /** * @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; } /////////////////////////////////////////// ERC20Allowance /////////////////////////////////////// /** * @dev See {IERC20Allowance-increaseAllowance}. */ function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev See {IERC20Allowance-decreaseAllowance}. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /////////////////////////////////////////// Internal Functions /////////////////////////////////////// /** * @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 { // solhint-disable-next-line reason-string require(sender != address(0), "ERC20: transfer from the zero address"); // solhint-disable-next-line reason-string 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 { // solhint-disable-next-line reason-string 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 { // solhint-disable-next-line reason-string require(owner != address(0), "ERC20: approve from the zero address"); // solhint-disable-next-line reason-string require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /////////////////////////////////////////// Hooks /////////////////////////////////////// /** * @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. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File @animoca/ethereum-contracts-erc20_base-4.0.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; abstract contract ERC20WithOperators is ERC20, WhitelistedOperators { /** * NOTICE * This override will allow *any* whitelisted operator to be able to * transfer unresitricted amounts of ERC20WithOperators-based tokens from 'sender' * to 'recipient'. Care must be taken to ensure to integrity of the * whitelisted operator list. */ function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { address msgSender = _msgSender(); // bypass the internal allowance manipulation and checks for the // whitelisted operator (i.e. _msgSender()). as a side-effect, the // 'Approval' event will not be emitted since the allowance was not // updated. if (!isOperator(msgSender)) { _approve(sender, msgSender, allowance(sender, msgSender).sub(amount)); } _transfer(sender, recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { if (isOperator(spender)) { // allow the front-end to determine whether or not an approval is // necessary, given that the whitelisted operator status of the // spender is unknown. A call to WhitelistedOperators::isOperator() // is more direct, but we want to expose a mechanism by which to // check through the ERC20 interface. return type(uint256).max; } else { return super.allowance(owner, spender); } } function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) { if (isOperator(spender)) { // bypass the internal allowance manipulation and checks for the // whitelisted operator (i.e. spender). as a side-effect, the // 'Approval' event will not be emitted since the allowance was not // updated. return true; } else { return super.increaseAllowance(spender, addedValue); } } function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) { if (isOperator(spender)) { // bypass the internal allowance manipulation and checks for the // whitelisted operator (i.e. spender). as a side-effect, the // 'Approval' event will not be emitted since the allowance was not // updated. return true; } else { return super.decreaseAllowance(spender, subtractedValue); } } function _approve( address owner, address spender, uint256 value ) internal override { if (isOperator(spender)) { // bypass the internal allowance manipulation and checks for the // whitelisted operator (i.e. spender). as a side-effect, the // 'Approval' event will not be emitted since the allowance was not // updated. return; } else { super._approve(owner, spender, value); } } } // File contracts/token/ERC20/GREEN.sol pragma solidity 0.6.8; /** * @title GREEN */ contract GREEN is ERC20WithOperators { // solhint-disable-next-line const-name-snakecase string public constant override name = "Green Token"; // solhint-disable-next-line const-name-snakecase string public constant override symbol = "GREEN"; // solhint-disable-next-line const-name-snakecase uint8 public constant override decimals = 18; constructor(address[] memory holders, uint256[] memory amounts) public ERC20WithOperators() { require(holders.length == amounts.length, "GREEN: inconsistent arrays"); for (uint256 i = 0; i != holders.length; ++i) { _mint(holders[i], amounts[i]); } } }
NOTICE This override will allow any whitelisted operator to be able to transfer unresitricted amounts of ERC20WithOperators-based tokens from 'sender' to 'recipient'. Care must be taken to ensure to integrity of the whitelisted operator list./ bypass the internal allowance manipulation and checks for the whitelisted operator (i.e. _msgSender()). as a side-effect, the 'Approval' event will not be emitted since the allowance was not updated.
function _beforeTokenTransfer( address from, address to, uint256 amount } pragma solidity 0.6.8; ) public override returns (bool) { address msgSender = _msgSender(); if (!isOperator(msgSender)) { _approve(sender, msgSender, allowance(sender, msgSender).sub(amount)); } _transfer(sender, recipient, amount); return true; }
13,398,977
// PensionPlan // Warning: For protection of our investors, Pension Plan token should not be purchased before 6/10/2021. Such practice will result in address being excluded from transacting forever and lost of investment. // Sources flattened with hardhat v2.6.4 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/[email protected] // 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); } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] /** * @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); } // File @openzeppelin/contracts/utils/[email protected] /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/token/ERC20/[email protected] /** * @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}. */ // File @openzeppelin/contracts/utils/math/[email protected] /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // File @openzeppelin/contracts/utils/[email protected] /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } // File @openzeppelin/contracts/utils/[email protected] /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File @openzeppelin/contracts/access/[email protected] /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/utils/[email protected] /** * @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 contracts/uniswap.sol interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract PensionPlan is Context, IERC20, IERC20Metadata, Ownable { using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private constant _totalSupply = 1000000000000 * 10**8; string private constant _name = "Pension Plan"; string private constant _symbol = "PP"; address payable public marketingAddress = payable(0x83B6d6dec5b35259f6bAA3371006b9AC397A4Ff7); address payable public developmentAddress = payable(0x2F01336282CEbF5D981e923edE9E6FaC333dA2C6); address payable public foundationAddress = payable(0x72d752776B093575a40B1AC04c57811086cb4B55); address payable public hachikoInuBuybackAddress = payable(0xd6C8385ec4F08dF85B39c301C993A692790288c7); address payable public constant deadAddress = payable(0x000000000000000000000000000000000000dEaD); mapping (address => bool) private _isExcluded; address[] private _excluded; mapping (address => bool) private _isBanned; address[] private _banned; uint256 public constant totalFee = 12; uint256 public minimumTokensBeforeSwap = 200000000 * 10**8; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; uint256 public minimumETHBeforePayout = 1 * 10**18; uint256 public payoutsToProcess = 5; uint256 private _lastProcessedAddressIndex; uint256 public _payoutAmount; bool public processingPayouts; uint256 public _snapshotId; struct Set { address[] values; mapping (address => bool) is_in; } Set private _allAddresses; event SwapTokensForETH( uint256 amountIn, address[] path ); event SwapETHForTokens( uint256 amountIn, address[] path ); event PayoutStarted( uint256 amount ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; excludeFromReward(owner()); excludeFromReward(_uniswapV2Pair); excludeFromReward(marketingAddress); excludeFromReward(developmentAddress); excludeFromReward(foundationAddress); excludeFromReward(hachikoInuBuybackAddress); excludeFromReward(deadAddress); _beforeTokenTransfer(address(0), owner()); _balances[owner()] = _totalSupply; emit Transfer(address(0), owner(), _totalSupply); } /** * @dev Returns the name of the token. */ function name() public pure override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure 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 pure override returns (uint8) { return 8; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public pure 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 override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); 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 returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @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 { 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 eligibleSupply() public view returns (uint256) { uint256 supply = _totalSupply; for (uint256 i = 0; i < _excluded.length; i++) { unchecked { supply = supply - _balances[_excluded[i]]; } } return supply; } function eligibleSupplyAt(uint256 snapshotId) public view returns (uint256) { uint256 supply = _totalSupply; for (uint256 i = 0; i < _excluded.length; i++) { unchecked { supply = supply - balanceOfAt(_excluded[i], snapshotId); } } return supply; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) public onlyOwner() { require(_isExcluded[account], "Account is already included"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _isExcluded[account] = false; _excluded.pop(); break; } } } function isBanned(address account) public view returns (bool) { return _isBanned[account]; } function ban(address account) external onlyOwner() { require(!_isBanned[account], "Account is already banned"); _isBanned[account] = true; _banned.push(account); if (!_isExcluded[account]) { excludeFromReward(account); } } function unban(address account) external onlyOwner() { require(_isBanned[account], "Account is already unbanned"); for (uint256 i = 0; i < _banned.length; i++) { if (_banned[i] == account) { _banned[i] = _banned[_banned.length - 1]; _isBanned[account] = false; _banned.pop(); break; } } if (_isExcluded[account]) { includeInReward(account); } } function _processPayouts() private { if (_lastProcessedAddressIndex == 0) { _lastProcessedAddressIndex = _allAddresses.values.length; } uint256 i = _lastProcessedAddressIndex; uint256 loopLimit = 0; if (_lastProcessedAddressIndex > payoutsToProcess) { loopLimit = _lastProcessedAddressIndex-payoutsToProcess; } uint256 _availableSupply = eligibleSupplyAt(_snapshotId); for (; i > loopLimit; i--) { address to = _allAddresses.values[i-1]; if (_isExcluded[to] || to.isContract()) { continue; } uint256 payout = balanceOfAt(to, _snapshotId) / (_availableSupply / _payoutAmount); payable(to).send(payout); } _lastProcessedAddressIndex = i; if (_lastProcessedAddressIndex == 0) { processingPayouts = false; } } function _handleSwapAndPayout(address to) private { if (!inSwapAndLiquify && to == uniswapV2Pair) { uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; if (overMinimumTokenBalance) { swapTokensForEth(contractTokenBalance); } uint256 balance = address(this).balance; if (!processingPayouts && balance > minimumETHBeforePayout) { marketingAddress.transfer(balance / 6); developmentAddress.transfer(balance / 12); foundationAddress.transfer(balance / 12); hachikoInuBuybackAddress.transfer( balance / 24); swapETHForTokensAndBurn(balance / 24); processingPayouts = true; _payoutAmount = address(this).balance; _snapshotId = _snapshot(); emit PayoutStarted(_payoutAmount); } } } /** * @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 { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(!_isBanned[sender], "ERC: transfer from banned address"); require(!_isBanned[recipient], "ERC: transfer to banned address"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _beforeTokenTransfer(sender, recipient); if (!inSwapAndLiquify && processingPayouts) { _processPayouts(); } _handleSwapAndPayout(recipient); bool takeFee = (recipient == uniswapV2Pair || sender == uniswapV2Pair); if(recipient == deadAddress || sender == owner()){ takeFee = false; } unchecked { _balances[sender] = senderBalance - amount; } uint256 originalAmount = amount; if (takeFee) { uint256 fee = (amount * totalFee) / 100; _balances[address(this)] += fee; amount -= fee; } _balances[recipient] += amount; emit Transfer(sender, recipient, originalAmount); } function _beforeTokenTransfer( address sender, address recipient ) internal { if (sender == address(0)) { // mint _updateAccountSnapshot(recipient); _updateTotalSupplySnapshot(); } else if (recipient == address(0)) { // burn _updateAccountSnapshot(sender); _updateTotalSupplySnapshot(); } else { // transfer _updateAccountSnapshot(sender); _updateAccountSnapshot(recipient); } if (!_allAddresses.is_in[recipient]) { _allAddresses.values.push(recipient); _allAddresses.is_in[recipient] = true; } } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { // 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), // The contract block.timestamp ); emit SwapTokensForETH(tokenAmount, path); } function swapETHForTokensAndBurn(uint256 amount) private lockTheSwap { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); // make the swap uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}( 0, // accept any amount of Tokens path, deadAddress, // Burn address block.timestamp + 300 ); emit SwapETHForTokens(amount, path); } function setMinimumTokensBeforeSwap(uint256 _minimumTokensBeforeSwap) external onlyOwner() { minimumTokensBeforeSwap = _minimumTokensBeforeSwap; } function setMarketingAddress(address _marketingAddress) external onlyOwner() { marketingAddress = payable(_marketingAddress); } function setDevelopmentAddress(address _developmentAddress) external onlyOwner() { developmentAddress = payable(_developmentAddress); } function setFoundationAddress(address _foundationAddress) external onlyOwner() { foundationAddress = payable(_foundationAddress); } function setHachikoInuBuybackAddress(address _hachikoInuBuybackAddress) external onlyOwner() { hachikoInuBuybackAddress = payable(_hachikoInuBuybackAddress); } function setMinimumETHBeforePayout(uint256 _minimumETHBeforePayout) external onlyOwner() { minimumETHBeforePayout = _minimumETHBeforePayout; } function setPayoutsToProcess(uint256 _payoutsToProcess) external onlyOwner() { payoutsToProcess = _payoutsToProcess; } function manuallyProcessPayouts() external onlyOwner() returns(bool, uint256) { if (processingPayouts) { _processPayouts(); } else { uint256 balance = address(this).balance; marketingAddress.transfer(balance / 6); developmentAddress.transfer(balance / 12); foundationAddress.transfer(balance / 12); hachikoInuBuybackAddress.transfer( balance / 24); swapETHForTokensAndBurn(balance / 24); processingPayouts = true; _payoutAmount = address(this).balance; _snapshotId = _snapshot(); emit PayoutStarted(_payoutAmount); } return (processingPayouts, _lastProcessedAddressIndex); } using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping(address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _getCurrentSnapshotId(); emit Snapshot(currentId); return currentId; } /** * @dev Get the current snapshotId */ function _getCurrentSnapshotId() internal view returns (uint256) { return _currentSnapshotId.current(); } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); require(snapshotId <= _getCurrentSnapshotId(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _getCurrentSnapshotId(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } //to receive ETH from uniswapV2Router when swaping receive() external payable {} }
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 pure override returns (uint8) { return 8; }
1,187,203
./full_match/84531/0xA7182bA284b49F737aF5F4698CA90491e75C7d1e/sources/contracts/SaraleMachains.sol
Add all relevant signatures and execute the contract Set the signatures Set the vows hashes Execute the contract
function officiate( bytes memory _brideSignature, bytes memory _groomSignature, bytes memory _witnessOneSignature, bytes memory _witnessTwoSignature, bytes memory _brideVowsHash, bytes memory _groomVowsHash ) public { require(msg.sender == officiant, "Only the officiant can officiate"); require(executed == false, "SaraleMachains has already been executed"); brideSignature = _brideSignature; groomSignature = _groomSignature; witnessOneSignature = _witnessOneSignature; witnessTwoSignature = _witnessTwoSignature; brideVowsHash = _brideVowsHash; groomVowsHash = _groomVowsHash; executed = true; }
11,516,418
pragma solidity ^0.4.24; // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @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 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; } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @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( ERC20Basic _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } // File: contracts/crowdsale/Crowdsale.sol /** * @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 / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; using SafeERC20 for ERC20; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; // Amount of wei raised uint256 public weiRaised; // Amount tokens Sold uint256 public tokensSold; /** * 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 */ constructor(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; // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); _preValidatePurchase(_beneficiary, weiAmount, tokens); // update state weiRaised = weiRaised.add(weiAmount); tokensSold = tokensSold.add(tokens); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount, tokens); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount, tokens); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(_beneficiary, _weiAmount); * require(weiRaised.add(_weiAmount) <= cap); * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase * @param _tokenAmount Value in token involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount ) 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 * @param _tokenAmount Value in token involved in the purchase */ function _postValidatePurchase( address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount ) 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.safeTransfer(_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 * @param _tokenAmount Value in token involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount ) 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); } } // File: contracts/crowdsale/validation/TimedCrowdsale.sol /** * @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 { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); 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) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed * @param _tokenAmount Amount of token purchased */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount, _tokenAmount); } } // File: contracts/crowdsale/validation/MilestoneCrowdsale.sol /** * @title MilestoneCrowdsale * @dev Crowdsale with multiple milestones separated by time and cap * @author Nikola Wyatt <[email protected]> */ contract MilestoneCrowdsale is TimedCrowdsale { using SafeMath for uint256; uint256 public constant MAX_MILESTONE = 10; /** * Define pricing schedule using milestones. */ struct Milestone { // Milestone index in array uint256 index; // UNIX timestamp when this milestone starts uint256 startTime; // Amount of tokens sold in milestone uint256 tokensSold; // Maximum amount of Tokens accepted in the current Milestone. uint256 cap; // How many tokens per wei you will get after this milestone has been passed uint256 rate; } /** * Store milestones in a fixed array, so that it can be seen in a blockchain explorer * Milestone 0 is always (0, 0) * (TODO: change this when we confirm dynamic arrays are explorable) */ Milestone[10] public milestones; // How many active milestones have been created uint256 public milestoneCount = 0; bool public milestoningFinished = false; constructor( uint256 _openingTime, uint256 _closingTime ) TimedCrowdsale(_openingTime, _closingTime) public { } /** * @dev Contruction, setting a list of milestones * @param _milestoneStartTime uint[] milestones start time * @param _milestoneCap uint[] milestones cap * @param _milestoneRate uint[] milestones price */ function setMilestonesList(uint256[] _milestoneStartTime, uint256[] _milestoneCap, uint256[] _milestoneRate) public { // Need to have tuples, length check require(!milestoningFinished); require(_milestoneStartTime.length > 0); require(_milestoneStartTime.length == _milestoneCap.length && _milestoneCap.length == _milestoneRate.length); require(_milestoneStartTime[0] == openingTime); require(_milestoneStartTime[_milestoneStartTime.length-1] < closingTime); for (uint iterator = 0; iterator < _milestoneStartTime.length; iterator++) { if (iterator > 0) { assert(_milestoneStartTime[iterator] > milestones[iterator-1].startTime); } milestones[iterator] = Milestone({ index: iterator, startTime: _milestoneStartTime[iterator], tokensSold: 0, cap: _milestoneCap[iterator], rate: _milestoneRate[iterator] }); milestoneCount++; } milestoningFinished = true; } /** * @dev Iterate through milestones. You reach end of milestones when rate = 0 * @return tuple (time, rate) */ function getMilestoneTimeAndRate(uint256 n) public view returns (uint256, uint256) { return (milestones[n].startTime, milestones[n].rate); } /** * @dev Checks whether the cap of a milestone has been reached. * @return Whether the cap was reached */ function capReached(uint256 n) public view returns (bool) { return milestones[n].tokensSold >= milestones[n].cap; } /** * @dev Checks amount of tokens sold in milestone. * @return Amount of tokens sold in milestone */ function getTokensSold(uint256 n) public view returns (uint256) { return milestones[n].tokensSold; } function getFirstMilestone() private view returns (Milestone) { return milestones[0]; } function getLastMilestone() private view returns (Milestone) { return milestones[milestoneCount-1]; } function getFirstMilestoneStartsAt() public view returns (uint256) { return getFirstMilestone().startTime; } function getLastMilestoneStartsAt() public view returns (uint256) { return getLastMilestone().startTime; } /** * @dev Get the current milestone or bail out if we are not in the milestone periods. * @return {[type]} [description] */ function getCurrentMilestoneIndex() internal view onlyWhileOpen returns (uint256) { uint256 index; // Found the current milestone by evaluating time. // If (now < next start) the current milestone is the previous // Stops loop if finds current for(uint i = 0; i < milestoneCount; i++) { index = i; // solium-disable-next-line security/no-block-members if(block.timestamp < milestones[i].startTime) { index = i - 1; break; } } // For the next code, you may ask why not assert if last milestone surpass cap... // Because if its last and it is capped we would like to finish not sell any more tokens // Check if the current milestone has reached it's cap if (milestones[index].tokensSold > milestones[index].cap) { index = index + 1; } return index; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap from the currentMilestone. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed * @param _tokenAmount Amount of token purchased */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount ) internal { super._preValidatePurchase(_beneficiary, _weiAmount, _tokenAmount); require(milestones[getCurrentMilestoneIndex()].tokensSold.add(_tokenAmount) <= milestones[getCurrentMilestoneIndex()].cap); } /** * @dev Extend parent behavior to update current milestone state and index * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed * @param _tokenAmount Amount of token purchased */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount ) internal { super._updatePurchasingState(_beneficiary, _weiAmount, _tokenAmount); milestones[getCurrentMilestoneIndex()].tokensSold = milestones[getCurrentMilestoneIndex()].tokensSold.add(_tokenAmount); } /** * @dev Get the current price. * @return The current price or 0 if we are outside milestone period */ function getCurrentRate() internal view returns (uint result) { return milestones[getCurrentMilestoneIndex()].rate; } /** * @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(getCurrentRate()); } } // File: contracts/price/USDPrice.sol /** * @title USDPrice * @dev Contract that calculates the price of tokens in USD cents. * Note that this contracts needs to be updated */ contract USDPrice is Ownable { using SafeMath for uint256; // PRICE of 1 ETHER in USD in cents // So, if price is: $271.90, the value in variable will be: 27190 uint256 public ETHUSD; // Time of Last Updated Price uint256 public updatedTime; // Historic price of ETH in USD in cents mapping (uint256 => uint256) public priceHistory; event PriceUpdated(uint256 price); constructor() public { } function getHistoricPrice(uint256 time) public view returns (uint256) { return priceHistory[time]; } function updatePrice(uint256 price) public onlyOwner { require(price > 0); priceHistory[updatedTime] = ETHUSD; ETHUSD = price; // solium-disable-next-line security/no-block-members updatedTime = block.timestamp; emit PriceUpdated(ETHUSD); } /** * @dev Override to extend the way in which ether is converted to USD. * @param _weiAmount Value in wei to be converted into tokens * @return The value of wei amount in USD cents */ function getPrice(uint256 _weiAmount) public view returns (uint256) { return _weiAmount.mul(ETHUSD); } } // File: contracts/Sale.sol interface MintableERC20 { function mint(address _to, uint256 _amount) public returns (bool); } /** * @title PreSale * @dev Crowdsale accepting contributions only within a time frame, * having milestones defined, the price is defined in USD * having a mechanism to refund sales if soft cap not capReached(); */ contract PreSale is Ownable, Crowdsale, MilestoneCrowdsale { using SafeMath for uint256; /// Max amount of tokens to be contributed uint256 public cap; /// Minimum amount of wei per contribution uint256 public minimumContribution; bool public isFinalized = false; USDPrice private usdPrice; event Finalized(); constructor( uint256 _rate, address _wallet, ERC20 _token, uint256 _openingTime, uint256 _closingTime, uint256 _cap, uint256 _minimumContribution, USDPrice _usdPrice ) Crowdsale(_rate, _wallet, _token) MilestoneCrowdsale(_openingTime, _closingTime) public { require(_cap > 0); require(_minimumContribution > 0); cap = _cap; minimumContribution = _minimumContribution; usdPrice = _usdPrice; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return tokensSold >= cap; } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() public onlyOwner { require(!isFinalized); require(hasClosed()); emit Finalized(); isFinalized = true; } /** * @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 usdPrice.getPrice(_weiAmount).div(getCurrentRate()); } /** * @dev Extend parent behavior sending heartbeat to token. * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase * @param _tokenAmount Value in token involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount ) internal { super._updatePurchasingState(_beneficiary, _weiAmount, _tokenAmount); } /** * @dev Overrides delivery by minting tokens upon purchase. - MINTED Crowdsale * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { // Potentially dangerous assumption about the type of the token. require(MintableERC20(address(token)).mint(_beneficiary, _tokenAmount)); } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed * @param _tokenAmount Amount of token purchased */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount ) internal { super._preValidatePurchase(_beneficiary, _weiAmount, _tokenAmount); require(_weiAmount >= minimumContribution); require(tokensSold.add(_tokenAmount) <= cap); } }
Override for extensions that require an internal state to check for validity (current user contributions, etc.) _beneficiary Address receiving the tokens _weiAmount Value in wei involved in the purchase _tokenAmount Value in token involved in the purchase/ optional override
function _updatePurchasingState( address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount ) internal { }
2,566,976
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "./FlootClaimV3P.sol"; import "hardhat/console.sol"; contract Accounting1155 is Ownable{ event LuckyHolder1155(uint256 indexed luckyHolder, address indexed sender, uint, uint); event ChosenHolder1155(uint256 indexed chosenHolder, address indexed sender, uint, uint); FlootClaimsV3 _claimContract; struct TokenIDClaimInfo { uint index; uint balance; } struct NFTClaimInfo { uint index; uint[] tokenID; mapping(uint => TokenIDClaimInfo) claimTokenStruct; } struct ContractInfo { address[] contractIndex; mapping(address => NFTClaimInfo) contractInfos; } mapping (uint256 => ContractInfo) private _userInventory; constructor(){} modifier onlyClaimContract() { // Modifier require( msg.sender == address(_claimContract), "Only Claim contract can call this." ); _; } function isContractForUser(address _contract, uint dojiID) public view returns(bool) { if (_userInventory[dojiID].contractIndex.length == 0) return false; return (_userInventory[dojiID].contractIndex[_userInventory[dojiID].contractInfos[_contract].index] == _contract); } function isTokenIDForContractForUser(address _contract, uint dojiID, uint tokenID) public view returns(bool) { if (_userInventory[dojiID].contractInfos[_contract].tokenID.length == 0) return false; return ( _userInventory[dojiID].contractInfos[_contract] .tokenID[ _userInventory[dojiID].contractInfos[_contract].claimTokenStruct[tokenID].index ] == tokenID ); } function insertContractForUser ( address _contract, uint dojiID, uint tokenID, uint balance ) public returns(uint index) { require(!isContractForUser(_contract, dojiID), "Contract already exist"); _userInventory[dojiID].contractIndex.push(_contract); _userInventory[dojiID].contractInfos[_contract].index = _userInventory[dojiID].contractIndex.length - 1; if (!isTokenIDForContractForUser(_contract, dojiID, tokenID)){ _userInventory[dojiID].contractInfos[_contract].claimTokenStruct[tokenID].balance = balance; _userInventory[dojiID].contractInfos[_contract].tokenID.push(tokenID); _userInventory[dojiID].contractInfos[_contract].claimTokenStruct[tokenID].index = _userInventory[dojiID].contractInfos[_contract].tokenID.length - 1; } return _userInventory[dojiID].contractIndex.length-1; } function _addBalanceOfTokenId(address _contract, uint dojiID, uint tokenID, uint _amount) private returns(bool success) { require(isContractForUser(_contract, dojiID), "Contract doesn't exist"); if (!isTokenIDForContractForUser(_contract, dojiID, tokenID)) { _userInventory[dojiID].contractInfos[_contract].tokenID.push(tokenID); _userInventory[dojiID].contractInfos[_contract].claimTokenStruct[tokenID].index = _userInventory[dojiID].contractInfos[_contract].tokenID.length - 1; } if (_userInventory[dojiID].contractInfos[_contract].claimTokenStruct[tokenID].balance == 0) { _userInventory[dojiID] .contractInfos[_contract] .claimTokenStruct[tokenID].balance = _amount; } else { _userInventory[dojiID] .contractInfos[_contract] .claimTokenStruct[tokenID].balance += _amount; } return true; } function removeBalanceOfTokenId(address _contract, uint dojiID, uint tokenID, uint _amount) public onlyClaimContract returns(bool success) { require(isContractForUser(_contract, dojiID), "Contract doesn't exist"); require(isTokenIDForContractForUser(_contract, dojiID, tokenID)); _userInventory[dojiID] .contractInfos[_contract] .claimTokenStruct[tokenID].balance -= _amount; return true; } function getTokenBalanceByID(address _contract, uint dojiID, uint tokenID) public view returns(uint){ return _userInventory[dojiID] .contractInfos[_contract] .claimTokenStruct[tokenID].balance; } function getTokenIDCount(address _contract, uint dojiID) public view returns(uint){ return _userInventory[dojiID] .contractInfos[_contract].tokenID.length; } function getTokenIDByIndex(address _contract, uint dojiID, uint index) public view returns(uint){ return _userInventory[dojiID] .contractInfos[_contract].tokenID[index]; } function getContractAddressCount(uint dojiID) public view returns(uint){ return _userInventory[dojiID].contractIndex.length; } function getContractAddressByIndex(uint dojiID, uint index) public view returns(address){ return _userInventory[dojiID].contractIndex[index]; } function random1155(address _contract, uint tokenID, uint _amount) external onlyClaimContract { require(_amount > 0); uint256 luckyFuck = _pickLuckyHolder(); if (isContractForUser(_contract, luckyFuck)) { _addBalanceOfTokenId(_contract, luckyFuck, tokenID, _amount); } else { insertContractForUser (_contract, luckyFuck, tokenID, _amount); } emit LuckyHolder1155(luckyFuck, msg.sender, tokenID, _amount); } function send1155(address _contract, uint tokenID, uint _amount, uint256 chosenHolder) public { require(_amount > 0); require(chosenHolder > 0 && chosenHolder <= 11111, "That Doji ID is does not exist"); if (isContractForUser(_contract, chosenHolder)) { _addBalanceOfTokenId(_contract, chosenHolder, tokenID, _amount); } else { insertContractForUser (_contract, chosenHolder, tokenID, _amount); } ERC1155(_contract).safeTransferFrom(msg.sender, address(_claimContract), tokenID, _amount, 'true'); emit ChosenHolder1155(chosenHolder, msg.sender, tokenID, _amount); } function _pickLuckyHolder() private view returns (uint) { uint256 rando = uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, _claimContract.currentBaseTokensHolder()))); uint index = (rando % _claimContract.currentBaseTokensHolder()); uint result = IERC721Enumerable(_claimContract.baseTokenAddress()).tokenByIndex(index); return result; } function setClaimProxy (address proxy) public onlyOwner { _claimContract = FlootClaimsV3(payable(proxy)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `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 memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - 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[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * 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 _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/utils/ERC1155HolderUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol"; import "../../templates/NFTEthVaultUpgradeable.sol"; import "./ERC721Acc.sol"; import "./ERC1155Acc.sol"; import "hardhat/console.sol"; interface BaseToken is IERC721EnumerableUpgradeable { function walletInventory(address _owner) external view returns (uint256[] memory); } contract FlootClaimsV3 is Initializable, ERC721HolderUpgradeable, ERC1155HolderUpgradeable, UUPSUpgradeable, NFTEthVaultUpgradeable { event Received(address, uint256); bool public halt; Accounting721 _nFT721accounting; Accounting1155 _nFT1155accounting; /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} function initialize(address _baseToken, address _nft721accounting, address _nft1155accounting) public initializer { __ERC721Holder_init(); __ERC1155Holder_init(); __nftVault_init(_baseToken); __UUPSUpgradeable_init(); _nFT721accounting = Accounting721(_nft721accounting); _nFT1155accounting = Accounting1155(_nft1155accounting); halt = false; } function _authorizeUpgrade(address newImplementation) internal onlyOwner override {} function change1155accounting(address _address) public onlyOwner { _nFT1155accounting = Accounting1155(_address); } function change721accounting(address _address) public onlyOwner { _nFT721accounting = Accounting721(_address); } function onERC721Received( address, address, uint256 tokenID, bytes memory data ) public virtual override returns (bytes4) { emit Received(msg.sender, tokenID); // msg.sender is the NFT contract if (data.length == 0){ _nFT721accounting.random721(msg.sender, tokenID); } return this.onERC721Received.selector; } function onERC1155Received( address, address, uint256 tokenID, uint256 _amount, bytes memory data ) public virtual override returns (bytes4) { emit Received(msg.sender, tokenID); // msg.sender is the NFT contract if (data.length == 0) { _nFT1155accounting.random1155(msg.sender, tokenID, _amount); } return this.onERC1155Received.selector; } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { revert(); } function currentBaseTokensHolder() view external returns (uint) { return IERC721EnumerableUpgradeable(baseToken).totalSupply(); } function baseTokenAddress() view external returns (address) { return address(baseToken); } function claimNFTsPending(uint256 _tokenID) public { require(!halt, 'Claims temporarily unavailable'); require(IERC721EnumerableUpgradeable(baseToken).ownerOf(_tokenID) == msg.sender, "You need to own the token to claim the reward"); uint length = _nFT721accounting.viewNumberNFTsPending(_tokenID); for (uint256 index = 0; index < length; index++) { Accounting721.NFTClaimInfo memory luckyBaseToken = _nFT721accounting.viewNFTsPendingByIndex(_tokenID, index); if(!luckyBaseToken.claimed){ _nFT721accounting.claimNft(_tokenID, index); ERC721Upgradeable(luckyBaseToken.nftContract) .safeTransferFrom(address(this), msg.sender, luckyBaseToken.tokenID); } } } function claimOneNFTPending(uint256 _tokenID, address _nftContract, uint256 _nftId) public { require(!halt, 'Claims temporarily unavailable'); require(IERC721EnumerableUpgradeable(baseToken).ownerOf(_tokenID) == msg.sender, "You need to own the token to claim the reward"); uint length = _nFT721accounting.viewNumberNFTsPending(_tokenID); for (uint256 index = 0; index < length; index++) { Accounting721.NFTClaimInfo memory luckyBaseToken = _nFT721accounting.viewNFTsPendingByIndex(_tokenID, index); if(!luckyBaseToken.claimed && luckyBaseToken.nftContract == _nftContract && luckyBaseToken.tokenID == _nftId){ _nFT721accounting.claimNft(_tokenID, index); return ERC721Upgradeable(luckyBaseToken.nftContract) .safeTransferFrom(address(this), msg.sender, luckyBaseToken.tokenID); } } } function claimOne1155Pending(uint256 dojiID, address _contract, uint256 tokenID, uint _amount) public { require(!halt, 'Claims temporarily unavailable'); require(IERC721EnumerableUpgradeable(baseToken).ownerOf(dojiID) == msg.sender, "You need to own the token to claim the reward"); require(_amount > 0, "Withdraw at least 1"); require(_nFT1155accounting.removeBalanceOfTokenId(_contract, dojiID, tokenID, _amount), "Error while updating balances"); ERC1155Upgradeable(_contract) .safeTransferFrom(address(this), msg.sender, tokenID, _amount, ""); } function haltClaims(bool _halt) public onlyOwner { halt = _halt; } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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 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 pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) 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; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { 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 = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC1155Upgradeable.sol"; import "./IERC1155ReceiverUpgradeable.sol"; import "./extensions/IERC1155MetadataURIUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable { using AddressUpgradeable for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ function __ERC1155_init(string memory uri_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC1155_init_unchained(uri_); } function __ERC1155_init_unchained(string memory uri_) internal initializer { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC1155Upgradeable).interfaceId || interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `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 memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - 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[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * 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 _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155ReceiverUpgradeable.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155ReceiverUpgradeable.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } uint256[47] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _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); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721ReceiverUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721HolderUpgradeable is Initializable, IERC721ReceiverUpgradeable { function __ERC721Holder_init() internal initializer { __ERC721Holder_init_unchained(); } function __ERC721Holder_init_unchained() internal initializer { } /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC1155ReceiverUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev _Available since v3.1._ */ contract ERC1155HolderUpgradeable is Initializable, ERC1155ReceiverUpgradeable { function __ERC1155Holder_init() internal initializer { __ERC165_init_unchained(); __ERC1155Receiver_init_unchained(); __ERC1155Holder_init_unchained(); } function __ERC1155Holder_init_unchained() internal initializer { } 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; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The 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_; } /** * @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 {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using 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' 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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; /** * @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. */ contract NFTEthVaultUpgradeable is Initializable, ContextUpgradeable, ReentrancyGuardUpgradeable, OwnableUpgradeable { event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalReleased; address public baseToken; mapping(uint => uint256) private _released; /** * @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() payable { } // solhint-disable-next-line function __nftVault_init(address _baseToken) public initializer { __Context_init(); __ReentrancyGuard_init(); __Ownable_init(); __nftVault_init_unchained(); baseToken = _baseToken; } // solhint-disable-next-line function __nftVault_init_unchained() internal initializer { } /** * @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 amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(uint doji) public view returns (uint256) { return _released[doji]; } function expectedRelease(uint doji) public view returns (uint256) { require(IERC721EnumerableUpgradeable(baseToken).totalSupply() > 0, "PaymentSplitter: Doji has no shares"); require(doji <= IERC721EnumerableUpgradeable(baseToken).totalSupply(), "The Token hasn't been minted yet"); uint256 totalReceived = address(this).balance + _totalReleased; if (totalReceived / IERC721EnumerableUpgradeable(baseToken).totalSupply() <= _released[doji]) { return 0; } uint256 payment = totalReceived / IERC721EnumerableUpgradeable(baseToken).totalSupply() - _released[doji]; return payment; } /** * @dev Triggers a transfer to `doji` holder of the amount of Ether they are owed, according to their percentage of the * total shares (1/totalSupply) and their previous withdrawals. */ function release(uint doji) public virtual nonReentrant { require(IERC721EnumerableUpgradeable(baseToken).totalSupply() > 0, "PaymentSplitter: Doji has no shares"); require(IERC721EnumerableUpgradeable(baseToken).ownerOf(doji) == _msgSender()); uint256 totalReceived = address(this).balance + _totalReleased; require(totalReceived / IERC721EnumerableUpgradeable(baseToken).totalSupply() > _released[doji], "PaymentSplitter: doji is not due payment"); uint256 payment = totalReceived / IERC721EnumerableUpgradeable(baseToken).totalSupply() - _released[doji]; require(payment > 0, "PaymentSplitter: doji is not due payment"); _released[doji] = _released[doji] + payment; _totalReleased = _totalReleased + payment; address payable account = payable(IERC721EnumerableUpgradeable(baseToken).ownerOf(doji)); AddressUpgradeable.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to owner in case of emergency */ function rescueEther() public onlyOwner { uint256 currentBalance = address(this).balance; (bool sent, ) = address(msg.sender).call{value: currentBalance}(''); require(sent,"Error while transfering the eth"); } function changeBaseToken(address _baseToken) public onlyOwner { require(_baseToken != address(0)); baseToken = _baseToken; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "./FlootClaimV3P.sol"; contract Accounting721 is Ownable { event LuckyHolder(uint256 indexed luckyHolder, address indexed sender); event ChosenHolder(uint256 indexed chosenHolder, address indexed sender); FlootClaimsV3 _claimContract; struct NFTClaimInfo { address nftContract; uint256 tokenID; uint256 holder; bool claimed; } mapping (uint256 => NFTClaimInfo[]) public nftClaimInfo; constructor(){ } modifier onlyClaimContract() { // Modifier require( msg.sender == address(_claimContract), "Only Claim contract can call this." ); _; } function random721(address nftContract, uint256 tokenID) external onlyClaimContract { uint256 luckyFuck = _pickLuckyHolder(); NFTClaimInfo memory newClaim = NFTClaimInfo(nftContract, tokenID, luckyFuck, false); nftClaimInfo[luckyFuck].push(newClaim); emit LuckyHolder(luckyFuck, nftContract); } function send721(address nftContract, uint256 tokenID, uint256 chosenHolder) public { require(chosenHolder > 0 && chosenHolder <= 11111, "That Doji ID is does not exist"); ERC721(nftContract).safeTransferFrom(msg.sender,address(_claimContract),tokenID, 'true'); NFTClaimInfo memory newClaim = NFTClaimInfo(nftContract, tokenID, chosenHolder, false); nftClaimInfo[chosenHolder].push(newClaim); emit ChosenHolder(chosenHolder, nftContract); } function _pickLuckyHolder() private view returns (uint) { uint256 rando = uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, _claimContract.currentBaseTokensHolder()))); uint index = (rando % _claimContract.currentBaseTokensHolder()); uint result = IERC721Enumerable(_claimContract.baseTokenAddress()).tokenByIndex(index); return result; } function viewNFTsPending(uint id)view external returns (NFTClaimInfo[] memory) { return nftClaimInfo[id]; } function viewNFTsPendingByIndex(uint id, uint index)view external returns (NFTClaimInfo memory) { return nftClaimInfo[id][index]; } function viewNumberNFTsPending(uint id) view external returns (uint) { return nftClaimInfo[id].length; } function viewNumberNFTsPendingByAcc(address account) public view returns(uint256){ BaseToken baseToken = BaseToken(_claimContract.baseTokenAddress()); uint256[] memory userInventory = baseToken.walletInventory(account); uint256 pending; // get pending payouts for all tokenids in caller's wallet for (uint256 index = 0; index < userInventory.length; index++) { for(uint256 j = 0; j < nftClaimInfo[userInventory[index]].length; j++) { if (nftClaimInfo[userInventory[index]][j].claimed == false) { pending++; } } } return pending; } function claimNft(uint id, uint index) external onlyClaimContract { require(msg.sender == address(_claimContract)); nftClaimInfo[id][index].claimed = true; } function setClaimProxy (address proxy) public onlyOwner { _claimContract = FlootClaimsV3(payable(proxy)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.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 IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @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 pragma solidity ^0.8.0; import "../IERC1155Upgradeable.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC1155ReceiverUpgradeable.sol"; import "../../../utils/introspection/ERC165Upgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155ReceiverUpgradeable is Initializable, ERC165Upgradeable, IERC1155ReceiverUpgradeable { function __ERC1155Receiver_init() internal initializer { __ERC165_init_unchained(); __ERC1155Receiver_init_unchained(); } function __ERC1155Receiver_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC1155ReceiverUpgradeable).interfaceId || super.supportsInterface(interfaceId); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @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) private returns (bytes memory) { require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 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); } }
Converts a `uint256` to its ASCII `string` decimal representation./ Inspired by OraclizeAPI's implementation - MIT licence https:github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
function _beforeTokenTransfer( address from, address to, uint256 tokenId } pragma solidity ^0.8.0; } pragma solidity ^0.8.0; import "../IERC721.sol"; } pragma solidity ^0.8.0; function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); }
594,866
./full_match/42161/0x5bBacBb0EA1B5d450d92850cB8AB5f1AAD92C97A/sources/gist-17a8c2cf6c1a3e0ddc7d724e1e52f122/NFTEarthStaking.sol
Fetches an array of DashboardStakes for the NFW3C pool return dashboardStakes An array of DashboardStake structs/
function getNFW3CStakes(address _address) public view returns (DashboardStake[] memory) { return _getStakes(_address, NFW3C_POOL_ID); }
16,301,193