comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/** * @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes. * @param payload Payload of the initial transaction. * @param partition Name of the partition. * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. ...
function canTransfer(bytes memory payload, bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData) external returns (bytes1, bytes32, bytes32) { if(_balanceOfByPartition[from][partition] < value) { return(hex"52", "", partition); ...
0.8.10
/** * @dev Set list of token controllers. * @param operators Controller addresses. */
function _setControllers(address[] memory operators) internal { for (uint i = 0; i<_controllers.length; i++){ _isController[_controllers[i]] = false; } for (uint j = 0; j<operators.length; j++){ _isController[operators[j]] = true; } _controllers = operators; }
0.8.10
/** * @dev Set list of token partition controllers. * @param partition Name of the partition. * @param operators Controller addresses. */
function _setPartitionControllers(bytes32 partition, address[] memory operators) internal { for (uint i = 0; i<_controllersByPartition[partition].length; i++){ _isControllerByPartition[partition][_controllersByPartition[partition][i]] = false; } for (uint j = 0; j<operators.length; j++){ _i...
0.8.10
/** * @dev Set token extension contract address. * The extension contract can for example verify "ERC1400TokensValidator" or "ERC1400TokensChecker" interfaces. * If the extension is an "ERC1400TokensValidator", it will be called everytime a transfer is executed. * @param extension Address of the extension contract....
function _setTokenExtension(address extension, string memory interfaceLabel, bool removeOldExtensionRoles, bool addMinterRoleForExtension, bool addControllerRoleForExtension) internal { address oldExtension = interfaceAddr(address(this), interfaceLabel); if (oldExtension != address(0) && removeOldExtensionRole...
0.8.10
/** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _totalSupply total supply of the token. * @param _name token name e.g QASH Token. * @param _symbol token symbol e.g QASH. * @param _decimals amount of decimals. */
function LMToken(uint256 _totalSupply, string _name, string _symbol, uint8 _decimals) { balances[msg.sender] = _totalSupply; // Give the creator all initial tokens totalSupply = _totalSupply; name = _name; symbol = _symbol; decimals = _decimals; }
0.4.16
/** * @dev Get total supply of all TrueCurrency * Equal to deposit backed TrueCurrency plus debt backed TrueCurrency * @return total supply in trueCurrency */
function totalSupply() public view returns (uint256) { // if supply in opportunity finOp, return supply of deposits + debt // otherwise call super to return normal totalSupply if (opportunityRewardSupply() != 0) { return totalSupply_.add(opportunityTotalSupply()); } ...
0.5.13
/** * @dev Get balance of TrueCurrency including rewards for an address * * @param _who address of account to get balanceOf for * @return balance total balance of address including rewards */
function balanceOf(address _who) public view returns (uint256) { // if trueReward enabled, return token value of reward balance // otherwise call token balanceOf if (trueRewardEnabled(_who)) { return _toToken(rewardTokenBalance(_who, opportunity()), opportunity()); } ...
0.5.13
/** * @dev Enable TrueReward and deposit user balance into opportunity. * Currently supports a single financial opportunity */
function enableTrueReward() external { // require TrueReward is not enabled require(registry.hasAttribute(msg.sender, IS_TRUEREWARDS_WHITELISTED), "must be whitelisted to enable TrueRewards"); require(!trueRewardEnabled(msg.sender), "TrueReward already enabled"); // get sender bala...
0.5.13
/** * @dev Disable TrueReward and withdraw user balance from opportunity. */
function disableTrueReward() external { // require TrueReward is enabled require(trueRewardEnabled(msg.sender), "TrueReward already disabled"); // get balance uint rewardBalance = rewardTokenBalance(msg.sender, opportunity()); // remove reward distribution _remove...
0.5.13
/** * @dev mint function for TrueRewardBackedToken * Mints TrueCurrency backed by debt * When we add multiple opportunities, this needs to work for mutliple interfaces */
function mint(address _to, uint256 _value) public onlyOwner { // check if to address is enabled bool toEnabled = trueRewardEnabled(_to); // if to enabled, mint to this contract and deposit into finOp if (toEnabled) { // mint to this contract super.mint(add...
0.5.13
/** * @dev Transfer helper function for TrueRewardBackedToken */
function _transferAllArgs(address _from, address _to, uint256 _value) internal { // 1. Both sender and receiver are disabled // Exchange is in TrueCurrency -> call the normal transfer function if (!trueRewardEnabled(_from) && !trueRewardEnabled(_to)) { // sender not enabled recei...
0.5.13
// addListing(): add a point to the registry, including its corresponding price and owner address. // optional reserved buyer address can be included. //
function addListing(uint32 _point, uint96 _price, address _reservedBuyer) external { // intentionally using isOwner() instead of canTransfer(), which excludes third-party proxy addresses. // the exchange owner also has no ability to list anyone else's assets, it can strictly only be the point owner....
0.8.11
//<interface-functions>
function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == 0x3b3b57de //addr || interfaceID == 0x59d1d43c //text || interfaceID == 0x691f3431 //name || interfaceID == 0x01ffc9a7; //supportsInterface << [inception] }
0.8.7
//</read-functions> //--------------------------------------------------------------------------------------------// //<helper-functions>
function addressToString(address _addr) private pure returns(string memory) { bytes32 value = bytes32(uint256(uint160(_addr))); bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(51); str[0] = "0"; str[1] = "x"; for (uint i = 0; i < 20; i++) { str[2+i*2] = ...
0.8.7
/** * @dev 2. Swaps fAsset for mAsset and then deposits to Save/Savings Vault * @param _mAsset mAsset address * @param _save Save address * @param _vault Boosted Savings Vault address * @param _feeder Feeder Pool address * @param _fAsset fAsset addres...
function saveViaSwap( address _mAsset, address _save, address _vault, address _feeder, address _fAsset, uint256 _fAssetQuantity, uint256 _minOutputQuantity, bool _stake ) external { _saveViaSwap( _mAsset, _save, ...
0.8.6
/** * @dev 3. Buys a bAsset on Uniswap with ETH, then mints imAsset via mAsset, * optionally staking in the Boosted Savings Vault * @param _mAsset mAsset address * @param _save Save address * @param _vault Boosted vault address * @param _uniswap Uniswap router address * ...
function saveViaUniswapETH( address _mAsset, address _save, address _vault, address _uniswap, uint256 _amountOutMin, address[] calldata _path, uint256 _minOutMStable, bool _stake ) external payable { _saveViaUniswapETH( _mAsset, ...
0.8.6
/** * @dev Gets estimated mAsset output from a WETH > bAsset > mAsset trade * @param _mAsset mAsset address * @param _uniswap Uniswap router address * @param _ethAmount ETH amount to sell * @param _path Sell path on Uniswap (e.g. [WETH, DAI]) */
function estimate_saveViaUniswapETH( address _mAsset, address _uniswap, uint256 _ethAmount, address[] calldata _path ) external view returns (uint256 out) { require(_mAsset != address(0), "Invalid mAsset"); require(_uniswap != address(0), "Invalid uniswap"); ...
0.8.6
/** * @dev 0. Simply saves an mAsset and then into the vault * @param _mAsset mAsset address * @param _save Save address * @param _vault Boosted Savings Vault address * @param _amount Units of mAsset to deposit to savings * @param _referrer Referrer address for this deposit. */
function _saveAndStake( address _mAsset, address _save, address _vault, uint256 _amount, bool _stake, address _referrer ) internal { require(_mAsset != address(0), "Invalid mAsset"); require(_save != address(0), "Invalid save"); require(_vault ...
0.8.6
/** @dev Internal func to deposit into Save and optionally stake in the vault * @param _save Save address * @param _vault Boosted vault address * @param _amount Amount of mAsset to deposit * @param _stake Add the imAsset to the Savings Vault? * @param _referrer Referrer address for this depos...
function _depositAndStake( address _save, address _vault, uint256 _amount, bool _stake, address _referrer ) internal { if (_stake && _referrer != address(0)) { uint256 credits = ISavingsContractV3(_save).depositSavings( _amount, ...
0.8.6
/** * @dev 1. Mints an mAsset and then deposits to Save/Savings Vault * @param _mAsset mAsset address * @param _bAsset bAsset address * @param _save Save address * @param _vault Boosted Savings Vault address * @param _amount Amount of bAsset to mint with * @param _minOut Mi...
function _saveViaMint( address _mAsset, address _save, address _vault, address _bAsset, uint256 _amount, uint256 _minOut, bool _stake, address _referrer ) internal { require(_mAsset != address(0), "Invalid mAsset"); require(_save != add...
0.8.6
/** * @dev Approve mAsset and bAssets, Feeder Pools and fAssets, and Save/vault */
function approve( address _mAsset, address[] calldata _bAssets, address[] calldata _fPools, address[] calldata _fAssets, address _save, address _vault ) external onlyKeeperOrGovernor { _approve(_mAsset, _save); _approve(_save, _vault); _approve...
0.8.6
/* This function is used to transfer tokens to a particular address * @param _to receiver address where transfer is to be done * @param _value value to be transferred */
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { require(balanceOf[msg.sender] > 0); require(balanceOf[msg.sender] >= _value); // Check if the sender has enough require(_to != address(0)); ...
0.4.24
/** * This function Burns a specific amount of tokens. * @param _value The amount of token to be burned. */
function burn(uint256 _value) public onlyOwner { require(_value <= balanceOf[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; ba...
0.4.24
/** * @notice Returns royalty reciever address and royalty amount * @param _tokenId Token Id * @param _salePrice Value to calculate royalty from * @return receiver Royalty reciever address * @return amount Royalty amount */
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view override returns (address receiver, uint256 amount) { require(_tokenId > 0); receiver = this.owner(); if (_salePrice <= 100) { amount = 0; } else { ...
0.8.11
/** * @notice Calls when royalty recieved */
function onRoyaltiesReceived( address _royaltyRecipient, address _buyer, uint256 _tokenId, address _tokenPaid, uint256 _amount, bytes32 _metadata ) external returns (bytes4) { emit RoyaltiesReceived( _royaltyRecipient, _buyer,...
0.8.11
// ------------------------------------------------------------------------ // 1,000 WALL Tokens per 1 ETH // ------------------------------------------------------------------------
function () public payable { require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 1200; } else { tokens = msg.value * 1000; } balances[msg.sender] = safeAdd(balances[msg.sender], tokens); ...
0.4.18
///////////// /// @dev the inflation rate begins at 100% and decreases by 30% every year until it reaches 10% /// at 10% the rate begins to decrease by 0.5% until it reaches 1%
function adjustInflationRate() private { // Make sure adjustInflationRate cannot be called for at least another year lastInflationUpdate = now; // Decrease inflation rate by 30% each year if (inflationRate > 100) { inflationRate = inflationRate.sub(300); } // Inflati...
0.4.24
/// @dev adjusts the mint rate when the yearly inflation update is called
function adjustMintRates() internal { // Calculate new mint amount of Scale that should be created per year. poolMintAmount = totalSupply.mul(inflationRate).div(1000).mul(poolPercentage).div(100); ownerMintAmount = totalSupply.mul(inflationRate).div(1000).mul(ownerPercentage).div(100); sta...
0.4.24
/// @dev Transfer tokens from the contract to the user when unstaking /// @param _value uint256 the amount of tokens to be transferred
function transferFromContract(uint _value) internal { // Sanity check to make sure we are not transferring more than the contract has require(_value <= balances[address(this)]); // Add to the msg.sender balance balances[msg.sender] = balances[msg.sender].add(_value); // Subtract...
0.4.24
/// @dev stake function reduces the user's total available balance and adds it to their staking balance /// @param _value how many tokens a user wants to stake
function stakeScale(address _user, uint256 _value) private returns (bool success) { // You can only stake / stakeFor as many tokens as you have require(_value <= balances[msg.sender]); // Require the user is not in power down period require(stakeBalances[_user].unstakeTime == 0); ...
0.4.24
/// @dev deposit a user's initial stake plus earnings if the user unstaked at least 14 days ago
function claimStake() external returns (bool) { // Require that at least 14 days have passed (days) require(now.div(timingVariable).sub(stakeBalances[msg.sender].unstakeTime) >= 14); // Get the user's stake balance uint _userStakeBalance = stakeBalances[msg.sender].stakeBalance; ...
0.4.24
/// @dev allows users to start the reclaim process for staked tokens and stake rewards /// @return bool on success
function initUnstake() external returns (bool) { // Require that the user has not already started the unstaked process require(stakeBalances[msg.sender].unstakeTime == 0); // Require that there was some amount staked require(stakeBalances[msg.sender].stakeBalance > 0); ...
0.4.24
/// @dev set the new totalStakingHistory mapping to the current timestamp and totalScaleStaked
function setTotalStakingHistory() private { // Get now in terms of the variable staking accuracy (days in Scale's case) uint _nowAsTimingVariable = now.div(timingVariable); // Set the totalStakingHistory as a timestamp of the totalScaleStaked today totalStakingHistory[_nowAsTimingVariabl...
0.4.24
// @dev anyone can call this function that mints Scale to the pool dedicated to Scale distribution to rewards pool
function poolIssue() public { // Do not allow tokens to be minted to the pool until the pool is set require(pool != address(0)); // Make sure time has passed since last minted to pool require(now > poolTimeLastMinted); require(pool != address(0)); uint _timePa...
0.4.24
//BUY Ethminter
function EthTomining(address _addr)payable public{ uint256 amount=msg.value; uint256 usdt=amount; uint256 _udst=amount; miner storage user=miners[_addr]; require(amount>800000000000000000); if(usdt>40000000000000000000){ usdt=amount*150/100; ...
0.4.24
//BUY BEBminter
function BebTomining(uint256 _value,address _addr)public{ uint256 usdt=_value* 10 ** 18; uint256 _udst=usdt/bebethex; uint256 bebudst=usdt/bebethex; miner storage user=miners[_addr]; bebvv storage _user=bebvvs[_addr]; require(usdt>40000000000000000000000); ...
0.4.24
/// Get the full uri to get the token meta data
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(!isRevealed) { return _unrevealedUri; } string memory currentBaseURI = _baseURI(); ...
0.8.7
/// Mint a new Katana(s)
function mintToken(uint numberOfTokens) public payable { require(isSaleActive, "Sale is not active"); require((totalSupply() + numberOfTokens) <= MAX_TOKEN, "Number of tokens requested are not available"); require((mintPrice * numberOfTokens) <= msg.value, "Not enough ether value sent"); ...
0.8.7
/// Mint a new Katana(s) during presale
function premintToken(uint numberOfTokens, string calldata password) public payable { require(isSaleActive, "Sale is not active"); require(isPrivateSaleActive, "presale is not active"); require(keccak256(abi.encodePacked(password)) == premintPassword, "Premint password is not correct."); ...
0.8.7
// Inspired from CyberKongz! Thanks for everything you are doing.
function isValidBiome(uint256 _id) public pure returns(bool) { if (_id >> 96 != 0x000000000000000000000000547e4f8fcE41fE8e46dbe7554B9153Ea087311d7) return false; if (_id & 0x000000000000000000000000000000000000000000000000000000ffffffffff != 1) return false; uint256 id = (_id & 0x000000000000000000000...
0.8.0
// Helper to list all the Biomes of a wallet
function walletOfOwner(address _owner) public view returns(uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for(uint256 i; i < tokenCount; i++){ tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return t...
0.8.0
/** * Reserve for the team and giveaways */
function reserve() public onlyOwner { require(RESERVATION_COMPLETED == false, "You already reserved your tokens"); for (uint i = 0; i < RESERVE_AMOUNT; i++) { uint mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } RESERVATION_COMPLETED = true;...
0.8.0
/** * Mints NFTs */
function mintClown(uint numberOfTokens) public payable returns (uint[] memory) { require(SALE_ACTIVE, "Sale must be active to mint a Clown"); require(totalSupply().add(numberOfTokens) <= MAX_SUPPLY, "Purchase would exceed the max supply of Clownz"); require(NFT_MAIN_SALE_PRICE.mul(numberOfTok...
0.8.0
/** * Mints NTFs in presale */
function mintClownPresale(uint numberOfTokens) public payable returns (uint[] memory) { require(PRESALE_ACTIVE, "Presale must be active to mint a Clown in presale"); require(NFT_PRESALE_PRICE.mul(numberOfTokens) <= msg.value, "Ether value is not correct"); require(_whitelist[msg.sender], "You...
0.8.0
/** * @dev Retuns ids of the tokens that are owned by the given address. */
function getOwnedTokens(address owner) external view returns (uint[] memory) { uint[] memory result = new uint[](_balances[owner]); uint counter = 0; for (uint i = 0; i < _tokensMinted; i++) { if (_owners[i] == owner) { result[counter] = i; count...
0.8.0
// Minting function with signature for txn relayers
function mintWithSig( address account, uint256 id, bytes memory data, bytes memory sig, uint256 blockExpiry ) external { bytes32 message = getMintSigningHash(blockExpiry, account, id).toEthSignedMessageHash(); require(ECDSA.recover(message, sig) == signVerifier, 'Permission to call...
0.8.2
// // Construction helpers //
function getContracts(IController _controller, bytes32 _orderId) private view returns (Contracts memory) { IOrders _orders = IOrders(_controller.lookup("Orders")); IMarket _market = _orders.getMarket(_orderId); uint256 _outcome = _orders.getOutcome(_orderId); return Contracts({ ...
0.4.20
/// @notice withdraw up to all user deposited
function withdraw(address _lpToken, uint256 _amount) external override nonReentrant notPaused { require( pools[_lpToken].lastUpdatedAt > 0, "Blacksmith: pool does not exists" ); _updatePool(_lpToken); User storage user = users[...
0.8.3
/// @notice extend the current bonus program, the program has to be active (endTime is in the future)
function extendBonus( address _lpToken, uint256 _poolBonusId, address _bonusTokenAddr, uint256 _transferAmount ) external override nonReentrant notPaused { require( _isAuthorized(allowedTokenAuthorizers[_lpToken][_bonusTokenAddr]), "BonusRewards: not a...
0.8.3
/// @notice add pools and authorizers to add bonus tokens for pools, combine two calls into one. Only reason we add pools is when bonus tokens will be added
function addPoolsAndAllowBonus( address[] calldata _lpTokens, address[] calldata _bonusTokenAddrs, address[] calldata _authorizers ) external override onlyOwner notPaused { // add pools uint256 currentTime = block.timestamp; for (uint256 i = 0; i < _lpTokens.length; i...
0.8.3
/// @notice update pool's bonus per staked token till current block timestamp, do nothing if pool does not exist
function _updatePool(address _lpToken) private { Pool storage pool = pools[_lpToken]; uint256 poolLastUpdatedAt = pool.lastUpdatedAt; if (poolLastUpdatedAt == 0 || block.timestamp <= poolLastUpdatedAt) return; pool.lastUpdatedAt = block.timestamp; uint256 lpTotal = po...
0.8.3
/// @notice transfer upto what the contract has
function _safeTransfer(address _token, uint256 _amount) private returns (uint256 _transferred) { IERC20 token = IERC20(_token); uint256 balance = token.balanceOf(address(this)); if (balance > _amount) { token.safeTransfer(msg.sender, _amount); _transfe...
0.8.3
// only owner or authorized users from list
function _isAuthorized(address[] memory checkList) private view returns (bool) { if (msg.sender == owner()) return true; for (uint256 i = 0; i < checkList.length; i++) { if (msg.sender == checkList[i]) { return true; } } ...
0.8.3
/** * Transfer tokens from the caller to a new holder. * Remember, there's a 15% fee here as well. */
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase...
0.4.22
/** * @dev Mint * @param owner address to set ownership to */
function mint(address owner) external { require(minters[msg.sender] || owner == msg.sender, "This address cannot mint"); // NOTE - we don't require this so external callers don't blow up if a note already exists if(ownerTokenId[owner] == 0) { _tokenIds.increment(); uint25...
0.8.0
/** * Takes a real unit and divides by the position multiplier to return the virtual unit */
function _convertRealToVirtualUnit(int256 _realUnit) internal view returns(int256) { int256 virtualUnit = _realUnit.conservativePreciseDiv(positionMultiplier); // These checks ensure that the virtual unit does not return a result that has rounded down to 0 if (_realUnit > 0 && virtualUnit =...
0.6.10
/** * Loops through all of the positions and returns the smallest absolute value of * the virtualUnit. * * @return Min virtual unit across positions denominated as int256 */
function _getPositionsAbsMinimumVirtualUnit() internal view returns(int256) { // Additional assignment happens in the loop below uint256 minimumUnit = uint256(-1); for (uint256 i = 0; i < components.length; i++) { address component = components[i]; // A default p...
0.6.10
// to withdraw token from the contract
function transferTokenBack(address TokenAddress) external onlyOwner returns (uint256) { IERC20 Token = IERC20(TokenAddress); uint256 balance = Token.balanceOf(address(this)); if (balance > 0) { Token.safeTransfer(msg.sender, balance); } ...
0.6.12
/** * @dev Edit whitelist */
function editWhitelist(address[] calldata walletsToAdd, address[] calldata walletsToRemove) external onlyOwner { for (uint256 i = 0; i < walletsToAdd.length; i++) { isWhitelisted[walletsToAdd[i]] = true; } for (uint256 i = 0; i < walletsToRemove.length; i++) { isWhit...
0.8.7
/** * @dev Manual minting by owner, callable by owner; phase can be one of [1,2,3,4] */
function mintOwner(address[] calldata owners, uint256[] calldata counts, uint256 phase) external onlyOwner { require(owners.length == counts.length, "Bad length"); for (uint256 i = 0; i < counts.length; i++) { require(reserveForPhase[phase] >= counts[i], "Reserve exceeded"); ...
0.8.7
/** * @dev Gets the price tier from token count */
function getPrice(uint256 count) public view returns (uint256) { if (count <= 2) { return price12; } else if (count <= 4) { return price34; } else { return price56; } }
0.8.7
/** * @dev Public minting during public sale or presale */
function mint(uint256 count) public payable{ require(!mintPaused, "Minting is currently paused"); require(currentPhase > 0, "Sale not started"); require(publicSaleEnded == false, "Sale ended"); require(msg.value == count * getPrice(count), "Ether value incorrect"); require...
0.8.7
/** * @dev The function which performs the multi path swap. * @param fromToken Address of the source token * @param toToken Address of the destination token * @param fromAmount Amount of source tokens to be swapped * @param toAmount Minimum destination token amount expected out of this swap * @param expecte...
function multiSwap( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, uint256 toAmount, uint256 expectedAmount, Utils.Path[] memory path, uint256 mintPrice, address payable beneficiary, uint256 donationPercentage, string memor...
0.5.11
/** * @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) ...
0.6.6
// Returns the value of excess collateral held in this Pusd pool, compared to what is needed to maintain the global collateral ratio
function availableExcessCollatDV() public view returns (uint256) { uint256 total_supply = PUSD.totalSupply(); uint256 global_collateral_ratio = PUSD.global_collateral_ratio(); uint256 global_collat_value = PUSD.globalCollateralValue(); if (global_collateral_ratio > COLLATERAL_RATIO_PREC...
0.6.11
// We separate out the 1t1, fractional and algorithmic minting functions for gas efficiency
function mint1t1PUSD(uint256 collateral_amount, uint256 PUSD_out_min) external notMintPaused { uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); uint256 global_collateral_ratio = PUSD.global_collateral_ratio(); require(global_collateral_ratio >= COLLATERAL_RATIO_MAX,...
0.6.11
// 0% collateral-backed // function mintAlgorithmicPUSD(uint256 pegs_amount_d18, uint256 PUSD_out_min) external notMintPaused { // uint256 pegs_price = PUSD.pegs_price(); // uint256 global_collateral_ratio = PUSD.global_collateral_ratio(); // require(global_collateral_ratio == 0, "Collateral ratio must be 0...
function mintFractionalPUSD(uint256 collateral_amount, uint256 pegs_amount, uint256 PUSD_out_min) external notMintPaused { uint256 pusd_price = PUSD.pusd_price(); uint256 pegs_price = PUSD.pegs_price(); uint256 global_collateral_ratio = PUSD.global_collateral_ratio(); require(global_col...
0.6.11
// Redeem collateral. 100% collateral-backed
function redeem1t1PUSD(uint256 PUSD_amount, uint256 COLLATERAL_out_min) external notRedeemPaused { uint256 global_collateral_ratio = PUSD.global_collateral_ratio(); require(global_collateral_ratio == COLLATERAL_RATIO_MAX, "Collateral ratio must be == 1"); // // Need to adjust for decimals of co...
0.6.11
// Will fail if fully collateralized or algorithmic // Redeem PUSD for collateral and PEGS. > 0% and < 100% collateral-backed
function redeemFractionalPUSD(uint256 PUSD_amount, uint256 PEGS_out_min, uint256 COLLATERAL_out_min) external notRedeemPaused { uint256 global_collateral_ratio = PUSD.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio need...
0.6.11
// Redeem PUSD for PEGS. 0% collateral-backed // function redeemAlgorithmicPUSD(uint256 PUSD_amount, uint256 PEGS_out_min) external notRedeemPaused { // uint256 pegs_price = PUSD.pegs_price(); // uint256 global_collateral_ratio = PUSD.global_collateral_ratio(); // require(global_collateral_ratio == 0, "Coll...
function collectRedemption() external { require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "Must wait for redemption_delay blocks before collecting redemption"); bool sendPEGS = false; bool sendCollateral = false; uint PEGSAmount; uint CollateralAmount; ...
0.6.11
// When the protocol is recollateralizing, we need to give a discount of PEGS to hit the new CR target // Thus, if the target collateral ratio is higher than the actual value of collateral, minters get PEGS for adding collateral // This function simply rewards anyone that sends collateral to a pool with the same amount...
function recollateralizePUSD(uint256 collateral_amount, uint256 PEGS_out_min) external { require(recollateralizePaused == false, "Recollateralize is paused"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); uint256 pegs_price = PUSD.pegs_price(); uint256 pus...
0.6.11
// Function can be called by an PEGS holder to have the protocol buy back PEGS with excess collateral value from a desired collateral pool // This can also happen if the collateral ratio > 1
function buyBackPEGS(uint256 PEGS_amount, uint256 COLLATERAL_out_min) external { require(buyBackPaused == false, "Buyback is paused"); uint256 pegs_price = PUSD.pegs_price(); PusdPoolLibrary.BuybackPEGS_Params memory input_params = PusdPoolLibrary.BuybackPEGS_Params( availab...
0.6.11
// Combined into one function due to 24KiB contract memory limit
function setPoolParameters(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, address _bonus_address) external onlyByOwnerOrGovernance { pool_ceiling = new_ceiling; bonus_rate = new_bonus_rate; redemption_delay = new_redemption_delay; minting_fee = PUSD.minting_fe...
0.6.11
//===================== // Main gameplay //=====================
function playWar(uint sideBetPercent) public whenNotPaused TokenCheck payable { require(sideBetPercent >= 0 && sideBetPercent <= sideBetPercent_MAX); require(hasHandInProgress[msg.sender]==false); require(msg.value <= bet_MAX && msg.value >= bet_MIN); uint betAmount = msg.value; ...
0.4.24
//===================== // Special //=====================
function getCardValue(uint card) private pure returns(uint){ if (card > 416 || card < 1) { return 0; } card = card % 52; if (card == 0) { return 13; } else if (card <= 4) { return 14; } else if (card % 4 > 0) { card = card.div(4).add(1); ...
0.4.24
// @dev function to decreaseApproval to spender
function decreaseApproval (address _spender, uint256 _subtractedValue) public returns (bool success) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = safeSub(oldValue,_subtracte...
0.4.21
// msg.sender must be the user who originally created the swap. // Otherwise, the unique identifier will not match from the originally // sending txn. // // NOTE: We're aware this function can be spoofed by creating a sha256 hash of msg.sender's address // and _origTimestamp, but it's important to note refundTokensFrom...
function fundSendToDestinationGas( bytes32 _id, uint256 _origTimestamp, uint256 _amount ) external payable { require( msg.value >= minimumGasForOperation, "you must send enough gas to cover the send transaction" ); require( _id == ...
0.8.4
// This must be called AFTER fundSendToDestinationGas has been executed // for this txn to fund this send operation
function sendTokensToDestination(bytes32 _id) external returns (bytes32) { require(isActive, "this atomic swap instance is not active"); Swap storage swap = swaps[_id]; _confirmSwapExistsGasFundedAndSenderValid(swap); _token.transfer(swap.swapAddress, swap.amount); swap.currentT...
0.8.4
//transfers various amounts to the holders of the stalemate cards
function _stalemateTransfer() private{ uint payout=this.balance; //pay the pot to holders of the stalemate cards for(uint i=9;i<12;i++){ require(msg.sender != indexToAddress[i]); if(indexToAddress[i]!=address(this)){ uint proportion=(i-8)*15; ...
0.4.21
/** * @dev Validation of an incoming purchase. Use require statemens to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view { require(_beneficiary != address(0)); require(_weiAmount != 0); require(_weiAmount > minInvestment); // Revert if payment is less than 0.40 ETH require(whitelistedAddr[_beneficiary]); // Rev...
0.4.23
// collect any token send by mistake, collect target after 90 days
function collectDust(address _token) external { if (_token == address(0)) { // token address(0) = ETH payable(owner()).transfer(address(this).balance); } else { if (_token == token) { require(block.timestamp > deployedAt + 90 days, "WETHDistributor: Not ready"); } uint256 balance...
0.8.0
// Transfer control
function canTransfer(address sender, uint256 amount) public view returns (bool) { // Control is scheduled wallet if (!frozenWallets[sender].scheduled) { return true; } uint256 balance = balanceOf(sender); uint256 restAmount = getRestAmount(sender); ...
0.6.11
/// Constructor function. This is only called on contract creation.
function SEEDDEX(address admin_, address manager_, address feeAccount_, uint feeTakeMaker_, uint feeTakeSender_, uint feeTakeMakerFic_, uint feeTakeSenderFic_, address predecessor_) public { admin = admin_; manager = manager_; feeAccount = feeAccount_; feeTakeMaker = feeTakeMaker_; ...
0.4.25
/** * This function handles deposits of Ethereum based tokens to the contract. * Does not allow Ether. * If token transfer fails, transaction is reverted and remaining gas is refunded. * Emits a Deposit event. * Note: Remember to call IERC20(address).approve(this, amount) or this contract will not be able to ...
function depositToken(address token, uint amount) { //remember to call IERC20(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf. if (token == 0) throw; if (!IERC20(token).transferFrom(msg.sender, this, amount)) throw; tokens[token][msg...
0.4.25
/** * This function provides a fallback solution as outlined in ERC223. * If tokens are deposited through depositToken(), the transaction will continue. * If tokens are sent directly to this contract, the transaction is reverted. * @param sender Ethereum address of the sender of the token * @param amount amou...
function tokenFallback(address sender, uint amount, bytes data) public returns (bool ok) { if (depositingTokenFlag) { // Transfer was initiated from depositToken(). User token balance will be updated there. return true; } else { // Direct ECR223 Token.transfer in...
0.4.25
/** * Stores the active order inside of the contract. * Emits an Order event. * * * Note: tokenGet & tokenGive can be the Ethereum contract address. * @param tokenGet Ethereum contract address of the token to receive * @param amountGet uint amount of tokens being received * @param tokenGive Ethereum con...
function order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce) public { bytes32 hash = keccak256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); uint amount; orders[msg.sender][hash] = true; Order(tokenGet, amountGet,...
0.4.25
/** * Facilitates a trade from one user to another. * Requires that the transaction is signed properly, the trade isn't past its expiration, and all funds are present to fill the trade. * Calls tradeBalances(). * Updates orderFills with the amount traded. * Emits a Trade event. * Note: tokenGet & tokenGive ...
function trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) public { bytes32 hash = keccak256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); require(( (orders[u...
0.4.25
/** * This is a private function and is only being called from trade(). * Handles the movement of funds when a trade occurs. * Takes fees. * Updates token balances for both buyer and seller. * Note: tokenGet & tokenGive can be the Ethereum contract address. * Note: amount is in amountGet / tokenGet terms. ...
function tradeBalances(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private { if (tokenGet == FicAddress || tokenGive == FicAddress) { tokens[tokenGet][msg.sender] = SafeMath.sub(tokens[tokenGet][msg.sender], amount); tokens[tokenGet...
0.4.25
/** * This function is to test if a trade would go through. * Note: tokenGet & tokenGive can be the Ethereum contract address. * Note: amount is in amountGet / tokenGet terms. * @param tokenGet Ethereum contract address of the token to receive * @param amountGet uint amount of tokens being received * @param...
function testTrade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) public constant returns (bool) { if (!( tokens[tokenGet][sender] >= amount && availableVolume(tokenGet, ...
0.4.25
/** * This function checks the available volume for a given order. * Note: tokenGet & tokenGive can be the Ethereum contract address. * @param tokenGet Ethereum contract address of the token to receive * @param amountGet uint amount of tokens being received * @param tokenGive Ethereum contract address of the ...
function availableVolume(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) public constant returns (uint) { bytes32 hash = keccak256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); if (!( ...
0.4.25
/** * This function checks the amount of an order that has already been filled. * Note: tokenGet & tokenGive can be the Ethereum contract address. * @param tokenGet Ethereum contract address of the token to receive * @param amountGet uint amount of tokens being received * @param tokenGive Ethereum contract ad...
function amountFilled(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) public constant returns (uint) { bytes32 hash = keccak256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); return orderFi...
0.4.25
/** * This function cancels a given order by editing its fill data to the full amount. * Requires that the transaction is signed properly. * Updates orderFills to the full amountGet * Emits a Cancel event. * Note: tokenGet & tokenGive can be the Ethereum contract address. * @param tokenGet Ethereum contract...
function cancelOrder(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, uint8 v, bytes32 r, bytes32 s) public { bytes32 hash = keccak256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); require((orders[msg.sender][hash] || ecrecover(keccak...
0.4.25
/** * User triggered function to migrate funds into a new contract to ease updates. * Emits a FundsMigrated event. * @param newContract Contract address of the new contract we are migrating funds to * @param tokens_ Array of token addresses that we will be migrating to the new contract */
function migrateFunds(address newContract, address[] tokens_) public { require(newContract != address(0)); SEEDDEX newExchange = SEEDDEX(newContract); // Move Ether into new exchange. uint etherAmount = tokens[0][msg.sender]; if (etherAmount > 0) { tokens[...
0.4.25
/** * This function handles deposits of Ethereum based tokens into the contract, but allows specification of a user. * Does not allow Ether. * If token transfer fails, transaction is reverted and remaining gas is refunded. * Note: This is generally used in migration of funds. * Note: Remember to call Token(ad...
function depositTokenForUser(address token, uint amount, address user) public { require(token != address(0)); require(user != address(0)); require(amount > 0); depositingTokenFlag = true; if (!IERC20(token).transferFrom(msg.sender, this, amount)) throw; depositingTo...
0.4.25
/** * @dev Main sale function. Mints Pizzas */
function mintNFT(uint256 numberOfPizzas) public payable { require(hasSaleStarted, "sale hasn't started"); require( supremePizzas.totalSupply().add(numberOfPizzas) <= MAX_SUPPLY, "Exceeds MAX_SUPPLY" ); require( price.mul(numberOfPizzas) == msg.value, ...
0.7.3
/** @dev Returns the smallest integer larger than or equal to _x. @param _x number _x @return ret value ret */
function ceil(uint _x)public pure returns(uint ret){ ret = (_x / 1 ether) * 1 ether; if((_x % 1 ether) == 0){ return ret; }else{ return ret + 1 ether; } }
0.6.7
/** @dev removes tokens from an account and decreases the token supply can be called by the contract creator to destroy tokens from any account or by any holder to destroy tokens from his/her own account @param _from account to remove the amount from @param _amount amount to decrease the supply by ...
function destroy(address _from, uint256 _amount) virtual override internal { //require(msg.sender == _from || msg.sender == creator); // validate input m_balanceOf[_from] = safeSub(m_balanceOf[_from], _amount); m_totalSupply = safeSub(m_totalSupply, _amount); emit Transfer(_from,...
0.6.7
/** @dev given a token supply, connector balance, weight and a deposit amount (in the connector token), calculates the return for a given conversion (in the main token) Formula: Return = _supply * ((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1) @param _supply t...
function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256) { // validate input require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT); // special...
0.6.7
/** @dev given a token supply, connector balance, weight and a sell amount (in the main token), calculates the return for a given conversion (in the connector token) Formula: Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000))) @param _supply t...
function calculateRedeemReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256) { // validate input require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply); ...
0.6.7
// support _baseN < _baseD
function power2(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) public view returns (uint256, uint8) { if(_baseN >= _baseD) return power(_baseN, _baseD, _expN, _expD); uint256 lnBaseTimesExp = ln(_baseD, _baseN) * _expN / _expD; uint8 precision = findPositionInMaxExpA...
0.6.7