comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
// From compound's _moveDelegates // Keep track of votes. "Delegates" is a misnomer here
function trackVotes(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, "PEGS::_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, "PEGS::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } }
0.6.11
/** * repays bond token, any user can call it */
function withdraw(uint256 tokenId) external { // check if token exists require( IBondToken(_bond).hasToken(tokenId), "bond token id does not exist"); address user = _msgSender(); // get token properties ( uint256 value, /* uint256 interest */, uint256 maturity ) = IBondToken(_bond) .getTokenInfo(tokenId); address owner = IERC721(_bond).ownerOf(tokenId); bool isOwner = owner == user; if (!isOwner) { require ( IAllowList(_allowList).isAllowedAccount(user), "user is not allowed"); require( block.timestamp > maturity + _claimPeriod, "claim period is not finished yet"); } // check if enough money to repay require(IERC20(_eurxb).balanceOf(user) >= value, "not enough EURxb to withdraw"); // burn EURxb IEURxb(_eurxb).burn(user, value); if (maturity > block.timestamp) { // only if maturity has not arrived yet IEURxb(_eurxb).removeMaturity(value, maturity); } if (!isOwner) { // if not owner, need to transfer ownership first IBondToken(_bond).safeTransferFrom(owner, user, tokenId); } // burn token IBondToken(_bond).burn(tokenId); }
0.6.3
/* Private allocation functions */
function _calculatePoolMax() private { uint256[] memory poolMax = new uint256[](combinedPoolAllocation.length); for (uint256 i = 0; i < combinedPoolAllocation.length; i++) { uint256 max = 0; for (uint256 j = 0; j < combinedPoolAllocation[i].length; j++) { max += combinedPoolAllocation[i][j]; } poolMax[i] = max; } _poolMax = poolMax; }
0.6.12
/* PUBLIC ADMIN ONLY */
function withdraw() public payable override nonReentrant { require( hasRole(OWNER_ROLE, _msgSender()), "must have owner role to withdraw" ); uint256 remainder = (address(this).balance); uint256 division = remainder.div(100); for (uint8 i = 0; i < splitAddresses.length; i++) { // if at last address send the remainder if (i == splitAddresses.length - 1) { Address.sendValue(payable(splitAddresses[i]), remainder); } else { uint256 alloc = division.mul(splitPercentage[i]); Address.sendValue(payable(splitAddresses[i]), alloc); remainder -= alloc; } } }
0.6.12
/** * @notice Cannot be used for already spawned positions * @notice Token using as main collateral must be whitelisted * @notice Depositing tokens must be pre-approved to vault address * @notice position actually considered as spawned only when usdpAmount > 0 * @dev Spawns new positions * @param asset The address of token using as main collateral * @param mainAmount The amount of main collateral to deposit * @param usdpAmount The amount of USDP token to borrow **/
function spawn(address asset, uint mainAmount, uint usdpAmount) public nonReentrant { require(usdpAmount != 0, "Unit Protocol: ZERO_BORROWING"); // check whether the position is spawned require(vault.getTotalDebt(asset, msg.sender) == 0, "Unit Protocol: SPAWNED_POSITION"); // oracle availability check require(vault.vaultParameters().isOracleTypeEnabled(ORACLE_TYPE, asset), "Unit Protocol: WRONG_ORACLE_TYPE"); // USDP minting triggers the spawn of a position vault.spawn(asset, msg.sender, ORACLE_TYPE); _depositAndBorrow(asset, msg.sender, mainAmount, usdpAmount); // fire an event emit Join(asset, msg.sender, mainAmount, usdpAmount); }
0.7.6
/** * @notice Cannot be used for already spawned positions * @notice WETH must be whitelisted as collateral * @notice position actually considered as spawned only when usdpAmount > 0 * @dev Spawns new positions using ETH * @param usdpAmount The amount of USDP token to borrow **/
function spawn_Eth(uint usdpAmount) public payable nonReentrant { require(usdpAmount != 0, "Unit Protocol: ZERO_BORROWING"); // check whether the position is spawned require(vault.getTotalDebt(vault.weth(), msg.sender) == 0, "Unit Protocol: SPAWNED_POSITION"); // oracle availability check require(vault.vaultParameters().isOracleTypeEnabled(ORACLE_TYPE, vault.weth()), "Unit Protocol: WRONG_ORACLE_TYPE"); // USDP minting triggers the spawn of a position vault.spawn(vault.weth(), msg.sender, ORACLE_TYPE); _depositAndBorrow_Eth(msg.sender, usdpAmount); // fire an event emit Join(vault.weth(), msg.sender, msg.value, usdpAmount); }
0.7.6
/** * @notice Position should be spawned (USDP borrowed from position) to call this method * @notice Depositing tokens must be pre-approved to vault address * @notice Token using as main collateral must be whitelisted * @dev Deposits collaterals and borrows USDP to spawned positions simultaneously * @param asset The address of token using as main collateral * @param mainAmount The amount of main collateral to deposit * @param usdpAmount The amount of USDP token to borrow **/
function depositAndBorrow( address asset, uint mainAmount, uint usdpAmount ) public spawned(asset, msg.sender) nonReentrant { require(usdpAmount != 0, "Unit Protocol: ZERO_BORROWING"); _depositAndBorrow(asset, msg.sender, mainAmount, usdpAmount); // fire an event emit Join(asset, msg.sender, mainAmount, usdpAmount); }
0.7.6
/** * @notice Tx sender must have a sufficient USDP balance to pay the debt * @dev Withdraws collateral and repays specified amount of debt simultaneously * @param asset The address of token using as main collateral * @param mainAmount The amount of main collateral token to withdraw * @param usdpAmount The amount of USDP token to repay **/
function withdrawAndRepay( address asset, uint mainAmount, uint usdpAmount ) public spawned(asset, msg.sender) nonReentrant { // check usefulness of tx require(mainAmount != 0, "Unit Protocol: USELESS_TX"); uint debt = vault.debts(asset, msg.sender); require(debt != 0 && usdpAmount != debt, "Unit Protocol: USE_REPAY_ALL_INSTEAD"); if (mainAmount != 0) { // withdraw main collateral to the user address vault.withdrawMain(asset, msg.sender, mainAmount); } if (usdpAmount != 0) { uint fee = vault.calculateFee(asset, msg.sender, usdpAmount); vault.chargeFee(vault.usdp(), msg.sender, fee); vault.repay(asset, msg.sender, usdpAmount); } vault.update(asset, msg.sender); _ensurePositionCollateralization(asset, msg.sender); // fire an event emit Exit(asset, msg.sender, mainAmount, usdpAmount); }
0.7.6
/** * @notice Tx sender must have a sufficient USDP balance to pay the debt * @dev Withdraws collateral and repays specified amount of debt simultaneously converting WETH to ETH * @param ethAmount The amount of ETH to withdraw * @param usdpAmount The amount of USDP token to repay **/
function withdrawAndRepay_Eth( uint ethAmount, uint usdpAmount ) public spawned(vault.weth(), msg.sender) nonReentrant { // check usefulness of tx require(ethAmount != 0, "Unit Protocol: USELESS_TX"); uint debt = vault.debts(vault.weth(), msg.sender); require(debt != 0 && usdpAmount != debt, "Unit Protocol: USE_REPAY_ALL_INSTEAD"); if (ethAmount != 0) { // withdraw main collateral to the user address vault.withdrawEth(msg.sender, ethAmount); } if (usdpAmount != 0) { uint fee = vault.calculateFee(vault.weth(), msg.sender, usdpAmount); vault.chargeFee(vault.usdp(), msg.sender, fee); vault.repay(vault.weth(), msg.sender, usdpAmount); } vault.update(vault.weth(), msg.sender); _ensurePositionCollateralization_Eth(msg.sender); // fire an event emit Exit(vault.weth(), msg.sender, ethAmount, usdpAmount); }
0.7.6
// ensures that borrowed value is in desired range
function _ensureCollateralization( address asset, address user, uint mainUsdValue_q112 ) internal view { // USD limit of the position uint usdLimit = mainUsdValue_q112 * vaultManagerParameters.initialCollateralRatio(asset) / Q112 / 100; // revert if collateralization is not enough require(vault.getTotalDebt(asset, user) <= usdLimit, "Unit Protocol: UNDERCOLLATERALIZED"); }
0.7.6
/// WALK THE PLANK ///
function walkPlank() external whenNotPaused nonReentrant { require(tx.origin == msg.sender, "Only EOA"); require(_pendingPlankCommitId[msg.sender] == 0, "Already have pending mints"); uint16 totalPirats = uint16(potm.getTotalPirats()); uint16 totalPending = pendingMintAmt + pendingPlankAmt; uint256 maxTokens = potm.maxTokens(); require(totalPirats + totalPending + 1 <= maxTokens, "All tokens minted"); uint256 totalBootyCost = 0; for (uint i = 1; i <= 1; i++) { totalBootyCost += plankCost(totalPirats + totalPending + i); } if (totalBootyCost > 0) { booty.burnExternal(msg.sender, totalBootyCost); } _plankCommitId += 1; uint16 commitId = _plankCommitId; _plankCommits[msg.sender][commitId] = PlankCommit(1); _pendingPlankCommitId[msg.sender] = commitId; pendingPlankAmt += 1; uint256 randomNumber = _rand(commitId); commitIdToRandomNumber[commitId] = randomNumber; commitTimeStamp[msg.sender] = block.timestamp; emit PlankCommitted(msg.sender, 1); }
0.8.7
/// For creating Rich Token
function _createRich(string _name, address _owner, uint256 _price) private { Rich memory _richtoken = Rich({ name: _name }); uint256 newRichId = richtokens.push(_richtoken) - 1; // It's probably never going to happen, 4 billion tokens are A LOT, but // let's just be 100% sure we never let this happen. require(newRichId == uint256(uint32(newRichId))); Birth(newRichId, _name, _owner); richtokenIndexToPrice[newRichId] = _price; // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), _owner, newRichId); }
0.4.18
/** * @dev Updates parameters of the position to the current ones * @param asset The address of the main collateral token * @param user The owner of a position **/
function update(address asset, address user) public hasVaultAccess notLiquidating(asset, user) { // calculate fee using stored stability fee uint debtWithFee = getTotalDebt(asset, user); tokenDebts[asset] = tokenDebts[asset].sub(debts[asset][user]).add(debtWithFee); debts[asset][user] = debtWithFee; stabilityFee[asset][user] = vaultParameters.stabilityFee(asset); liquidationFee[asset][user] = vaultParameters.liquidationFee(asset); lastUpdate[asset][user] = block.timestamp; }
0.7.6
/** * @dev Increases position's debt and mints USDP token * @param asset The address of the main collateral token * @param user The address of a position's owner * @param amount The amount of USDP to borrow **/
function borrow( address asset, address user, uint amount ) external hasVaultAccess notLiquidating(asset, user) returns(uint) { require(vaultParameters.isOracleTypeEnabled(oracleType[asset][user], asset), "Unit Protocol: WRONG_ORACLE_TYPE"); update(asset, user); debts[asset][user] = debts[asset][user].add(amount); tokenDebts[asset] = tokenDebts[asset].add(amount); // check USDP limit for token require(tokenDebts[asset] <= vaultParameters.tokenDebtLimit(asset), "Unit Protocol: ASSET_DEBT_LIMIT"); USDP(usdp).mint(user, amount); return debts[asset][user]; }
0.7.6
/** * @dev Deletes position and transfers collateral to liquidation system * @param asset The address of the main collateral token * @param positionOwner The address of a position's owner * @param initialPrice The starting price of collateral in USDP **/
function triggerLiquidation( address asset, address positionOwner, uint initialPrice ) external hasVaultAccess notLiquidating(asset, positionOwner) { // reverts if oracle type is disabled require(vaultParameters.isOracleTypeEnabled(oracleType[asset][positionOwner], asset), "Unit Protocol: WRONG_ORACLE_TYPE"); // fix the debt debts[asset][positionOwner] = getTotalDebt(asset, positionOwner); liquidationBlock[asset][positionOwner] = block.number; liquidationPrice[asset][positionOwner] = initialPrice; }
0.7.6
// Functions // Transaction overview: // 1. User approves transfer of token to AtomicSwap contract (triggered by the frontend) // 2. User calls AtomicSwap.swapExactTokensAndMint() (triggered by the frontend) // 2.1 AtomicSwap transfers token from user to itself (internal tx) // 2.2 AtomicSwap approves IUniswapV2Router02 (internal tx) // 2.3 AtomicSwap calls IUniswapV2Router02.swapExactTokensForTokens() to exchange token for collateral (internal tx) // 2.4 AtomicSwap approves SynthereumPool (internal tx) // 2.5 AtomicSwap calls SynthereumPool.mint() to mint synth with collateral (internal tx)
function swapExactTokensAndMint( uint256 tokenAmountIn, uint256 collateralAmountOut, address[] calldata tokenSwapPath, ISynthereumPoolOnChainPriceFeed synthereumPool, ISynthereumPoolOnChainPriceFeed.MintParams memory mintParams ) public returns ( uint256 collateralOut, IERC20 synthToken, uint256 syntheticTokensMinted ) { IERC20 collateralInstance = checkPoolRegistration(synthereumPool); uint256 numberOfSwapTokens = tokenSwapPath.length - 1; require( address(collateralInstance) == tokenSwapPath[numberOfSwapTokens], 'Wrong collateral instance' ); synthToken = synthereumPool.syntheticToken(); IERC20 inputTokenInstance = IERC20(tokenSwapPath[0]); inputTokenInstance.safeTransferFrom( msg.sender, address(this), tokenAmountIn ); inputTokenInstance.safeApprove(address(uniswapRouter), tokenAmountIn); collateralOut = uniswapRouter.swapExactTokensForTokens( tokenAmountIn, collateralAmountOut, tokenSwapPath, address(this), mintParams.expiration )[numberOfSwapTokens]; collateralInstance.safeApprove(address(synthereumPool), collateralOut); mintParams.collateralAmount = collateralOut; (syntheticTokensMinted, ) = synthereumPool.mint(mintParams); emit Swap( address(inputTokenInstance), tokenAmountIn, address(synthToken), syntheticTokensMinted ); }
0.6.12
// Transaction overview: // 1. User approves transfer of token to AtomicSwap contract (triggered by the frontend) // 2. User calls AtomicSwap.swapTokensForExactAndMint() (triggered by the frontend) // 2.1 AtomicSwap transfers token from user to itself (internal tx) // 2.2 AtomicSwap approves IUniswapV2Router02 (internal tx) // 2.3 AtomicSwap checks the return amounts of the swapTokensForExactTokens() function and saves the leftover of the inputTokenAmount in a variable // 2.4 AtomicSwap calls IUniswapV2Router02.swapTokensForExactTokens() to exchange token for collateral (internal tx) // 2.5 AtomicSwap approves SynthereumPool (internal tx) // 2.6 AtomicSwap calls SynthereumPool.mint() to mint synth with collateral (internal tx) // 2.7 AtomicSwap transfers the remaining input tokens to the user
function swapTokensForExactAndMint( uint256 tokenAmountIn, uint256 collateralAmountOut, address[] calldata tokenSwapPath, ISynthereumPoolOnChainPriceFeed synthereumPool, ISynthereumPoolOnChainPriceFeed.MintParams memory mintParams ) public returns ( uint256 collateralOut, IERC20 synthToken, uint256 syntheticTokensMinted ) { IERC20 collateralInstance = checkPoolRegistration(synthereumPool); uint256 numberOfSwapTokens = tokenSwapPath.length - 1; require( address(collateralInstance) == tokenSwapPath[numberOfSwapTokens], 'Wrong collateral instance' ); synthToken = synthereumPool.syntheticToken(); IERC20 inputTokenInstance = IERC20(tokenSwapPath[0]); inputTokenInstance.safeTransferFrom( msg.sender, address(this), tokenAmountIn ); uint256[2] memory amounts = _getNeededAmountAndLeftover( collateralAmountOut, tokenSwapPath, tokenAmountIn ); inputTokenInstance.safeApprove(address(uniswapRouter), amounts[0]); collateralOut = uniswapRouter.swapTokensForExactTokens( collateralAmountOut, amounts[0], tokenSwapPath, address(this), mintParams.expiration )[numberOfSwapTokens]; collateralInstance.safeApprove(address(synthereumPool), collateralOut); mintParams.collateralAmount = collateralOut; (syntheticTokensMinted, ) = synthereumPool.mint(mintParams); if (amounts[1] != 0) { inputTokenInstance.safeTransfer(mintParams.recipient, amounts[1]); } emit Swap( address(inputTokenInstance), tokenAmountIn, address(synthToken), syntheticTokensMinted ); }
0.6.12
// Transaction overview: // 1. User approves transfer of synth to `AtomicSwap` contract (triggered by the frontend) // 2. User calls `AtomicSwap.redeemAndSwapExactTokens()` (triggered by the frontend) // 2.1 `AtomicSwaps` transfers synth from user to itself (internal tx) // 2.2 `AtomicSwaps` approves transfer of synth from itself to pool (internal tx) // 2.3 `AtomicSwap` calls `pool.redeem()` to redeem synth for collateral (internal tx) // 2.4 `AtomicSwap` approves transfer of collateral to `IUniswapV2Router02` (internal tx) // 2.7 `AtomicSwap` calls `IUniswapV2Router02.swapExactTokensForTokens` to swap collateral for token (internal tx)
function redeemAndSwapExactTokens( uint256 amountTokenOut, address[] calldata tokenSwapPath, ISynthereumPoolOnChainPriceFeed synthereumPool, ISynthereumPoolOnChainPriceFeed.RedeemParams memory redeemParams, address recipient ) public returns ( uint256 collateralRedeemed, IERC20 outputToken, uint256 outputTokenAmount ) { IERC20 collateralInstance = checkPoolRegistration(synthereumPool); require( address(collateralInstance) == tokenSwapPath[0], 'Wrong collateral instance' ); IERC20 synthToken = synthereumPool.syntheticToken(); outputToken = IERC20(tokenSwapPath[tokenSwapPath.length - 1]); uint256 numTokens = redeemParams.numTokens; synthToken.safeTransferFrom(msg.sender, address(this), numTokens); synthToken.safeApprove(address(synthereumPool), numTokens); redeemParams.recipient = address(this); (collateralRedeemed, ) = synthereumPool.redeem(redeemParams); collateralInstance.safeApprove(address(uniswapRouter), collateralRedeemed); outputTokenAmount = uniswapRouter.swapExactTokensForTokens( collateralRedeemed, amountTokenOut, tokenSwapPath, recipient, redeemParams.expiration )[tokenSwapPath.length - 1]; emit Swap( address(synthToken), numTokens, address(outputToken), outputTokenAmount ); }
0.6.12
// Transaction overview: // 1. User approves transfer of synth to `AtomicSwap` contract (triggered by the frontend) // 2. User calls `AtomicSwap.redeemAndSwapTokensForExact()` (triggered by the frontend) // 2.1 `AtomicSwaps` transfers synth from user to itself (internal tx) // 2.2 `AtomicSwaps` approves transfer of synth from itself to pool (internal tx) // 2.3 `AtomicSwap` calls `pool.redeem()` to redeem synth for collateral (internal tx) // 2.4 `AtomicSwap` approves transfer of collateral to `IUniswapV2Router02` (internal tx) // 2.5 AtomicSwap checks the return amounts from the swapTokensForExactTokens() function and saves the leftover of inputTokens in a variable // 2.6 `AtomicSwap` calls `IUniswapV2Router02.swapTokensForExactTokens` to swap collateral for token (internal tx) // 2.7 AtomicSwap transfers the leftover amount to the user if there is any
function redeemAndSwapTokensForExact( uint256 amountTokenOut, address[] calldata tokenSwapPath, ISynthereumPoolOnChainPriceFeed synthereumPool, ISynthereumPoolOnChainPriceFeed.RedeemParams memory redeemParams, address recipient ) public returns ( uint256 collateralRedeemed, IERC20 outputToken, uint256 outputTokenAmount ) { IERC20 collateralInstance = checkPoolRegistration(synthereumPool); require( address(collateralInstance) == tokenSwapPath[0], 'Wrong collateral instance' ); IERC20 synthToken = synthereumPool.syntheticToken(); outputToken = IERC20(tokenSwapPath[tokenSwapPath.length - 1]); uint256 numTokens = redeemParams.numTokens; synthToken.safeTransferFrom(msg.sender, address(this), numTokens); synthToken.safeApprove(address(synthereumPool), numTokens); redeemParams.recipient = address(this); (collateralRedeemed, ) = synthereumPool.redeem(redeemParams); uint256[2] memory amounts = _getNeededAmountAndLeftover( amountTokenOut, tokenSwapPath, collateralRedeemed ); collateralInstance.safeApprove(address(uniswapRouter), amounts[0]); outputTokenAmount = uniswapRouter.swapTokensForExactTokens( amountTokenOut, amounts[0], tokenSwapPath, recipient, redeemParams.expiration )[tokenSwapPath.length - 1]; if (amounts[1] != 0) { collateralInstance.safeTransfer(recipient, amounts[1]); } emit Swap( address(synthToken), numTokens, address(outputToken), outputTokenAmount ); }
0.6.12
// ------------------------------------------------------------------------ // 100000 FWD Tokens per 1 ETH // ------------------------------------------------------------------------
function () public payable { require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 10000000000; } else { tokens = msg.value * 100000; } balances[msg.sender] = safeAdd(balances[msg.sender], tokens); _totalSupply = safeAdd(_totalSupply, tokens); Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value); }
0.4.26
// Transaction overview: // 1. User calls AtomicSwap.swapExactETHAndMint() sending Ether (triggered by the frontend) // 1.1 AtomicSwap calls IUniswapV2Router02.swapExactETHForTokens() to exchange ETH for collateral (internal tx) // 1.2 AtomicSwap approves SynthereumPool (internal tx) // 1.3 AtomicSwap calls SynthereumPool.mint() to mint synth with collateral (internal tx)
function swapExactETHAndMint( uint256 collateralAmountOut, address[] calldata tokenSwapPath, ISynthereumPoolOnChainPriceFeed synthereumPool, ISynthereumPoolOnChainPriceFeed.MintParams memory mintParams ) public payable returns ( uint256 collateralOut, IERC20 synthToken, uint256 syntheticTokensMinted ) { IERC20 collateralInstance = checkPoolRegistration(synthereumPool); uint256 numberOfSwapTokens = tokenSwapPath.length - 1; require( address(collateralInstance) == tokenSwapPath[numberOfSwapTokens], 'Wrong collateral instance' ); synthToken = synthereumPool.syntheticToken(); collateralOut = uniswapRouter.swapExactETHForTokens{value: msg.value}( collateralAmountOut, tokenSwapPath, address(this), mintParams.expiration )[numberOfSwapTokens]; collateralInstance.safeApprove(address(synthereumPool), collateralOut); mintParams.collateralAmount = collateralOut; (syntheticTokensMinted, ) = synthereumPool.mint(mintParams); emit Swap( address(0), msg.value, address(synthToken), syntheticTokensMinted ); }
0.6.12
// Transaction overview: // 1. User calls AtomicSwap.swapETHForExactAndMint() sending Ether (triggered by the frontend) // 1.1 AtomicSwap checks the return amounts from the IUniswapV2Router02.swapETHForExactTokens() // 1.2 AtomicSwap saves the leftover ETH that won't be used in a variable // 1.3 AtomicSwap calls IUniswapV2Router02.swapETHForExactTokens() to exchange ETH for collateral (internal tx) // 1.4 AtomicSwap approves SynthereumPool (internal tx) // 1.5 AtomicSwap calls SynthereumPool.mint() to mint synth with collateral (internal tx) // 1.6 AtomicSwap transfers the remaining ETH from the transactions to the user
function swapETHForExactAndMint( uint256 collateralAmountOut, address[] calldata tokenSwapPath, ISynthereumPoolOnChainPriceFeed synthereumPool, ISynthereumPoolOnChainPriceFeed.MintParams memory mintParams ) public payable returns ( uint256 collateralOut, IERC20 synthToken, uint256 syntheticTokensMinted ) { IERC20 collateralInstance = checkPoolRegistration(synthereumPool); uint256 numberOfSwapTokens = tokenSwapPath.length - 1; require( address(collateralInstance) == tokenSwapPath[numberOfSwapTokens], 'Wrong collateral instance' ); synthToken = synthereumPool.syntheticToken(); collateralOut = uniswapRouter.swapETHForExactTokens{value: msg.value}( collateralAmountOut, tokenSwapPath, address(this), mintParams.expiration )[numberOfSwapTokens]; collateralInstance.safeApprove(address(synthereumPool), collateralOut); mintParams.collateralAmount = collateralOut; (syntheticTokensMinted, ) = synthereumPool.mint(mintParams); if (address(this).balance != 0) { msg.sender.transfer(address(this).balance); } emit Swap( address(0), msg.value, address(synthToken), syntheticTokensMinted ); }
0.6.12
// Transaction overview: // 1. User approves transfer of synth to `AtomicSwap` contract (triggered by the frontend) // 2. User calls `AtomicSwap.redeemAndSwapExactTokensForETH()` (triggered by the frontend) // 2.1 `AtomicSwaps` transfers synth from user to itself (internal tx) // 2.2 `AtomicSwaps` approves transfer of synth from itself to pool (internal tx) // 2.3 `AtomicSwap` calls `pool.redeem()` to redeem synth for collateral (internal tx) // 2.4 `AtomicSwap` approves transfer of collateral to `IUniswapV2Router02` (internal tx) // 2.5 `AtomicSwap` calls `IUniswapV2Router02.swapExactTokensForETH` to swap collateral for ETH (internal tx)
function redeemAndSwapExactTokensForETH( uint256 amountTokenOut, address[] calldata tokenSwapPath, ISynthereumPoolOnChainPriceFeed synthereumPool, ISynthereumPoolOnChainPriceFeed.RedeemParams memory redeemParams, address recipient ) public returns ( uint256 collateralRedeemed, IERC20 outputToken, uint256 outputTokenAmount ) { IERC20 collateralInstance = checkPoolRegistration(synthereumPool); require( address(collateralInstance) == tokenSwapPath[0], 'Wrong collateral instance' ); IERC20 synthToken = synthereumPool.syntheticToken(); uint256 numTokens = redeemParams.numTokens; synthToken.safeTransferFrom(msg.sender, address(this), numTokens); synthToken.safeApprove(address(synthereumPool), numTokens); redeemParams.recipient = address(this); (collateralRedeemed, ) = synthereumPool.redeem(redeemParams); collateralInstance.safeApprove(address(uniswapRouter), collateralRedeemed); outputTokenAmount = uniswapRouter.swapExactTokensForETH( collateralRedeemed, amountTokenOut, tokenSwapPath, recipient, redeemParams.expiration )[tokenSwapPath.length - 1]; emit Swap( address(synthToken), numTokens, address(outputToken), outputTokenAmount ); }
0.6.12
// Transaction overview: // 1. User approves transfer of synth to `AtomicSwap` contract (triggered by the frontend) // 2. User calls `AtomicSwap.redeemAndSwapTokensForExactETH()` (triggered by the frontend) // 2.1 `AtomicSwaps` transfers synth from user to itself (internal tx) // 2.2 `AtomicSwaps` approves transfer of synth from itself to pool (internal tx) // 2.3 `AtomicSwap` calls `pool.redeem()` to redeem synth for collateral (internal tx) // 2.4 `AtomicSwap` approves transfer of collateral to `IUniswapV2Router02` (internal tx) // 2.5 AtomicSwap checks what would be the leftover of tokens after the swap and saves it in a variable // 2.6 `AtomicSwap` calls `IUniswapV2Router02.swapTokensForExactETH` to swap collateral for ETH (internal tx) // 2.7 AtomicSwap transfers the leftover tokens to the user if there are any
function redeemAndSwapTokensForExactETH( uint256 amountTokenOut, address[] calldata tokenSwapPath, ISynthereumPoolOnChainPriceFeed synthereumPool, ISynthereumPoolOnChainPriceFeed.RedeemParams memory redeemParams, address recipient ) public returns ( uint256 collateralRedeemed, IERC20 outputToken, uint256 outputTokenAmount ) { IERC20 collateralInstance = checkPoolRegistration(synthereumPool); require( address(collateralInstance) == tokenSwapPath[0], 'Wrong collateral instance' ); IERC20 synthToken = synthereumPool.syntheticToken(); uint256 numTokens = redeemParams.numTokens; synthToken.safeTransferFrom(msg.sender, address(this), numTokens); synthToken.safeApprove(address(synthereumPool), numTokens); redeemParams.recipient = address(this); (collateralRedeemed, ) = synthereumPool.redeem(redeemParams); uint256[2] memory amounts = _getNeededAmountAndLeftover( amountTokenOut, tokenSwapPath, collateralRedeemed ); collateralInstance.safeApprove(address(uniswapRouter), amounts[0]); outputTokenAmount = uniswapRouter.swapTokensForExactETH( amountTokenOut, amounts[0], tokenSwapPath, recipient, redeemParams.expiration )[tokenSwapPath.length - 1]; if (amounts[1] != 0) { collateralInstance.safeTransfer(recipient, amounts[1]); } emit Swap( address(synthToken), numTokens, address(outputToken), outputTokenAmount ); }
0.6.12
// Checks if a pool is registered with the SynthereumRegistry
function checkPoolRegistration(ISynthereumPoolOnChainPriceFeed synthereumPool) internal view returns (IERC20 collateralInstance) { ISynthereumRegistry poolRegistry = ISynthereumRegistry( synthereumFinder.getImplementationAddress( SynthereumInterfaces.PoolRegistry ) ); string memory synthTokenSymbol = synthereumPool.syntheticTokenSymbol(); collateralInstance = synthereumPool.collateralToken(); uint8 version = synthereumPool.version(); require( poolRegistry.isDeployed( synthTokenSymbol, collateralInstance, version, address(synthereumPool) ), 'Pool not registred' ); }
0.6.12
/** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */
function requestRandomness( bytes32 _keyHash, uint256 _fee ) internal returns ( bytes32 requestId ) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); }
0.8.7
// Sends all avaibile balances and creates LP tokens // Possible ways this could break addressed // 1) Multiple calls and resetting amounts - addressed with boolean // 2) Failed WETH wrapping/unwrapping addressed with checks // 3) Failure to create LP tokens, addressed with checks // 4) Unacceptable division errors . Addressed with multiplications by 1e18 // 5) Pair not set - impossible since its set in constructor
function addLiquidityToUniswapPxWETHPair() public { require(liquidityGenerationOngoing() == false, "Liquidity generation onging"); require(LPGenerationCompleted == false, "Liquidity generation already finished"); totalETHContributed = address(this).balance; IUniswapV2Pair pair = IUniswapV2Pair(tokenUniswapPair); Console.log("Balance of this", totalETHContributed / 1e18); //Wrap eth address WETH = uniswapRouterV2.WETH(); IWETH(WETH).deposit{value : totalETHContributed}(); require(address(this).balance == 0 , "Transfer Failed"); IWETH(WETH).transfer(address(pair),totalETHContributed); emit Transfer(address(this), address(pair), _balances[address(this)]); _balances[address(pair)] = _balances[address(this)]; _balances[address(this)] = 0; pair.mint(address(this)); totalLPTokensCreated = pair.balanceOf(address(this)); Console.log("Total tokens created",totalLPTokensCreated); require(totalLPTokensCreated != 0 , "LP creation failed"); LPperETHUnit = totalLPTokensCreated.mul(1e18).div(totalETHContributed); // 1e18x for change Console.log("Total per LP token", LPperETHUnit); require(LPperETHUnit != 0 , "LP creation failed"); LPGenerationCompleted = true; }
0.6.12
// Possible ways this could break addressed // 1) No ageement to terms - added require // 2) Adding liquidity after generaion is over - added require // 3) Overflow from uint - impossible there isnt that much ETH aviable // 4) Depositing 0 - not an issue it will just add 0 to tally
function addLiquidity(bool IreadParticipationAgreementInReadSectionAndIagreeFalseOrTrue) public payable { require(liquidityGenerationOngoing(), "Liquidity Generation Event over"); require(IreadParticipationAgreementInReadSectionAndIagreeFalseOrTrue, "No agreement provided"); ethContributed[msg.sender] += msg.value; // Overflow protection from safemath is not neded here totalETHContributed = totalETHContributed.add(msg.value); // for front end display during LGE. This resets with definietly correct balance while calling pair. emit LiquidityAddition(msg.sender, msg.value); }
0.6.12
// Possible ways this could break addressed // 1) Accessing before event is over and resetting eth contributed -- added require // 2) No uniswap pair - impossible at this moment because of the LPGenerationCompleted bool // 3) LP per unit is 0 - impossible checked at generation function
function claimLPTokens() public { require(LPGenerationCompleted, "Event not over yet"); require(ethContributed[msg.sender] > 0 , "Nothing to claim, move along"); IUniswapV2Pair pair = IUniswapV2Pair(tokenUniswapPair); uint256 amountLPToTransfer = ethContributed[msg.sender].mul(LPperETHUnit).div(1e18); pair.transfer(msg.sender, amountLPToTransfer); // stored as 1e18x value for change ethContributed[msg.sender] = 0; emit LPTokenClaimed(msg.sender, amountLPToTransfer); }
0.6.12
// CHECK WHICH SERIES 2 ID CAN BE CLAIMED WITH SERIES 0 OR SERIES 1 TOKENS
function series2_token(CollectionToClaim _collection, uint256[] memory tokenIds) public view returns(uint256[] memory) { require(mintStartIndexDrawn); uint256[] memory ids = new uint256[](tokenIds.length); if (_collection == CollectionToClaim.Series0) { for(uint i = 0; i<tokenIds.length;i++) { uint tokenId = tokenIds[i]; require(tokenId < 18); require(tokenId > 0); ids[i] = (tokenId + Series0start + mintStartIndex) % Series2total; } } else if (_collection == CollectionToClaim.Series1) { for(uint i = 0; i<tokenIds.length;i++) { uint tokenId = tokenIds[i]; require(tokenId < 221); require(tokenId > 0); ids[i] = (tokenId + Series1start + mintStartIndex) % Series2total; } } else { revert(); } return ids; }
0.8.7
// CHECK IF SERIES 2 TOKEN IS CLAIMED
function check_claim(CollectionToClaim _collection, uint256[] memory tokenIds) public view returns(bool[] memory) { uint256[] memory ids = series2_token(_collection, tokenIds); bool[] memory isit = new bool[](tokenIds.length); for(uint i = 0; i<tokenIds.length;i++) { isit[i] = _exists(ids[i]); } return isit; }
0.8.7
// MINT THEM
function mint_series2(CollectionToClaim _collection, uint256[] memory tokenIds) public { require(claimRunning && mintStartIndexDrawn); require(tokenIds.length > 0 && tokenIds.length <= 15); if (_collection == CollectionToClaim.Series0) { for(uint i = 0; i<tokenIds.length;i++) { uint tokenId = tokenIds[i]; require(tokenId < 18); require(tokenId > 0); require(ClaimFromERC721(Series0Address).ownerOf(tokenId) == msg.sender); uint Series2idBeingMinted = (tokenId + Series0start + mintStartIndex) % Series2total; _safeMint(msg.sender, Series2idBeingMinted); emit Series2Claimed(_collection, tokenId, Series2idBeingMinted, msg.sender); } } else if (_collection == CollectionToClaim.Series1) { for(uint i = 0; i<tokenIds.length;i++) { uint tokenId = tokenIds[i]; require(tokenId < 221); require(tokenId > 0); require(ClaimFromERC721(Series1Address).ownerOf(tokenId) == msg.sender); uint Series2idBeingMinted = (tokenId + Series1start + mintStartIndex) % Series2total; _safeMint(msg.sender, Series2idBeingMinted); emit Series2Claimed(_collection, tokenId, Series2idBeingMinted, msg.sender); } } else { revert(); } }
0.8.7
/** * @notice Determine winner by tallying votes */
function _determineWinner(uint256 counter) internal view returns (uint256) { uint256 winner = currentAxonsNumbersForVotes[counter][0]; uint256 highestVoteCount = 0; for (uint i=0; i<10; i++) { uint256 currentAxonNumber = currentAxonsNumbersForVotes[counter][i]; uint256 currentVotesCount = currentVotesForAxonNumbers[counter][i]; if (currentVotesCount > highestVoteCount) { winner = currentAxonNumber; highestVoteCount = currentVotesCount; } } return winner; }
0.8.10
/** * @dev Subtracts two signed integers, reverts on overflow. */
function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; }
0.4.24
/** * @dev Adds two signed integers, reverts on overflow. */
function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; }
0.4.24
// Minting reserved tokens to the treasury wallet
function mintReserved(uint256 _mintAmount) external onlyOwner { require(_mintAmount > 0, "amount to mint should be a positive number"); require( reservedMinted + _mintAmount <= WT_MAX_RESERVED_COUNT, "cannot mint the amount requested" ); uint256 supply = currentIndex; require( supply + _mintAmount <= WT_TOTAL_SUPPLY, "the collection is sold out" ); _mint(WALLET_TREASURY, _mintAmount, "", false); }
0.8.4
// ------------------------------------------ // ASSETS ACCESS MANAGEMENT
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return notRevealedUri; } uint256 assetIndex = tokenId + 1; string memory currentBaseURI = baseURI; return bytes(currentBaseURI).length > 0 ? string( abi.encodePacked( currentBaseURI, assetIndex.toString(), baseExtension ) ) : ""; }
0.8.4
/// Convert from a pixel's x, y coordinates to its section index /// This is a helper function
function getSectionIndexFromRaw( uint _x, uint _y ) returns (uint) { if (_x >= mapWidth) throw; if (_y >= mapHeight) throw; // Convert raw x, y to section identifer x y _x = _x / 10; _y = _y / 10; //Get section_identifier from coords return _x + (_y * 100); }
0.4.11
/// Get Section index based on its upper left x,y coordinates or "identifier" /// coordinates /// This is a helper function
function getSectionIndexFromIdentifier ( uint _x_section_identifier, uint _y_section_identifier ) returns (uint) { if (_x_section_identifier >= (mapWidth / 10)) throw; if (_y_section_identifier >= (mapHeight / 10)) throw; uint index = _x_section_identifier + (_y_section_identifier * 100); return index; }
0.4.11
/// Returns whether a section is available for purchase as a market sale
function sectionForSale( uint _section_index ) returns (bool) { if (_section_index >= sections.length) throw; Section s = sections[_section_index]; // Has the user set the section as for_sale if(s.for_sale) { // Has the owner set a "sell only to" address? if(s.sell_only_to == 0x0) return true; if(s.sell_only_to == msg.sender) return true; return false; } else { // Not for sale return false; } }
0.4.11
/// Set an inidividual section as for sale at the provided price in wei. /// The section will be available for purchase by any address.
function setSectionForSale( uint _section_index, uint256 _price ) { if (_section_index >= sections.length) throw; Section section = sections[_section_index]; if(section.owner != msg.sender) throw; section.price = _price; section.for_sale = true; section.sell_only_to = 0x0; NewListing(_section_index, _price); }
0.4.11
/** * @notice Constructor for contract. Sets token and beneficiary addresses. * @param _token token address - supposed to be DGTX address * @param _beneficiary recipient of received ethers */
function Auction(address _token, address _beneficiary, uint _startTime, uint _maxBidInCentsPerAddress) public payable Ownable() { require(_token != address(0)); require(_beneficiary != address(0)); require(_startTime > now); require(_maxBidInCentsPerAddress > 0); token = _token; beneficiary = _beneficiary; startTime = _startTime; endTime = startTime + 30 days; maxBidInCentsPerAddress = _maxBidInCentsPerAddress; }
0.4.19
/** * @notice Fallback function. * During the auction receives and remembers participants bids. * After the sale is finished, withdraws tokens to participants. * It is not allowed to bid from contract (e.g., multisig). */
function () public payable { if (msg.sender == owner) { return; } require(now >= startTime); require(!isContract(msg.sender)); if (!hasEnded()) { require(msg.value >= TRANSACTION_MIN_IN_ETH); bid(msg.sender, msg.value); } else { require(!withdrawn[msg.sender]); require(centsReceived[msg.sender] != 0); withdrawTokens(msg.sender); msg.sender.transfer(msg.value); } }
0.4.19
/** * @notice Get current price: dgtx to cents. * 25 cents in the beginning and linearly decreases by 1 cent every hour until it reaches 1 cent. * @return current token to cents price */
function getPrice() public view returns (uint) { if (now < startTime) { return START_PRICE_IN_CENTS; } uint passedHours = (now - startTime) / 1 hours; return (passedHours >= 24) ? MIN_PRICE_IN_CENTS : (25 - passedHours); }
0.4.19
/** * @notice Function to receive transaction from oracle with new ETH rate. * @dev Calls updateEthToCentsRate in one hour (starts update cycle) * @param result string with new rate */
function __callback(bytes32, string result) public { require(msg.sender == oraclize_cbAddress()); uint newEthToCents = parseInt(result, 2); // convert string to cents if (newEthToCents > 0) { ethToCents = newEthToCents; EthToCentsUpdated(ethToCents); } if (!hasEnded()) { updateEthToCentsRate(1 hours); } }
0.4.19
/** * @notice Function to transfer tokens to participants in the range [_from, _to). * @param _from starting index in the range of participants to withdraw to * @param _to index after the last participant to withdraw to */
function distributeTokensRange(uint _from, uint _to) public { require(hasEnded()); require(_from < _to && _to <= participants.length); address recipient; for (uint i = _from; i < _to; ++i) { recipient = participants[i]; if (!withdrawn[recipient]) { withdrawTokens(recipient); } } }
0.4.19
/** * @dev Function which records bids. * @param _bidder is the address that bids * @param _valueETH is value of THE bid in ether */
function bid(address _bidder, uint _valueETH) internal { uint price = getPrice(); uint bidInCents = _valueETH * ethToCents / 1 ether; uint centsToAccept = bidInCents; uint ethToAccept = _valueETH; // Refund any ether above address bid limit if (centsReceived[_bidder] + centsToAccept > maxBidInCentsPerAddress) { centsToAccept = maxBidInCentsPerAddress - centsReceived[_bidder]; ethToAccept = centsToAccept * 1 ether / ethToCents; } // Refund bid part which more than total tokens cost if (totalCentsCollected + centsToAccept > price * totalTokens / TOKEN_DECIMALS_MULTIPLIER) { centsToAccept = price * totalTokens / TOKEN_DECIMALS_MULTIPLIER - totalCentsCollected; ethToAccept = centsToAccept * 1 ether / ethToCents; } require(centsToAccept > 0 && ethToAccept > 0); if (centsReceived[_bidder] == 0) { participants.push(_bidder); } centsReceived[_bidder] += centsToAccept; totalCentsCollected += centsToAccept; Bid(_bidder, centsToAccept); if (ethToAccept < _valueETH) { _bidder.transfer(_valueETH - ethToAccept); } beneficiary.transfer(ethToAccept); }
0.4.19
/** * @dev Internal function to withdraw tokens by final price. * @param _recipient participant to withdraw */
function withdrawTokens(address _recipient) internal { uint256 tokens = 0; if (totalCentsCollected < totalTokens * MIN_PRICE_IN_CENTS / TOKEN_DECIMALS_MULTIPLIER) { tokens = centsReceived[_recipient] * TOKEN_DECIMALS_MULTIPLIER / MIN_PRICE_IN_CENTS; } else { tokens = centsReceived[_recipient] * totalTokens / totalCentsCollected; } withdrawn[_recipient] = true; ERC223(token).transfer(_recipient, tokens); TokensWithdraw(_recipient, tokens); }
0.4.19
/// Set a section region for sale at the provided price in wei. /// The sections in the region will be available for purchase by any address.
function setRegionForSale( uint _start_section_index, uint _end_section_index, uint _price ) { if(_start_section_index > _end_section_index) throw; if(_end_section_index > 9999) throw; uint x_pos = _start_section_index % 100; uint base_y_pos = (_start_section_index - (_start_section_index % 100)) / 100; uint x_max = _end_section_index % 100; uint y_max = (_end_section_index - (_end_section_index % 100)) / 100; while(x_pos <= x_max) { uint y_pos = base_y_pos; while(y_pos <= y_max) { Section section = sections[x_pos + (y_pos * 100)]; if(section.owner == msg.sender) { section.price = _price; section.for_sale = true; section.sell_only_to = 0x0; NewListing(x_pos + (y_pos * 100), _price); } y_pos++; } x_pos++; } }
0.4.11
/// Set a section region starting in the top left at the supplied start section /// index to and including the supplied bottom right end section index /// for sale at the provided price in wei, to the provided address. /// The sections in the region will be available for purchase only by the /// provided address.
function setRegionForSaleToAddress( uint _start_section_index, uint _end_section_index, uint _price, address _only_sell_to ) { if(_start_section_index > _end_section_index) throw; if(_end_section_index > 9999) throw; uint x_pos = _start_section_index % 100; uint base_y_pos = (_start_section_index - (_start_section_index % 100)) / 100; uint x_max = _end_section_index % 100; uint y_max = (_end_section_index - (_end_section_index % 100)) / 100; while(x_pos <= x_max) { uint y_pos = base_y_pos; while(y_pos <= y_max) { Section section = sections[x_pos + (y_pos * 100)]; if(section.owner == msg.sender) { section.price = _price; section.for_sale = true; section.sell_only_to = _only_sell_to; NewListing(x_pos + (y_pos * 100), _price); } y_pos++; } x_pos++; } }
0.4.11
/// Update a region of sections' cloud image_id and md5 to be redrawn on the /// map starting at the top left start section index to and including the /// bottom right section index. Fires a NewImage event with the top left /// section index. If any sections not owned by the sender are in the region /// they are ignored.
function setRegionImageDataCloud( uint _start_section_index, uint _end_section_index, uint _image_id, string _md5 ) { if (_end_section_index < _start_section_index) throw; var (start_x, start_y) = getIdentifierFromSectionIndex(_start_section_index); var (end_x, end_y) = getIdentifierFromSectionIndex(_end_section_index); if (start_x >= mapWidth) throw; if (start_y >= mapHeight) throw; if (end_x >= mapWidth) throw; if (end_y >= mapHeight) throw; uint y_pos = start_y; while (y_pos <= end_y) { uint x_pos = start_x; while (x_pos <= end_x) { uint identifier = (x_pos + (y_pos * 100)); Section s = sections[identifier]; if(s.owner == msg.sender) { s.image_id = _image_id; s.md5 = _md5; } x_pos = x_pos + 1; } y_pos = y_pos + 1; } NewImage(_start_section_index); return; }
0.4.11
/// Set a single section as for sale at the provided price in wei only /// to the supplied address.
function setSectionForSaleToAddress( uint _section_index, uint256 _price, address _to ) { if (_section_index >= sections.length) throw; Section section = sections[_section_index]; if(section.owner != msg.sender) throw; section.price = _price; section.for_sale = true; section.sell_only_to = _to; NewListing(_section_index, _price); }
0.4.11
/// Delist a region of sections for sale. Making the sections no longer /// no longer available on the market.
function unsetRegionForSale( uint _start_section_index, uint _end_section_index ) { if(_start_section_index > _end_section_index) throw; if(_end_section_index > 9999) throw; uint x_pos = _start_section_index % 100; uint base_y_pos = (_start_section_index - (_start_section_index % 100)) / 100; uint x_max = _end_section_index % 100; uint y_max = (_end_section_index - (_end_section_index % 100)) / 100; while(x_pos <= x_max) { uint y_pos = base_y_pos; while(y_pos <= y_max) { Section section = sections[x_pos + (y_pos * 100)]; if(section.owner == msg.sender) { section.for_sale = false; section.price = 0; Delisted(x_pos + (y_pos * 100)); } y_pos++; } x_pos++; } }
0.4.11
/// Depreciated. Store the raw image data in the contract.
function setImageData( uint _section_index // bytes32 _row_zero, // bytes32 _row_one, // bytes32 _row_two, // bytes32 _row_three, // bytes32 _row_four, // bytes32 _row_five, // bytes32 _row_six, // bytes32 _row_seven, // bytes32 _row_eight, // bytes32 _row_nine ) { if (_section_index >= sections.length) throw; Section section = sections[_section_index]; if(section.owner != msg.sender) throw; // section.image_data[0] = _row_zero; // section.image_data[1] = _row_one; // section.image_data[2] = _row_two; // section.image_data[3] = _row_three; // section.image_data[4] = _row_four; // section.image_data[5] = _row_five; // section.image_data[6] = _row_six; // section.image_data[7] = _row_seven; // section.image_data[8] = _row_eight; // section.image_data[9] = _row_nine; section.image_id = 0; section.md5 = ""; section.last_update = block.timestamp; NewImage(_section_index); }
0.4.11
/// Set a section's image data to be redrawn on the map. Fires a NewImage /// event.
function setImageDataCloud( uint _section_index, uint _image_id, string _md5 ) { if (_section_index >= sections.length) throw; Section section = sections[_section_index]; if(section.owner != msg.sender) throw; section.image_id = _image_id; section.md5 = _md5; section.last_update = block.timestamp; NewImage(_section_index); }
0.4.11
/** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */
function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(msg.sender, beneficiary, weiAmount, tokens); // _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); // _postValidatePurchase(beneficiary, weiAmount); }
0.4.24
/** this can only be done once, so this oracle is solely for working with * three AssetSwap contracts * assetswap 0 is the ETH, at 2.5 leverage * assetswap 1 is the SPX, at 10x leverage * assetswap 2 is the BTC, at 2.5 leverage * */
function addAssetSwaps(address newAS0, address newAS1, address newAS2) external onlyAdmin { require(assetSwaps[0] == address(0)); assetSwaps[0] = newAS0; assetSwaps[1] = newAS1; assetSwaps[2] = newAS2; readers[newAS0] = true; readers[newAS1] = true; readers[newAS2] = true; }
0.5.15
/** Quickly fix an erroneous price, or correct the fact that 50% movements are * not allowed in the standard price input * this must be called within 60 minutes of the initial price update occurence */
function editPrice(uint _ethprice, uint _spxprice, uint _btcprice) external onlyAdmin { require(now < lastUpdateTime + 60 minutes); prices[0][currentDay] = _ethprice; prices[1][currentDay] = _spxprice; prices[2][currentDay] = _btcprice; emit PriceUpdated(_ethprice, _spxprice, _btcprice, now, currentDay, true); }
0.5.15
/** * @return startDay relevant for trades done now * pulls the day relevant for new AssetSwap subcontracts * startDay 2 means the 2 slot (ie, the third) of prices will be the initial * price for the subcontract. As 5 is the top slot, and rolls into slot 0 * the next week, the next pricing day is 1 when the current day == 5 * (this would be a weekend or Monday morning) */
function getStartDay() public view returns (uint8 _startDay) { if (nextUpdateSettle) { _startDay = 5; } else if (currentDay == 5) { _startDay = 1; } else { _startDay = currentDay + 1; } }
0.5.15
/// Transfer a region of sections and IPO tokens to the supplied address.
function transferRegion( uint _start_section_index, uint _end_section_index, address _to ) { if(_start_section_index > _end_section_index) throw; if(_end_section_index > 9999) throw; uint x_pos = _start_section_index % 100; uint base_y_pos = (_start_section_index - (_start_section_index % 100)) / 100; uint x_max = _end_section_index % 100; uint y_max = (_end_section_index - (_end_section_index % 100)) / 100; while(x_pos <= x_max) { uint y_pos = base_y_pos; while(y_pos <= y_max) { Section section = sections[x_pos + (y_pos * 100)]; if(section.owner == msg.sender) { if (balanceOf[_to] + 1 < balanceOf[_to]) throw; section.owner = _to; section.for_sale = false; balanceOf[msg.sender] -= 1; balanceOf[_to] += 1; } y_pos++; } x_pos++; } }
0.4.11
// this function will only return the no of dai can pay till now
function getCurrentInstallment(address _addr) public view returns(uint256) { require(registeredusers[_addr],'you are not registered'); if(block.timestamp > users[_addr].time){ return users[_addr].daiamount; } uint256 timeleft = users[_addr].time.sub(block.timestamp); uint256 amt = users[_addr].daiamount.mul(1e18).div(users[_addr].months); uint256 j; for(uint256 i = users[_addr].months;i>0;i--){ if(timeleft <= oneMonthTime || timeleft == 0){ return users[_addr].daiamount; } j= j.add(1); if(timeleft > i.sub(1).mul(oneMonthTime)){ return amt.mul(j).div(1e18); } } }
0.6.12
/* only owner address can do manual refund * used only if bet placed + oraclize failed to __callback * filter LogBet by address and/or playerBetId: * LogBet(playerBetId[rngId], playerAddress[rngId], safeAdd(playerBetValue[rngId], playerProfit[rngId]), playerProfit[rngId], playerBetValue[rngId], playerNumber[rngId]); * check the following logs do not exist for playerBetId and/or playerAddress[rngId] before refunding: * LogResult or LogRefund * if LogResult exists player should use the withdraw pattern playerWithdrawPendingTransactions */
function ownerRefundPlayer(bytes32 originalPlayerBetId, address sendTo, uint originalPlayerProfit, uint originalPlayerBetValue) public onlyOwner { /* safely reduce pendingPayouts by playerProfit[rngId] */ maxPendingPayouts = safeSub(maxPendingPayouts, originalPlayerProfit); /* send refund */ if(!sendTo.send(originalPlayerBetValue)) throw; /* log refunds */ LogRefund(originalPlayerBetId, sendTo, originalPlayerBetValue); }
0.4.10
/**************************************************** Public Interface for Stakers **************************************************************/
function createNewStake(uint256 _amount, uint8 _lockupPeriod, bool _compound) public { require(!paused, "New stakes are paused"); require(_isValidLockupPeriod(_lockupPeriod), "The lockup period is invalid"); require(_amount >= 5000000000000000000000, "You must stake at least 5000 LIT"); require(_canStakeToday(), "You can't start a stake until the first day of next month"); require(IERC20(litionToken).transferFrom(msg.sender, address(this), _amount), "Couldn't take the LIT from the sender"); Stake memory stake = Stake({createdOn: now, totalStaked:_amount, lockupPeriod:_lockupPeriod, compound:_compound, isFinished:false}); Stake[] storage stakes = stakeListBySender[msg.sender].stakes; stakes.push(stake); _addStakerIfNotExist(msg.sender); emit NewStake(msg.sender, _amount, _lockupPeriod, _compound); }
0.5.12
// Will be called monthly, at the end of each month
function _accreditRewards() public onlyOwner { uint256 totalToAccredit = getTotalRewardsToBeAccredited(); require(IERC20(litionToken).transferFrom(msg.sender, address(this), totalToAccredit), "Couldn't take the LIT from the sender"); for (uint256 i = 0; i < stakers.length; i++) { StakeList storage stakeList = stakeListBySender[stakers[i]]; uint256 rewardsToBeAccredited = stakeList.rewardsToBeAccredited; if (rewardsToBeAccredited > 0) { stakeList.rewardsToBeAccredited = 0; stakeList.rewards += rewardsToBeAccredited; emit RewardsAccreditedToStaker(stakers[i], rewardsToBeAccredited); } } emit RewardsAccredited(totalToAccredit); }
0.5.12
// Will be called every day to distribute the accumulated new MiningReward events coming from LitionRegistry
function _updateRewardsToBeAccredited(uint256 _fromMiningRewardBlock, uint256 _toMiningRewardBlock, uint256 _amount) public onlyOwner { require(_fromMiningRewardBlock < _toMiningRewardBlock, "Invalid params"); require(_fromMiningRewardBlock > lastMiningRewardBlock, "Rewards already distributed"); lastMiningRewardBlock = _toMiningRewardBlock; //Won't consider any stake marked as isFinished uint256 fees = _amount.mul(5) / 100; // Amount the validator will keep for himself uint256 totalParts = _calculateParts(); _distributeBetweenStakers(totalParts, _amount.sub(fees)); emit RewardsToBeAccreditedDistributed(_amount); }
0.5.12
/**************************************************** Internal Admin - Lockups **************************************************************/
function calculateFinishTimestamp(uint256 _timestamp, uint8 _lockupPeriod) public pure returns (uint256) { uint16 year = Date.getYear(_timestamp); uint8 month = Date.getMonth(_timestamp); month += _lockupPeriod; if (month > 12) { year += 1; month = month % 12; } uint8 newDay = Date.getDaysInMonth(month, year); return Date.toTimestamp(year, month, newDay); }
0.5.12
/**************************************************** Internal Admin - Validations **************************************************************/
function _isValidLockupPeriod(uint8 n) internal pure returns (bool) { if (n == 1) { return true; } else if (n == 3) { return true; } else if (n == 6) { return true; } else if (n == 12) { return true; } return false; }
0.5.12
// get back the BET before claimingPhase
function getRefund(uint _gameID) external { require(now < games[_gameID].claimingPhaseStart - 1 days); require(games[_gameID].tickets[msg.sender]>0); games[_gameID].tickets[msg.sender] -= 1; games[_gameID].numTickets -= 1; uint refund = games[_gameID].ticketPrice * REFUND_PERCENT / 100; uint admin_fee = games[_gameID].ticketPrice * (100 - REFUND_PERCENT - MAINTENANCE_FEE_PERCENT) / 100; admin_profit += admin_fee; games[_gameID].balance -= games[_gameID].ticketPrice * (100 - MAINTENANCE_FEE_PERCENT) / 100; msg.sender.transfer(refund); }
0.4.24
/// @dev Buy tokens function /// @param beneficiary Address which will receive the tokens
function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(helper.isWhitelisted(beneficiary)); uint256 weiAmount = msg.value; require(weiAmount > 0); uint256 tokenAmount = 0; if (isPresale()) { /// Minimum contribution of 1 ether during presale require(weiAmount >= 1 ether); tokenAmount = getTokenAmount(weiAmount, preDiscountPercentage); uint256 newTokensSoldPre = tokensSoldPre.add(tokenAmount); require(newTokensSoldPre <= preCap); tokensSoldPre = newTokensSoldPre; } else if (isIco()) { uint8 discountPercentage = getIcoDiscountPercentage(); tokenAmount = getTokenAmount(weiAmount, discountPercentage); /// Minimum contribution 1 token during ICO require(tokenAmount >= 10**18); uint256 newTokensSoldIco = tokensSoldIco.add(tokenAmount); require(newTokensSoldIco <= icoCap); tokensSoldIco = newTokensSoldIco; } else { /// Stop execution and return remaining gas require(false); } executeTransaction(beneficiary, weiAmount, tokenAmount); }
0.4.19
/// @dev Internal function used for calculating ICO discount percentage depending on levels
function getIcoDiscountPercentage() internal constant returns (uint8) { if (tokensSoldIco <= icoDiscountLevel1) { return icoDiscountPercentageLevel1; } else if (tokensSoldIco <= icoDiscountLevel1.add(icoDiscountLevel2)) { return icoDiscountPercentageLevel2; } else { return icoDiscountPercentageLevel3; //for everything else } }
0.4.19
/// @dev Internal function used to calculate amount of tokens based on discount percentage
function getTokenAmount(uint256 weiAmount, uint8 discountPercentage) internal constant returns (uint256) { /// Less than 100 to avoid division with zero require(discountPercentage >= 0 && discountPercentage < 100); uint256 baseTokenAmount = weiAmount.mul(rate); uint256 tokenAmount = baseTokenAmount.mul(10000).div(100 - discountPercentage); return tokenAmount; }
0.4.19
/// @dev Change discount percentages for different phases /// @param _icoDiscountPercentageLevel1 Discount percentage of phase 1 /// @param _icoDiscountPercentageLevel2 Discount percentage of phase 2 /// @param _icoDiscountPercentageLevel3 Discount percentage of phase 3
function changeIcoDiscountPercentages(uint8 _icoDiscountPercentageLevel1, uint8 _icoDiscountPercentageLevel2, uint8 _icoDiscountPercentageLevel3) public onlyOwner { require(_icoDiscountPercentageLevel1 >= 0 && _icoDiscountPercentageLevel1 < 100); require(_icoDiscountPercentageLevel2 >= 0 && _icoDiscountPercentageLevel2 < 100); require(_icoDiscountPercentageLevel3 >= 0 && _icoDiscountPercentageLevel3 < 100); IcoDiscountPercentagesChanged(owner, _icoDiscountPercentageLevel1, _icoDiscountPercentageLevel2, _icoDiscountPercentageLevel3); icoDiscountPercentageLevel1 = _icoDiscountPercentageLevel1; icoDiscountPercentageLevel2 = _icoDiscountPercentageLevel2; icoDiscountPercentageLevel3 = _icoDiscountPercentageLevel3; }
0.4.19
/** Configure redemption amounts for each group. ONE token of _groupIdin results in _amountOut number of _groupIdOut tokens @param _groupIdIn The group ID of the token being redeemed @param _groupIdIn The group ID of the token being received @param _data The redemption config data input. */
function setRedemptionConfig(uint256 _groupIdIn, uint256 _groupIdOut, address _tokenOut, RedemptionConfig calldata _data) external onlyOwner { redemptionConfigs[_groupIdIn][_tokenOut] = RedemptionConfig({ groupIdOut: _groupIdOut, amountOut: _data.amountOut, burnOnRedemption: _data.burnOnRedemption }); // uint256 groupId; // uint256 amountOut; // bool burnOnRedemption; emit ConfigUpdate(_groupIdIn, _groupIdOut, _tokenOut, _data.amountOut, _data.burnOnRedemption); }
0.7.6
//Note: returns a boolean indicating whether transfer was successful
function transfer(address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); //not sending to burn address require(_value <= balances[msg.sender]); // If the sender has sufficient funds to send require(_value>0);// and the amount is not zero or negative // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
0.4.23
// low level token purchase function //implements the logic for the token buying
function buyTokens(address beneficiary) public payable { //tokens cannot be burned by sending to 0x0 address require(beneficiary != address(0)); //token must adhere to the valid restrictions of the validPurchase() function, ie within time period and buying tokens within max/min limits require(validPurchase(beneficiary)); uint256 weiAmount = msg.value; // calculate token amount to be bought uint256 tokens = getTokenAmount(weiAmount); //Logic so that investors must purchase at least 1 token. require(weiAmount >= minPurchaseInEth); //Token transfer require(token.transfer(beneficiary, tokens)); // update state //increment the total ammount raised by the amount of this transaction weiRaised = weiRaised.add(weiAmount); //decrease the amount of remainingTokens by the amount of tokens sold remainingTokens = remainingTokens.sub(tokens); //increase the investment total of the buyer invested[beneficiary] = invested[beneficiary].add(msg.value); emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); //transfer the ether received to the specified recipient address forwardFunds(); }
0.4.23
// Function to have a way to add business logic to your crowdsale when buying
function getTokenAmount(uint256 weiAmount) internal returns(uint256) { //Logic for pricing based on the Tiers of the crowdsale // These bonus amounts and the number of tiers itself can be changed /*This means that: - If you purchase within the tier 1 ICO (earliest tier) you receive a 20% bonus in your token purchase. - If you purchase within the tier 2 ICO (later tier) you receive a 10% bonus in your token purchase. - If you purchase outside of any of the defined bonus tiers then you receive the original rate of tokens (1 token per 0.01 ether) */ if (now>=tier1Start && now < tier1End) { rate = 120; }else if (now>=tier2Start && now < tier2End) { rate = 110; }else { rate = 100; } return weiAmount.mul(rate); }
0.4.23
/** * @notice mint brand new RogueRhino nfts * @param _numRhinos is the number of rhinos to mint */
function mintRhino(uint256 _numRhinos) public payable saleIsLive { require(tx.origin == msg.sender, "Humans only"); require(_numRhinos > 0, "0 mint"); require(_numRhinos < MINT_MAX, "20 max"); require(msg.value == (_numRhinos * mintPrice), "Wrong ETH"); _mintRhinos(msg.sender, _numRhinos); }
0.8.4
/** * @notice mint rhinos from the two allowlists. * Raging Rhinos got rugged. If you held Raging (rugged) Rhinos * at the snapshot (Jan 25th 2022) you got on the Rogue allowlist. * @dev you do not have to mint all your quota at once but * you must pass the same sig and claimQuota each time you mint. * @param _numToMint number of rhinos to mint in this call * @param _sig allowlist signature * @param _claimQuota initial allowlist quota to claim * @param _listId 1 for raging rhino holder, 2 for public allowlist */
function rogueListMint( uint256 _numToMint, bytes calldata _sig, uint256 _claimQuota, uint256 _listId ) public payable presaleIsLive { //which allowlist is msg.sender in? if (_listId == 1) { //rogue allowlist require(msg.value == 0, "Wrong ETH"); } else if (_listId == 2) { //public allowlist require(msg.value == (mintPrice * _numToMint), "Wrong ETH"); } else { //for completeness revert("Bad listId"); } require(tx.origin == msg.sender, "Humans only"); require(_numToMint > 0, "0 mint"); uint256 _minted = minted[msg.sender]; //local var for gas efficiency require(_numToMint + _minted <= _claimQuota, "Quota exceeded"); require(legitSigner(_sig, _claimQuota, _listId), "Invalid sig"); _minted += _numToMint; minted[msg.sender] = _minted; _mintRhinos(msg.sender, _numToMint); }
0.8.4
/** * @notice list all the rhinos in a wallet * @dev useful for staking in future utility * @dev don't call from a contract or you'll * ruin yourself with gas */
function walletOfOwner(address _addr) public virtual view returns (uint256[] memory) { uint256 ownerBal = balanceOf(_addr); if (ownerBal == 0) { return new uint256[](0); } else { uint256[] memory tokenList = new uint256[](ownerBal); uint256 count; uint256 maxLoops = totalSupply; for (uint i = 0; i < maxLoops; i++) { bool exists = _exists(i); if (exists && ownerOf(i) == _addr) { tokenList[count] = i; count++; } else if (!exists && tokenList[ownerBal - 1] == 0) { maxLoops++; } } return tokenList; } }
0.8.4
///withdraw to trusted wallets
function withdraw() public { //team shares assigned in constructor are access keys require(teamShares[msg.sender] > 0, "Team only"); uint256 bal = address(this).balance; for (uint256 mem = 0; mem < teamAddrs.length; mem++) { address adi = teamAddrs[mem]; payable(adi).send(teamShares[adi] * bal / 10000); } }
0.8.4
/** * @notice mint function called by multiple other functions * @param _to recipient address * @param _num number of rhinos to mint */
function _mintRhinos(address _to, uint256 _num) internal { uint256 _totalSupply = totalSupply; //temp var for gas efficiency require(_totalSupply + _num < MAX_RHINOS, "Too few Rhinos left!"); for (uint256 r = 0; r < _num; r++) { unchecked { //overflow checked above _totalSupply++; } _safeMint(_to, _totalSupply); //trusted parent } totalSupply = _totalSupply; }
0.8.4
/** * @notice was the correct hash signed by the msgSigner? * @param _sig the signed hash to inspect * @dev _sig should be a signed hash of the sender, * this contract, their quota and the whitelist id. * The signer is recovered and compared to msgSigner for validity. */
function legitSigner(bytes memory _sig, uint256 _numToHash, uint256 _wlId) private view returns (bool) { //hash the sender, this address, and a number //this should be the same hash as signed in _sig bytes32 checkHash = keccak256(abi.encodePacked( msg.sender, address(this), _numToHash, _wlId )); bytes32 ethHash = ECDSA.toEthSignedMessageHash(checkHash); address recoveredSigner = ECDSA.recover(ethHash, _sig); return (recoveredSigner == msgSigner); }
0.8.4
/* * Set the reward peroid. If only possible to set the reward period after last rewards have been * expired. * * @param _periodStart timestamp of reward starting time * @param _rewardsDuration the duration of rewards in seconds */
function setPeriod(uint64 _periodStart, uint64 _rewardsDuration) public onlyOwner { require(_periodStart >= block.timestamp, "OpenDAOStaking: _periodStart shouldn't be in the past"); require(_rewardsDuration > 0, "OpenDAOStaking: Invalid rewards duration"); Config memory cfg = config; require(cfg.periodFinish < block.timestamp, "OpenDAOStaking: The last reward period should be finished before setting a new one"); uint64 _periodFinish = _periodStart + _rewardsDuration; config.periodStart = _periodStart; config.periodFinish = _periodFinish; config.totalReward = 0; }
0.8.9
/* * Returns the frozen rewards * * @returns amount of frozen rewards */
function frozenRewards() public view returns(uint256) { Config memory cfg = config; uint256 time = block.timestamp; uint256 remainingTime; uint256 duration = uint256(cfg.periodFinish) - uint256(cfg.periodStart); if (time <= cfg.periodStart) { remainingTime = duration; } else if (time >= cfg.periodFinish) { remainingTime = 0; } else { remainingTime = cfg.periodFinish - time; } return remainingTime * uint256(cfg.totalReward) / duration; }
0.8.9
/* * Staking specific amount of SOS token and get corresponding amount of veSOS * as the user's share in the pool * * @param _sosAmount */
function enter(uint256 _sosAmount) external { require(_sosAmount > 0, "OpenDAOStaking: Should at least stake something"); uint256 totalSOS = getSOSPool(); uint256 totalShares = totalSupply(); sos.safeTransferFrom(msg.sender, address(this), _sosAmount); if (totalShares == 0 || totalSOS == 0) { _mint(msg.sender, _sosAmount); } else { uint256 _share = _sosAmount * totalShares / totalSOS; _mint(msg.sender, _share); } }
0.8.9
/* * Redeem specific amount of veSOS to SOS tokens according to the user's share in the pool. * veSOS will be burnt. * * @param _share */
function leave(uint256 _share) external { require(_share > 0, "OpenDAOStaking: Should at least unstake something"); uint256 totalSOS = getSOSPool(); uint256 totalShares = totalSupply(); _burn(msg.sender, _share); uint256 _sosAmount = _share * totalSOS / totalShares; sos.safeTransfer(msg.sender, _sosAmount); }
0.8.9
/** * @dev Public Mint */
function mintPublic() public payable nonReentrant { require(tx.origin == msg.sender, "Bad."); require(publicMintState, "Public mint is currently paused."); uint256 currentSupply = totalSupply(); require(currentSupply < MAX_SUPPLY, "Maximum amount of NFTs have been minted."); require(msg.value >= mintPrice, "Not enough Ether sent to mint an NFT."); _safeMint(msg.sender, 1); }
0.8.11
/** * @dev Whitelist Mint */
function mintWhitelist(uint256 _amount) public nonReentrant { require(tx.origin == msg.sender, "Bad."); require(whitelistMintState, "Whitelist mint is currently paused."); uint256 currentSupply = totalSupply(); require(_amount <= whitelist[msg.sender], "You can't mint that many NFT's"); require((currentSupply + _amount) < maxWhitelistAmount, "Max whitelist NFTs minted."); require(_amount > 0, "Amount must be greater than zero."); whitelist[msg.sender] -= _amount; _safeMint(msg.sender, _amount); }
0.8.11
/** * @dev Requests updating rate from oraclize. */
function updateRate() external onlyBank returns (bool) { if (getPrice() > this.balance) { OraclizeError("Not enough ether"); return false; } bytes32 queryId = oraclize_query(oracleConfig.datasource, oracleConfig.arguments, gasLimit, priceLimit); if (queryId == bytes32(0)) { OraclizeError("Unexpectedly high query price"); return false; } NewOraclizeQuery(); validIds[queryId] = true; waitQuery = true; updateTime = now; return true; }
0.4.23
/** * @dev Oraclize default callback with the proof set. * @param myid The callback ID. * @param result The callback data. * @param proof The oraclize proof bytes. */
function __callback(bytes32 myid, string result, bytes proof) public { require(validIds[myid] && msg.sender == oraclize_cbAddress()); rate = Helpers.parseIntRound(result, 3); // save it in storage as 1/1000 of $ delete validIds[myid]; callbackTime = now; waitQuery = false; PriceTicker(result, myid, proof); }
0.4.23
// ###################### // ##### ONLY OWNER ##### // ######################
function addLiquidity() external onlyOwner() { require(!m_TradingOpened,"trading is already open"); m_Whitelist[_msgSender()] = true; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); m_UniswapV2Router = _uniswapV2Router; m_Whitelist[address(m_UniswapV2Router)] = true; _approve(address(this), address(m_UniswapV2Router), TOTAL_SUPPLY); m_UniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); m_Whitelist[m_UniswapV2Pair] = true; m_Exchange[m_UniswapV2Pair] = true; m_UniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); m_SwapEnabled = true; m_TradingOpened = true; IERC20(m_UniswapV2Pair).approve(address(m_UniswapV2Router), type(uint).max); }
0.8.4
/** * @dev Set the limit of a class. * @param _id The id of the class. * @param _limit The limit of the class. */
function setLimit(uint256 _id, uint256 _limit) external onlyOwner { Info storage info = table[_id]; Action action = getAction(info.limit, _limit); if (action == Action.Insert) { info.index = array.length; info.limit = _limit; array.push(_id); } else if (action == Action.Update) { info.limit = _limit; } else if (action == Action.Remove) { // at this point we know that array.length > info.index >= 0 uint256 last = array[array.length - 1]; // will never underflow table[last].index = info.index; array[info.index] = last; array.length -= 1; // will never underflow delete table[_id]; } emit ActionCompleted(_id, _limit, action); }
0.4.25
/** * @dev Get the required action. * @param _prev The old limit. * @param _next The new limit. * @return The required action. */
function getAction(uint256 _prev, uint256 _next) private pure returns (Action) { if (_prev == 0 && _next != 0) return Action.Insert; if (_prev != 0 && _next == 0) return Action.Remove; if (_prev != _next) return Action.Update; return Action.None; }
0.4.25
/** * @dev Transfer tokens in batches (of adresses) * @param _vaddr address The address which you want to send tokens from * @param _vamounts address The address which you want to transfer to */
function batchAssignTokens(address[] _vaddr, uint[] _vamounts, uint[] _vDefrostClass ) onlyOwner { require ( batchAssignStopped == false ); require ( _vaddr.length == _vamounts.length && _vaddr.length == _vDefrostClass.length); //Looping into input arrays to assign target amount to each given address for (uint index=0; index<_vaddr.length; index++) { address toAddress = _vaddr[index]; uint amount = SafeMath.mul(_vamounts[index], 10 ** decimals); uint defrostClass = _vDefrostClass[index]; // 0=ico investor, 1=reserveandteam/advisors if ( defrostClass == 0 ) { // investor account transfer(toAddress, amount); assignedSupply = SafeMath.add(assignedSupply, amount); } else if(defrostClass == 1){ // Iced account. The balance is not affected here vIcedBalances.push(toAddress); icedBalances_frosted[toAddress] = amount; icedBalances_defrosted[toAddress] = 0; assignedSupply = SafeMath.add(assignedSupply, amount); } } }
0.4.23
/* * An accurate estimate for the total amount of assets (principle + return) * that this strategy is currently managing, denominated in terms of want tokens. */
function estimatedTotalAssets() public override view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 _claimableComp = predictCompAccrued(); uint256 currentComp = IERC20(comp).balanceOf(address(this)); // Use touch price. it doesnt matter if we are wrong as this is not used for decision making uint256 estimatedWant = priceCheck(comp, address(want),_claimableComp.add(currentComp)); uint256 conservativeWant = estimatedWant.mul(9).div(10); //10% pessimist return want.balanceOf(address(this)).add(deposits).add(conservativeWant).sub(borrows); }
0.6.12
//predicts our profit at next report
function expectedReturn() public view returns (uint256) { uint256 estimateAssets = estimatedTotalAssets(); uint256 debt = vault.strategies(address(this)).totalDebt; if (debt > estimateAssets) { return 0; } else { return estimateAssets - debt; } }
0.6.12
//WARNING. manipulatable and simple routing. Only use for safe functions
function priceCheck(address start, address end, uint256 _amount) public view returns (uint256) { if (_amount == 0) { return 0; } address[] memory path; if(start == weth){ path = new address[](2); path[0] = weth; path[1] = end; }else{ path = new address[](3); path[0] = start; path[1] = weth; path[2] = end; } uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path); return amounts[amounts.length - 1]; }
0.6.12
//Calculate how many blocks until we are in liquidation based on current interest rates //WARNING does not include compounding so the estimate becomes more innacurate the further ahead we look //equation. Compound doesn't include compounding for most blocks //((deposits*colateralThreshold - borrows) / (borrows*borrowrate - deposits*colateralThreshold*interestrate));
function getblocksUntilLiquidation() public view returns (uint256) { (, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken)); (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 borrrowRate = cToken.borrowRatePerBlock(); uint256 supplyRate = cToken.supplyRatePerBlock(); uint256 collateralisedDeposit1 = deposits.mul(collateralFactorMantissa).div(1e18); uint256 collateralisedDeposit = collateralisedDeposit1; uint256 denom1 = borrows.mul(borrrowRate); uint256 denom2 = collateralisedDeposit.mul(supplyRate); if (denom2 >= denom1) { return type(uint256).max; } else { uint256 numer = collateralisedDeposit.sub(borrows); uint256 denom = denom1 - denom2; //minus 1 for this block return numer.mul(1e18).div(denom); } }
0.6.12
// This function makes a prediction on how much comp is accrued // It is not 100% accurate as it uses current balances in Compound to predict into the past
function predictCompAccrued() public view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); if (deposits == 0) { return 0; // should be impossible to have 0 balance and positive comp accrued } //comp speed is amount to borrow or deposit (so half the total distribution for want) uint256 distributionPerBlock = compound.compSpeeds(address(cToken)); uint256 totalBorrow = cToken.totalBorrows(); //total supply needs to be echanged to underlying using exchange rate uint256 totalSupplyCtoken = cToken.totalSupply(); uint256 totalSupply = totalSupplyCtoken.mul(cToken.exchangeRateStored()).div(1e18); uint256 blockShareSupply = 0; if(totalSupply > 0){ blockShareSupply = deposits.mul(distributionPerBlock).div(totalSupply); } uint256 blockShareBorrow = 0; if(totalBorrow > 0){ blockShareBorrow = borrows.mul(distributionPerBlock).div(totalBorrow); } //how much we expect to earn per block uint256 blockShare = blockShareSupply.add(blockShareBorrow); //last time we ran harvest uint256 lastReport = vault.strategies(address(this)).lastReport; uint256 blocksSinceLast= (block.timestamp.sub(lastReport)).div(13); //roughly 13 seconds per block return blocksSinceLast.mul(blockShare); }
0.6.12
//sell comp function
function _disposeOfComp() internal { uint256 _comp = IERC20(comp).balanceOf(address(this)); if (_comp > minCompToSell) { address[] memory path = new address[](3); path[0] = comp; path[1] = weth; path[2] = address(want); IUni(uniswapRouter).swapExactTokensForTokens(_comp, uint256(0), path, address(this), now); } }
0.6.12