Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
12
// Add cumulatively
userValueFromSpending[_contract][_user] = spendableInfos[_contract][_token][_newLevel].amount.add(oldTotalValueFromSpending);
userValueFromSpending[_contract][_user] = spendableInfos[_contract][_token][_newLevel].amount.add(oldTotalValueFromSpending);
14,396
202
// pod state tracker.
mapping(uint256 => bool) private launchStatus;
mapping(uint256 => bool) private launchStatus;
32,897
397
// Ensure that a sufficient amount of authorities have signed to veto this proposal.
bytes32 eip712DomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this)); bytes32 vetoHash = LibVeto.getVetoHash(
bytes32 eip712DomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this)); bytes32 vetoHash = LibVeto.getVetoHash(
23,885
9
// owner may reserve certain mints for themselves
mapping (address => bool) public reserved;
mapping (address => bool) public reserved;
85,135
35
// Curve Pool Strategy Investment strategy for investing in Curve Pools Origin Protocol Inc Factor Finance 2022 /
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { ICurvePool } from "./ICurvePool.sol"; import { IERC20, InitializableAbstractStrategy } from "../utils/InitializableAbstractStrategy.sol"; import { StableMath } from "../utils/StableMath.sol"; import { Helpers } from "../utils/Helpers.sol"; abstract contract BaseCurveStrategy is InitializableAbstractStrategy { using StableMath for uint256; using SafeERC20 for IERC20; uint256 internal constant maxSlippage = 1e16; // 1%, same as the Curve UI address internal pTokenAddress; /** * @dev Deposit asset into the Curve Pool * @param _asset Address of asset to deposit * @param _amount Amount of asset to deposit */ function deposit(address _asset, uint256 _amount) external override onlyVault nonReentrant { require(_amount > 0, "Must deposit something"); emit Deposit(_asset, address(platformAddress), _amount); // Pools requires passing deposit amounts for all assets, set to 0 for // all uint256[2] memory _amounts; uint256 poolCoinIndex = _getCoinIndex(_asset); // Set the amount on the asset we want to deposit _amounts[poolCoinIndex] = _amount; ICurvePool curvePool = ICurvePool(platformAddress); uint256 assetDecimals = Helpers.getDecimals(_asset); uint256 depositValue = _amount.scaleBy(18, assetDecimals).divPrecisely( curvePool.get_virtual_price() ); uint256 minMintAmount = depositValue.mulTruncate( uint256(1e18) - maxSlippage ); // Do the deposit to pool curvePool.add_liquidity(_amounts, minMintAmount); _lpDepositAll(); } function _lpDepositAll() internal virtual; /** * @dev Deposit the entire balance of any supported asset into the Curve pool */ function depositAll() external override onlyVault nonReentrant { uint256[2] memory _amounts = [uint256(0), uint256(0)]; uint256 depositValue = 0; ICurvePool curvePool = ICurvePool(platformAddress); uint256 curveVirtualPrice = curvePool.get_virtual_price(); for (uint256 i = 0; i < assetsMapped.length; i++) { address assetAddress = assetsMapped[i]; uint256 balance = IERC20(assetAddress).balanceOf(address(this)); if (balance > 0) { uint256 poolCoinIndex = _getCoinIndex(assetAddress); // Set the amount on the asset we want to deposit _amounts[poolCoinIndex] = balance; uint256 assetDecimals = Helpers.getDecimals(assetAddress); // Get value of deposit in Curve LP token to later determine // the minMintAmount argument for add_liquidity depositValue = depositValue + balance.scaleBy(18, assetDecimals).divPrecisely( curveVirtualPrice ); emit Deposit(assetAddress, address(platformAddress), balance); } } uint256 minMintAmount = depositValue.mulTruncate( uint256(1e18) - maxSlippage ); // Do the deposit to pool curvePool.add_liquidity(_amounts, minMintAmount); // Deposit into Gauge, the PToken is the same (USDC/USDCe) for all mapped // assets, so just get the address from the first one _lpDepositAll(); } function _lpWithdraw(uint256 numPTokens) internal virtual; /** * @dev Withdraw asset from Curve Pool * @param _recipient Address to receive withdrawn asset * @param _asset Address of asset to withdraw * @param _amount Amount of asset to withdraw */ function withdraw( address _recipient, address _asset, uint256 _amount ) external override onlyVault nonReentrant { require(_amount > 0, "Invalid amount"); emit Withdrawal(_asset, address(assetToPToken[_asset]), _amount); (uint256 contractPTokens, , uint256 totalPTokens) = _getTotalPTokens(); uint256 coinIndex = _getCoinIndex(_asset); int128 curveCoinIndex = int128(uint128(coinIndex)); // Calculate the max amount of the asset we'd get if we withdrew all the // platform tokens ICurvePool curvePool = ICurvePool(platformAddress); // Calculate how many platform tokens we need to withdraw the asset // amount in the worst case (i.e withdrawing all LP tokens) uint256 maxAmount = curvePool.calc_withdraw_one_coin( totalPTokens, curveCoinIndex ); uint256 maxBurnedPTokens = (totalPTokens * _amount) / maxAmount; // Not enough in this contract or in the Gauge, can't proceed require( totalPTokens > maxBurnedPTokens, "Insufficient USDC-USDCe balance" ); // We have enough LP tokens, make sure they are all on this contract if (contractPTokens < maxBurnedPTokens) { _lpWithdraw(maxBurnedPTokens - contractPTokens); } uint256[2] memory _amounts = [uint256(0), uint256(0)]; _amounts[coinIndex] = _amount; curvePool.remove_liquidity_imbalance(_amounts, maxBurnedPTokens); IERC20(_asset).safeTransfer(_recipient, _amount); } /** * @dev Remove all assets from platform and send them to Vault contract. */ function withdrawAll() external override onlyVaultOrGovernor nonReentrant { // Withdraw all from Gauge (, uint256 gaugePTokens, uint256 totalPTokens) = _getTotalPTokens(); _lpWithdraw(gaugePTokens); // Withdraws are proportional to assets held by Pool uint256[2] memory minWithdrawAmounts = [uint256(0), uint256(0)]; // Remove liquidity ICurvePool curvePool = ICurvePool(platformAddress); curvePool.remove_liquidity(totalPTokens, minWithdrawAmounts); // Transfer assets out of Vault // Note that Curve will provide all of the assets in pool even if // we have not set PToken addresses for all of them in this strategy for (uint256 i = 0; i < assetsMapped.length; i++) { IERC20 asset = IERC20(curvePool.coins(i)); asset.safeTransfer(vaultAddress, asset.balanceOf(address(this))); } } /** * @dev Get the total asset value held in the platform * @param _asset Address of the asset * @return balance Total value of the asset in the platform */ function checkBalance(address _asset) public view override returns (uint256 balance) { require(assetToPToken[_asset] != address(0), "Unsupported asset"); // LP tokens in this contract. This should generally be nothing as we // should always stake the full balance in the Gauge, but include for // safety (, , uint256 totalPTokens) = _getTotalPTokens(); ICurvePool curvePool = ICurvePool(platformAddress); if (totalPTokens > 0) { uint256 virtual_price = curvePool.get_virtual_price(); uint256 value = (totalPTokens * virtual_price) / 1e18; uint256 assetDecimals = Helpers.getDecimals(_asset); balance = value.scaleBy(assetDecimals, 18) / 2; } } /** * @dev Retuns bool indicating whether asset is supported by strategy * @param _asset Address of the asset */ function supportsAsset(address _asset) external view override returns (bool) { return assetToPToken[_asset] != address(0); } /** * @dev Approve the spending of all assets by their corresponding pool tokens, * if for some reason is it necessary. */ function safeApproveAllTokens() external override onlyGovernor nonReentrant { _approveBase(); // This strategy is a special case since it only supports one asset for (uint256 i = 0; i < assetsMapped.length; i++) { _approveAsset(assetsMapped[i]); } } /** * @dev Calculate the total platform token balance (i.e. USDC-USDCe) that exist in * this contract or is staked in the Gauge (or in other words, the total * amount platform tokens we own). * @return contractPTokens Amount of platform tokens in this contract * @return gaugePTokens Amount of platform tokens staked in gauge * @return totalPTokens Total amount of platform tokens in native decimals */ function _getTotalPTokens() internal view virtual returns ( uint256 contractPTokens, uint256 gaugePTokens, uint256 totalPTokens ); /** * @dev Call the necessary approvals for the Curve pool and gauge * @param _asset Address of the asset */ function _abstractSetPToken(address _asset, address _pToken) internal override { _approveAsset(_asset); } function _approveAsset(address _asset) internal { IERC20 asset = IERC20(_asset); // Pool for asset (required for adding liquidity) asset.safeApprove(platformAddress, 0); asset.safeApprove(platformAddress, type(uint256).max); } function _approveBase() internal virtual; /** * @dev Get the index of the coin */ function _getCoinIndex(address _asset) internal view returns (uint256) { for (uint256 i = 0; i < 2; i++) { if (assetsMapped[i] == _asset) return i; } revert("Invalid pool asset"); } }
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { ICurvePool } from "./ICurvePool.sol"; import { IERC20, InitializableAbstractStrategy } from "../utils/InitializableAbstractStrategy.sol"; import { StableMath } from "../utils/StableMath.sol"; import { Helpers } from "../utils/Helpers.sol"; abstract contract BaseCurveStrategy is InitializableAbstractStrategy { using StableMath for uint256; using SafeERC20 for IERC20; uint256 internal constant maxSlippage = 1e16; // 1%, same as the Curve UI address internal pTokenAddress; /** * @dev Deposit asset into the Curve Pool * @param _asset Address of asset to deposit * @param _amount Amount of asset to deposit */ function deposit(address _asset, uint256 _amount) external override onlyVault nonReentrant { require(_amount > 0, "Must deposit something"); emit Deposit(_asset, address(platformAddress), _amount); // Pools requires passing deposit amounts for all assets, set to 0 for // all uint256[2] memory _amounts; uint256 poolCoinIndex = _getCoinIndex(_asset); // Set the amount on the asset we want to deposit _amounts[poolCoinIndex] = _amount; ICurvePool curvePool = ICurvePool(platformAddress); uint256 assetDecimals = Helpers.getDecimals(_asset); uint256 depositValue = _amount.scaleBy(18, assetDecimals).divPrecisely( curvePool.get_virtual_price() ); uint256 minMintAmount = depositValue.mulTruncate( uint256(1e18) - maxSlippage ); // Do the deposit to pool curvePool.add_liquidity(_amounts, minMintAmount); _lpDepositAll(); } function _lpDepositAll() internal virtual; /** * @dev Deposit the entire balance of any supported asset into the Curve pool */ function depositAll() external override onlyVault nonReentrant { uint256[2] memory _amounts = [uint256(0), uint256(0)]; uint256 depositValue = 0; ICurvePool curvePool = ICurvePool(platformAddress); uint256 curveVirtualPrice = curvePool.get_virtual_price(); for (uint256 i = 0; i < assetsMapped.length; i++) { address assetAddress = assetsMapped[i]; uint256 balance = IERC20(assetAddress).balanceOf(address(this)); if (balance > 0) { uint256 poolCoinIndex = _getCoinIndex(assetAddress); // Set the amount on the asset we want to deposit _amounts[poolCoinIndex] = balance; uint256 assetDecimals = Helpers.getDecimals(assetAddress); // Get value of deposit in Curve LP token to later determine // the minMintAmount argument for add_liquidity depositValue = depositValue + balance.scaleBy(18, assetDecimals).divPrecisely( curveVirtualPrice ); emit Deposit(assetAddress, address(platformAddress), balance); } } uint256 minMintAmount = depositValue.mulTruncate( uint256(1e18) - maxSlippage ); // Do the deposit to pool curvePool.add_liquidity(_amounts, minMintAmount); // Deposit into Gauge, the PToken is the same (USDC/USDCe) for all mapped // assets, so just get the address from the first one _lpDepositAll(); } function _lpWithdraw(uint256 numPTokens) internal virtual; /** * @dev Withdraw asset from Curve Pool * @param _recipient Address to receive withdrawn asset * @param _asset Address of asset to withdraw * @param _amount Amount of asset to withdraw */ function withdraw( address _recipient, address _asset, uint256 _amount ) external override onlyVault nonReentrant { require(_amount > 0, "Invalid amount"); emit Withdrawal(_asset, address(assetToPToken[_asset]), _amount); (uint256 contractPTokens, , uint256 totalPTokens) = _getTotalPTokens(); uint256 coinIndex = _getCoinIndex(_asset); int128 curveCoinIndex = int128(uint128(coinIndex)); // Calculate the max amount of the asset we'd get if we withdrew all the // platform tokens ICurvePool curvePool = ICurvePool(platformAddress); // Calculate how many platform tokens we need to withdraw the asset // amount in the worst case (i.e withdrawing all LP tokens) uint256 maxAmount = curvePool.calc_withdraw_one_coin( totalPTokens, curveCoinIndex ); uint256 maxBurnedPTokens = (totalPTokens * _amount) / maxAmount; // Not enough in this contract or in the Gauge, can't proceed require( totalPTokens > maxBurnedPTokens, "Insufficient USDC-USDCe balance" ); // We have enough LP tokens, make sure they are all on this contract if (contractPTokens < maxBurnedPTokens) { _lpWithdraw(maxBurnedPTokens - contractPTokens); } uint256[2] memory _amounts = [uint256(0), uint256(0)]; _amounts[coinIndex] = _amount; curvePool.remove_liquidity_imbalance(_amounts, maxBurnedPTokens); IERC20(_asset).safeTransfer(_recipient, _amount); } /** * @dev Remove all assets from platform and send them to Vault contract. */ function withdrawAll() external override onlyVaultOrGovernor nonReentrant { // Withdraw all from Gauge (, uint256 gaugePTokens, uint256 totalPTokens) = _getTotalPTokens(); _lpWithdraw(gaugePTokens); // Withdraws are proportional to assets held by Pool uint256[2] memory minWithdrawAmounts = [uint256(0), uint256(0)]; // Remove liquidity ICurvePool curvePool = ICurvePool(platformAddress); curvePool.remove_liquidity(totalPTokens, minWithdrawAmounts); // Transfer assets out of Vault // Note that Curve will provide all of the assets in pool even if // we have not set PToken addresses for all of them in this strategy for (uint256 i = 0; i < assetsMapped.length; i++) { IERC20 asset = IERC20(curvePool.coins(i)); asset.safeTransfer(vaultAddress, asset.balanceOf(address(this))); } } /** * @dev Get the total asset value held in the platform * @param _asset Address of the asset * @return balance Total value of the asset in the platform */ function checkBalance(address _asset) public view override returns (uint256 balance) { require(assetToPToken[_asset] != address(0), "Unsupported asset"); // LP tokens in this contract. This should generally be nothing as we // should always stake the full balance in the Gauge, but include for // safety (, , uint256 totalPTokens) = _getTotalPTokens(); ICurvePool curvePool = ICurvePool(platformAddress); if (totalPTokens > 0) { uint256 virtual_price = curvePool.get_virtual_price(); uint256 value = (totalPTokens * virtual_price) / 1e18; uint256 assetDecimals = Helpers.getDecimals(_asset); balance = value.scaleBy(assetDecimals, 18) / 2; } } /** * @dev Retuns bool indicating whether asset is supported by strategy * @param _asset Address of the asset */ function supportsAsset(address _asset) external view override returns (bool) { return assetToPToken[_asset] != address(0); } /** * @dev Approve the spending of all assets by their corresponding pool tokens, * if for some reason is it necessary. */ function safeApproveAllTokens() external override onlyGovernor nonReentrant { _approveBase(); // This strategy is a special case since it only supports one asset for (uint256 i = 0; i < assetsMapped.length; i++) { _approveAsset(assetsMapped[i]); } } /** * @dev Calculate the total platform token balance (i.e. USDC-USDCe) that exist in * this contract or is staked in the Gauge (or in other words, the total * amount platform tokens we own). * @return contractPTokens Amount of platform tokens in this contract * @return gaugePTokens Amount of platform tokens staked in gauge * @return totalPTokens Total amount of platform tokens in native decimals */ function _getTotalPTokens() internal view virtual returns ( uint256 contractPTokens, uint256 gaugePTokens, uint256 totalPTokens ); /** * @dev Call the necessary approvals for the Curve pool and gauge * @param _asset Address of the asset */ function _abstractSetPToken(address _asset, address _pToken) internal override { _approveAsset(_asset); } function _approveAsset(address _asset) internal { IERC20 asset = IERC20(_asset); // Pool for asset (required for adding liquidity) asset.safeApprove(platformAddress, 0); asset.safeApprove(platformAddress, type(uint256).max); } function _approveBase() internal virtual; /** * @dev Get the index of the coin */ function _getCoinIndex(address _asset) internal view returns (uint256) { for (uint256 i = 0; i < 2; i++) { if (assetsMapped[i] == _asset) return i; } revert("Invalid pool asset"); } }
20,967
2
// Deploys a new gauge for a Balancer pool. As anyone can register arbitrary Balancer pools with the Vault,it's impossible to prove onchain that `pool` is a "valid" deployment. Care must be taken to ensure that gauges deployed from this factory are suitable to distribute rewards. It is possible to deploy multiple gauges for a single pool. pool The address of the pool for which to deploy a gaugereturn The address of the deployed gauge /
function create(address pool) external returns (address) { address gauge = _create(); IChildChainGauge(gauge).initialize(pool, getProductVersion()); return gauge; }
function create(address pool) external returns (address) { address gauge = _create(); IChildChainGauge(gauge).initialize(pool, getProductVersion()); return gauge; }
14,501
69
// Sets the extra data for token `id` to `value`./ Minting, transferring, burning a token will not change the extra data./ The extra data can be set on a non existent token.
function _setExtraData(uint256 id, uint96 value) internal virtual { /// @solidity memory-safe-assembly assembly { mstore(0x00, id) mstore(0x1c, _ERC721_MASTER_SLOT_SEED) let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20))) let packed := sload(ownershipSlot) sstore(ownershipSlot, xor(packed, shl(160, xor(value, shr(160, packed))))) } }
function _setExtraData(uint256 id, uint96 value) internal virtual { /// @solidity memory-safe-assembly assembly { mstore(0x00, id) mstore(0x1c, _ERC721_MASTER_SLOT_SEED) let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20))) let packed := sload(ownershipSlot) sstore(ownershipSlot, xor(packed, shl(160, xor(value, shr(160, packed))))) } }
17,208
38
// skip checks if member is setting the delegate key to their member address
if (newDelegateKey != memberAddr) { require( memberAddresses[newDelegateKey] == address(0x0), "cannot overwrite existing members" ); require( memberAddresses[memberAddressesByDelegatedKey[newDelegateKey]] == address(0x0), "cannot overwrite existing delegate keys" );
if (newDelegateKey != memberAddr) { require( memberAddresses[newDelegateKey] == address(0x0), "cannot overwrite existing members" ); require( memberAddresses[memberAddressesByDelegatedKey[newDelegateKey]] == address(0x0), "cannot overwrite existing delegate keys" );
48,204
23
// Calculate sqrt (x) rounding down.Revert if x < 0.x signed 64.64-bit fixed point numberreturn signed 64.64-bit fixed point number /
function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64, 0x10000000000000000)); }
function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64, 0x10000000000000000)); }
2,497
0
// Stage2( 1525132800,start time 1527811200end time )
public
public
28,504
480
// 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 aviable4) Depositing 0 - not an issue it will just add 0 to tally
function addLiquidity(uint256 amount) public { require(liquidityGenerationOngoing(), "Liquidity Generation Event over"); //require(agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement, "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); require(liquidityGenerationOngoing(), "Liquidity Generation Event over"); require(amount > 0, "Cannot add 0"); aapl.transferFrom(msg.sender,address(this),amount); ethContributed[msg.sender] += amount; totalETHContributed = totalETHContributed.add(amount); emit LiquidityAddition(msg.sender, amount); }
function addLiquidity(uint256 amount) public { require(liquidityGenerationOngoing(), "Liquidity Generation Event over"); //require(agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement, "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); require(liquidityGenerationOngoing(), "Liquidity Generation Event over"); require(amount > 0, "Cannot add 0"); aapl.transferFrom(msg.sender,address(this),amount); ethContributed[msg.sender] += amount; totalETHContributed = totalETHContributed.add(amount); emit LiquidityAddition(msg.sender, amount); }
21,739
74
// Decrease spender balance by the freezed amount.
balances[_spender] = _newBalance;
balances[_spender] = _newBalance;
4,782
147
// Only accept from Etheria contract
require(_msgSender() == _etheriaAddress, "EW09: ETH sender isn't Etheria contract");
require(_msgSender() == _etheriaAddress, "EW09: ETH sender isn't Etheria contract");
48,312
145
// Deposit LP tokens to Chowswap for CHOW allocation.
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accChowPerShare).div(1e12).sub( user.rewardDebt ); safeChowTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); if (chow == address(pool.lpToken)) { lpSupplyOfChowPool = lpSupplyOfChowPool.add(_amount); } user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accChowPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accChowPerShare).div(1e12).sub( user.rewardDebt ); safeChowTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); if (chow == address(pool.lpToken)) { lpSupplyOfChowPool = lpSupplyOfChowPool.add(_amount); } user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accChowPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
21,495
14
// set destination account for handling fees//accountAddress of account receiving the fees/
function setWallet(address account) external ownerOnly { handling_wallet = account; }
function setWallet(address account) external ownerOnly { handling_wallet = account; }
50,070
49
// address saleRecipient = _primarySaleRecipient == address(0) ? primarySaleRecipient() : _primarySaleRecipient;
address saleRecipient = _primarySaleRecipient; CurrencyTransferLib.transferCurrency(_currency, msg.sender, saleRecipient, totalPrice);
address saleRecipient = _primarySaleRecipient; CurrencyTransferLib.transferCurrency(_currency, msg.sender, saleRecipient, totalPrice);
26,402
119
// edge case around reward ending periods
if(newbalance > 0){
if(newbalance > 0){
36,809
8
// passedreturns whether Challenge has passed
function passed() public view returns (bool) { require(ended()); // marketIndex 1 == deniedScalar // if proposal is denied, the challenge has passed. return futarchyOracle.getOutcome() == 1; }
function passed() public view returns (bool) { require(ended()); // marketIndex 1 == deniedScalar // if proposal is denied, the challenge has passed. return futarchyOracle.getOutcome() == 1; }
20,264
1
// Emitted when a set of staked token-ids are withdrawn.
event TokensWithdrawn(address indexed staker, uint256 indexed tokenId, uint256 amount);
event TokensWithdrawn(address indexed staker, uint256 indexed tokenId, uint256 amount);
13,789
41
// filtering if the target is a contract with bytecode inside it
require(super.transfer(_to, _value)); // do a normal token transfer if (isContract(_to)) { require(contractFallback(msg.sender, _to, _value, _data)); }
require(super.transfer(_to, _value)); // do a normal token transfer if (isContract(_to)) { require(contractFallback(msg.sender, _to, _value, _data)); }
34,125
30
// Reduce number of active users and team users
teams[userTeamId].numberUsers = teams[userTeamId].numberUsers.sub(1); numberActiveProfiles = numberActiveProfiles.sub(1);
teams[userTeamId].numberUsers = teams[userTeamId].numberUsers.sub(1); numberActiveProfiles = numberActiveProfiles.sub(1);
22,258
13
// Deploys and returns the address of a clone that mimics the behaviour of `implementation`. This function uses the create opcode, which should never revert. /
function clone(address implementation) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); }
function clone(address implementation) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); }
884
155
// assert that enough liquidity tokens are available to be minted
require(mintableLiquidity > 0, 'INSUFFICIENT_LIQUIDITY_MINTED');
require(mintableLiquidity > 0, 'INSUFFICIENT_LIQUIDITY_MINTED');
60,948
236
// Construct calldata for finalizeDeposit call
bytes memory message = abi.encodeWithSelector( iOVM_L2ERC20Bridge.finalizeDeposit.selector, address(0), Lib_PredeployAddresses.OVM_ETH, _from, _to, msg.value, _data );
bytes memory message = abi.encodeWithSelector( iOVM_L2ERC20Bridge.finalizeDeposit.selector, address(0), Lib_PredeployAddresses.OVM_ETH, _from, _to, msg.value, _data );
56,831
269
// burn tokens sent
_burn(msg.sender, amount); if (amountToWithdraw > currencyBalance()) { removeLiquidityFromCurve(amountToWithdraw.sub(currencyBalance())); require(amountToWithdraw <= currencyBalance(), "TrueFiPool: Not enough funds were withdrawn from Curve"); }
_burn(msg.sender, amount); if (amountToWithdraw > currencyBalance()) { removeLiquidityFromCurve(amountToWithdraw.sub(currencyBalance())); require(amountToWithdraw <= currencyBalance(), "TrueFiPool: Not enough funds were withdrawn from Curve"); }
22,105
65
// Save the new data
lastPricePerShare = _currentPricePerShare; lastVirtualPrice = _currentVirtualPrice;
lastPricePerShare = _currentPricePerShare; lastVirtualPrice = _currentVirtualPrice;
62,779
46
// shouldn&39;t happen, just in case
function emptyWrongEther() onlyOwner public { uint256 amount = address(this).balance; require(amount > 0); msg.sender.transfer(amount); emit WrongEtherEmptied(msg.sender, amount); }
function emptyWrongEther() onlyOwner public { uint256 amount = address(this).balance; require(amount > 0); msg.sender.transfer(amount); emit WrongEtherEmptied(msg.sender, amount); }
51,728
3
// Ownable contract - base contract with an owner /<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f3979685b3809e928187909c9d878192908796929edd909c9e">[email&160;protected]</a>
contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } }
contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } }
42,424
93
// ---------------------------------------------------------------------------- BokkyPooBah's Token Teleportation Service Token v1.10 Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018. The MIT Licence. ----------------------------------------------------------------------------
contract BTTSToken is BTTSTokenInterface { using BTTSLib for BTTSLib.Data; BTTSLib.Data data; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function BTTSToken(address owner, string symbol, string name, uint8 decimals, uint initialSupply, bool mintable, bool transferable) public { data.init(owner, symbol, name, decimals, initialSupply, mintable, transferable); } // ------------------------------------------------------------------------ // Ownership // ------------------------------------------------------------------------ function owner() public view returns (address) { return data.owner; } function newOwner() public view returns (address) { return data.newOwner; } function transferOwnership(address _newOwner) public { data.transferOwnership(_newOwner); } function acceptOwnership() public { data.acceptOwnership(); } function transferOwnershipImmediately(address _newOwner) public { data.transferOwnershipImmediately(_newOwner); } // ------------------------------------------------------------------------ // Token // ------------------------------------------------------------------------ function symbol() public view returns (string) { return data.symbol; } function name() public view returns (string) { return data.name; } function decimals() public view returns (uint8) { return data.decimals; } // ------------------------------------------------------------------------ // Minting and management // ------------------------------------------------------------------------ function minter() public view returns (address) { return data.minter; } function setMinter(address _minter) public { data.setMinter(_minter); } function mint(address tokenOwner, uint tokens, bool lockAccount) public returns (bool success) { return data.mint(tokenOwner, tokens, lockAccount); } function accountLocked(address tokenOwner) public view returns (bool) { return data.accountLocked[tokenOwner]; } function unlockAccount(address tokenOwner) public { data.unlockAccount(tokenOwner); } function mintable() public view returns (bool) { return data.mintable; } function transferable() public view returns (bool) { return data.transferable; } function disableMinting() public { data.disableMinting(); } function enableTransfers() public { data.enableTransfers(); } function nextNonce(address spender) public view returns (uint) { return data.nextNonce[spender]; } // ------------------------------------------------------------------------ // Other functions // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public returns (bool success) { return data.transferAnyERC20Token(tokenAddress, tokens); } // ------------------------------------------------------------------------ // Don't accept ethers // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Token functions // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return data.totalSupply - data.balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return data.balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return data.allowed[tokenOwner][spender]; } function transfer(address to, uint tokens) public returns (bool success) { return data.transfer(to, tokens); } function approve(address spender, uint tokens) public returns (bool success) { return data.approve(spender, tokens); } function transferFrom(address from, address to, uint tokens) public returns (bool success) { return data.transferFrom(from, to, tokens); } function approveAndCall(address spender, uint tokens, bytes _data) public returns (bool success) { return data.approveAndCall(spender, tokens, _data); } // ------------------------------------------------------------------------ // Signed function // ------------------------------------------------------------------------ function signedTransferHash(address tokenOwner, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) { return data.signedTransferHash(tokenOwner, to, tokens, fee, nonce); } function signedTransferCheck(address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public view returns (CheckResult result) { return data.signedTransferCheck(tokenOwner, to, tokens, fee, nonce, sig, feeAccount); } function signedTransfer(address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public returns (bool success) { return data.signedTransfer(tokenOwner, to, tokens, fee, nonce, sig, feeAccount); } function signedApproveHash(address tokenOwner, address spender, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) { return data.signedApproveHash(tokenOwner, spender, tokens, fee, nonce); } function signedApproveCheck(address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public view returns (CheckResult result) { return data.signedApproveCheck(tokenOwner, spender, tokens, fee, nonce, sig, feeAccount); } function signedApprove(address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public returns (bool success) { return data.signedApprove(tokenOwner, spender, tokens, fee, nonce, sig, feeAccount); } function signedTransferFromHash(address spender, address from, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) { return data.signedTransferFromHash(spender, from, to, tokens, fee, nonce); } function signedTransferFromCheck(address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public view returns (CheckResult result) { return data.signedTransferFromCheck(spender, from, to, tokens, fee, nonce, sig, feeAccount); } function signedTransferFrom(address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public returns (bool success) { return data.signedTransferFrom(spender, from, to, tokens, fee, nonce, sig, feeAccount); } function signedApproveAndCallHash(address tokenOwner, address spender, uint tokens, bytes _data, uint fee, uint nonce) public view returns (bytes32 hash) { return data.signedApproveAndCallHash(tokenOwner, spender, tokens, _data, fee, nonce); } function signedApproveAndCallCheck(address tokenOwner, address spender, uint tokens, bytes _data, uint fee, uint nonce, bytes sig, address feeAccount) public view returns (CheckResult result) { return data.signedApproveAndCallCheck(tokenOwner, spender, tokens, _data, fee, nonce, sig, feeAccount); } function signedApproveAndCall(address tokenOwner, address spender, uint tokens, bytes _data, uint fee, uint nonce, bytes sig, address feeAccount) public returns (bool success) { return data.signedApproveAndCall(tokenOwner, spender, tokens, _data, fee, nonce, sig, feeAccount); } }
contract BTTSToken is BTTSTokenInterface { using BTTSLib for BTTSLib.Data; BTTSLib.Data data; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function BTTSToken(address owner, string symbol, string name, uint8 decimals, uint initialSupply, bool mintable, bool transferable) public { data.init(owner, symbol, name, decimals, initialSupply, mintable, transferable); } // ------------------------------------------------------------------------ // Ownership // ------------------------------------------------------------------------ function owner() public view returns (address) { return data.owner; } function newOwner() public view returns (address) { return data.newOwner; } function transferOwnership(address _newOwner) public { data.transferOwnership(_newOwner); } function acceptOwnership() public { data.acceptOwnership(); } function transferOwnershipImmediately(address _newOwner) public { data.transferOwnershipImmediately(_newOwner); } // ------------------------------------------------------------------------ // Token // ------------------------------------------------------------------------ function symbol() public view returns (string) { return data.symbol; } function name() public view returns (string) { return data.name; } function decimals() public view returns (uint8) { return data.decimals; } // ------------------------------------------------------------------------ // Minting and management // ------------------------------------------------------------------------ function minter() public view returns (address) { return data.minter; } function setMinter(address _minter) public { data.setMinter(_minter); } function mint(address tokenOwner, uint tokens, bool lockAccount) public returns (bool success) { return data.mint(tokenOwner, tokens, lockAccount); } function accountLocked(address tokenOwner) public view returns (bool) { return data.accountLocked[tokenOwner]; } function unlockAccount(address tokenOwner) public { data.unlockAccount(tokenOwner); } function mintable() public view returns (bool) { return data.mintable; } function transferable() public view returns (bool) { return data.transferable; } function disableMinting() public { data.disableMinting(); } function enableTransfers() public { data.enableTransfers(); } function nextNonce(address spender) public view returns (uint) { return data.nextNonce[spender]; } // ------------------------------------------------------------------------ // Other functions // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public returns (bool success) { return data.transferAnyERC20Token(tokenAddress, tokens); } // ------------------------------------------------------------------------ // Don't accept ethers // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Token functions // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return data.totalSupply - data.balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return data.balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return data.allowed[tokenOwner][spender]; } function transfer(address to, uint tokens) public returns (bool success) { return data.transfer(to, tokens); } function approve(address spender, uint tokens) public returns (bool success) { return data.approve(spender, tokens); } function transferFrom(address from, address to, uint tokens) public returns (bool success) { return data.transferFrom(from, to, tokens); } function approveAndCall(address spender, uint tokens, bytes _data) public returns (bool success) { return data.approveAndCall(spender, tokens, _data); } // ------------------------------------------------------------------------ // Signed function // ------------------------------------------------------------------------ function signedTransferHash(address tokenOwner, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) { return data.signedTransferHash(tokenOwner, to, tokens, fee, nonce); } function signedTransferCheck(address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public view returns (CheckResult result) { return data.signedTransferCheck(tokenOwner, to, tokens, fee, nonce, sig, feeAccount); } function signedTransfer(address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public returns (bool success) { return data.signedTransfer(tokenOwner, to, tokens, fee, nonce, sig, feeAccount); } function signedApproveHash(address tokenOwner, address spender, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) { return data.signedApproveHash(tokenOwner, spender, tokens, fee, nonce); } function signedApproveCheck(address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public view returns (CheckResult result) { return data.signedApproveCheck(tokenOwner, spender, tokens, fee, nonce, sig, feeAccount); } function signedApprove(address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public returns (bool success) { return data.signedApprove(tokenOwner, spender, tokens, fee, nonce, sig, feeAccount); } function signedTransferFromHash(address spender, address from, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) { return data.signedTransferFromHash(spender, from, to, tokens, fee, nonce); } function signedTransferFromCheck(address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public view returns (CheckResult result) { return data.signedTransferFromCheck(spender, from, to, tokens, fee, nonce, sig, feeAccount); } function signedTransferFrom(address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public returns (bool success) { return data.signedTransferFrom(spender, from, to, tokens, fee, nonce, sig, feeAccount); } function signedApproveAndCallHash(address tokenOwner, address spender, uint tokens, bytes _data, uint fee, uint nonce) public view returns (bytes32 hash) { return data.signedApproveAndCallHash(tokenOwner, spender, tokens, _data, fee, nonce); } function signedApproveAndCallCheck(address tokenOwner, address spender, uint tokens, bytes _data, uint fee, uint nonce, bytes sig, address feeAccount) public view returns (CheckResult result) { return data.signedApproveAndCallCheck(tokenOwner, spender, tokens, _data, fee, nonce, sig, feeAccount); } function signedApproveAndCall(address tokenOwner, address spender, uint tokens, bytes _data, uint fee, uint nonce, bytes sig, address feeAccount) public returns (bool success) { return data.signedApproveAndCall(tokenOwner, spender, tokens, _data, fee, nonce, sig, feeAccount); } }
81,546
258
// Number of items you're guaranteed to get, for each class
uint16[NUM_CLASSES] guarantees;
uint16[NUM_CLASSES] guarantees;
17,022
260
// Retrieves the current pending reward for the MasterChef pool
function _getPendingReward() internal view returns (uint256 _pendingReward)
function _getPendingReward() internal view returns (uint256 _pendingReward)
7,319
70
// Allows drago owner to withdraw from an exchange/_exchange Address of the exchange/_token Address of the withdrawn token (null for eth)/_value Number of tokens deposited (0 for eth)
function withdrawFromExchange(address _exchange, address _token, uint _value) public onlyOwner whenApprovedExchange(_exchange)
function withdrawFromExchange(address _exchange, address _token, uint _value) public onlyOwner whenApprovedExchange(_exchange)
412
380
// views
function calcCurrentPayoutERC20(address user, address token) public view returns (uint256) { uint stakeBlock = erc20Stakes[user][token].setupBlock; require(stakeBlock != 0, "User has no stake"); if ((block.timestamp - erc20Stakes[user][token].setupTime) >= BLOCKTIME_PENALTY_THRESHOLD) { // normal payout if minimum time was reached return (block.number - stakeBlock) * erc20Stakes[user][token].tokenStaked * erc20StakeFactors[token].multi / erc20StakeFactors[token].divi; } else { // 90% payout if minimum time was not reached return (block.number - stakeBlock) * erc20Stakes[user][token].tokenStaked * erc20StakeFactors[token].multi / erc20StakeFactors[token].divi * 9 / 10; } }
function calcCurrentPayoutERC20(address user, address token) public view returns (uint256) { uint stakeBlock = erc20Stakes[user][token].setupBlock; require(stakeBlock != 0, "User has no stake"); if ((block.timestamp - erc20Stakes[user][token].setupTime) >= BLOCKTIME_PENALTY_THRESHOLD) { // normal payout if minimum time was reached return (block.number - stakeBlock) * erc20Stakes[user][token].tokenStaked * erc20StakeFactors[token].multi / erc20StakeFactors[token].divi; } else { // 90% payout if minimum time was not reached return (block.number - stakeBlock) * erc20Stakes[user][token].tokenStaked * erc20StakeFactors[token].multi / erc20StakeFactors[token].divi * 9 / 10; } }
16,172
50
// ico
if (now >= startIco && now < endIco && totalIco < maxIco){ tokens = weiAmount.mul(rateIco); if (maxIco.sub(totalIco) < tokens){ tokens = maxIco.sub(totalIco); weiAmount = tokens.div(rateIco); backAmount = msg.value.sub(weiAmount); }
if (now >= startIco && now < endIco && totalIco < maxIco){ tokens = weiAmount.mul(rateIco); if (maxIco.sub(totalIco) < tokens){ tokens = maxIco.sub(totalIco); weiAmount = tokens.div(rateIco); backAmount = msg.value.sub(weiAmount); }
64,987
35
// See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}. Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for ``sender``'s tokens of at least `amount`./
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; }
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; }
45,027
23
// Not infinities of the same sign
require (x != y || absoluteX < 0x7FFF0000000000000000000000000000); if (x == y) return 0; else { bool negativeX = uint128 (x) >= 0x80000000000000000000000000000000; bool negativeY = uint128 (y) >= 0x80000000000000000000000000000000; if (negativeX) { if (negativeY) return absoluteX > absoluteY ? -1 : int8 (1); else return -1;
require (x != y || absoluteX < 0x7FFF0000000000000000000000000000); if (x == y) return 0; else { bool negativeX = uint128 (x) >= 0x80000000000000000000000000000000; bool negativeY = uint128 (y) >= 0x80000000000000000000000000000000; if (negativeX) { if (negativeY) return absoluteX > absoluteY ? -1 : int8 (1); else return -1;
25,701
52
// contract owner can withdraw any ERC-20 token stuck inside the contract and return them to `walletAddress`
IERC20(_tokenAddress).transfer(walletAddress, IERC20(_tokenAddress).balanceOf(address(this))); emit EmergencyWithdrawActivated(_tokenAddress, IERC20(_tokenAddress).balanceOf(walletAddress));
IERC20(_tokenAddress).transfer(walletAddress, IERC20(_tokenAddress).balanceOf(address(this))); emit EmergencyWithdrawActivated(_tokenAddress, IERC20(_tokenAddress).balanceOf(walletAddress));
41,507
6
// Update the SeaDrop drop URI.Only the owner can use this function.dropURI The new drop URI. /
function updateDropURI(string calldata dropURI) external;
function updateDropURI(string calldata dropURI) external;
14,853
121
// Function for updating account's reward checkpoint.account - address of the account to update the reward checkpoint for./
function updateRewardCheckpoint(address account) external returns (bool);
function updateRewardCheckpoint(address account) external returns (bool);
51,053
8
// State changing functions
function charge(uint256 snapId) onlyAdmin public { uint256 balanceBefore = btcb.balanceOf(address(this)); masterContract.charge(snapId); uint256 balanceAfter = btcb.balanceOf(address(this)); chargedAt[snapId] = balanceAfter - balanceBefore; totalSharesAt[snapId] = totalShares; }
function charge(uint256 snapId) onlyAdmin public { uint256 balanceBefore = btcb.balanceOf(address(this)); masterContract.charge(snapId); uint256 balanceAfter = btcb.balanceOf(address(this)); chargedAt[snapId] = balanceAfter - balanceBefore; totalSharesAt[snapId] = totalShares; }
28,475
27
// The domain separator used in the permit signaturereturn The domain seperator used in encoding of permit signature /
function DOMAIN_SEPARATOR() external view returns (bytes32);
function DOMAIN_SEPARATOR() external view returns (bytes32);
44,805
21
// Ensuring the lottery is within a valid time
require( getCurrentTime() >= allLotteries[_lotteryId].startingTimestamp, "Invalid time for mint:start" ); require( getCurrentTime() < allLotteries[_lotteryId].closingTimestamp, "Invalid time for mint:end" ); if(allLotteries[_lotteryId].lotteryStatus == Status.NotStarted) { if(allLotteries[_lotteryId].startingTimestamp >= getCurrentTime()) {
require( getCurrentTime() >= allLotteries[_lotteryId].startingTimestamp, "Invalid time for mint:start" ); require( getCurrentTime() < allLotteries[_lotteryId].closingTimestamp, "Invalid time for mint:end" ); if(allLotteries[_lotteryId].lotteryStatus == Status.NotStarted) { if(allLotteries[_lotteryId].startingTimestamp >= getCurrentTime()) {
23,447
135
// not enough tokens
if(balance < data.tokensNeededForRefferalNumber) { return; }
if(balance < data.tokensNeededForRefferalNumber) { return; }
10,293
38
// This function makes it easy to get the total number of tokens/ return The total number of tokens
function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); }
function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); }
29,749
11
// Returns agreement status between the two parties
function isSigned(uint agreement_id) public view returns(bool) { return agreements[agreement_id].alice_agreed && agreements[agreement_id].bob_agreed; }
function isSigned(uint agreement_id) public view returns(bool) { return agreements[agreement_id].alice_agreed && agreements[agreement_id].bob_agreed; }
18,603
10
// FromからToに送信する
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool success) { require(_value <= allowed[_from][msg.sender]); _transfer(_from, _to, _value); allowed[_from][msg.sender] -= _value; return true; }
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool success) { require(_value <= allowed[_from][msg.sender]); _transfer(_from, _to, _value); allowed[_from][msg.sender] -= _value; return true; }
9,050
19
// using SafeMath for uint;
address payable public owner;
address payable public owner;
14,956
96
// prevents contracts from interacting with fomo3d/
modifier isHuman() {
modifier isHuman() {
30,586
40
// Requests an update of the ownership of the user representing the repository./ See `requestUpdateOwner` for more details./forge The forge where the repository is stored./name The name of the repository./fee The fee in Link to pay for the request./ return userId The ID of the user.
function _requestUpdateOwner(Forge forge, bytes memory name, uint256 fee) internal returns (uint256 userId)
function _requestUpdateOwner(Forge forge, bytes memory name, uint256 fee) internal returns (uint256 userId)
23,077
301
// ------------------------------------------------------------------------------- PRIVATE FUNCTIONS + ADDITIONAL REQUIREMENTS FOR CONTRACT -------------------------------------------------------------------------------
function DestroyWeapons( address tokenOwner, uint256 tokenId, uint256 totalToBurn
function DestroyWeapons( address tokenOwner, uint256 tokenId, uint256 totalToBurn
16,200
11
// add the sold amount, should not exceed daily limit (checked in DetherCore)
ethSellsUserToday[_from][date.day][date.month][date.year] = SafeMath.add(weiSoldToday, _amount); _to.transfer(_amount);
ethSellsUserToday[_from][date.day][date.month][date.year] = SafeMath.add(weiSoldToday, _amount); _to.transfer(_amount);
25,792
170
// File: contracts\patterns\Proxiable.sol
interface Proxiable { /// @dev Complying with EIP-1822: Universal Upgradable Proxy Standard (UUPS) /// @dev See https://eips.ethereum.org/EIPS/eip-1822. function proxiableUUID() external pure returns (bytes32); }
interface Proxiable { /// @dev Complying with EIP-1822: Universal Upgradable Proxy Standard (UUPS) /// @dev See https://eips.ethereum.org/EIPS/eip-1822. function proxiableUUID() external pure returns (bytes32); }
19,749
9
// set baseURI
function setURI(string memory baseURI_) public onlyOwner { baseURI = baseURI_; }
function setURI(string memory baseURI_) public onlyOwner { baseURI = baseURI_; }
35,027
22
// This internal function is equivalent to {transfer}, and can be used toe.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `from` cannot be the zero address.- `to` cannot be the zero address.- `from` must have a balance of at least `amount`. /
function _transfer(address from, address to, uint256 amount) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount;
function _transfer(address from, address to, uint256 amount) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount;
807
95
// set as marketing wallet
devWallet = 0x5C5Be295AaBb6Be6007b05C8FA8E159605e8856D;
devWallet = 0x5C5Be295AaBb6Be6007b05C8FA8E159605e8856D;
50,995
257
// Function setPresaleActive to activate/desactivate the whitelist/raffle presale/
function setPresaleActive( bool _isActive ) external onlyOwner
function setPresaleActive( bool _isActive ) external onlyOwner
16,656
121
// split & transfer fee for developer
uint developerAccountFee = msg.value / 100 * commission.developer; developerAccount.transfer(developerAccountFee);
uint developerAccountFee = msg.value / 100 * commission.developer; developerAccount.transfer(developerAccountFee);
8,716
37
// Call wrapper that performs `ERC20.permit` on `token`./ Lookup `IERC20.permit`. F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert) if part of a batch this could be used to grief once as the second call would not need the permit
function permitToken( IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s
function permitToken( IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s
32,154
35
// Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend)./
function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; }
function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; }
38
8
// Update transfer fee flag for a given bAsset, should it change its fee practice _bAssetPersonal Basset data storage array _bAssetIndexesMapping of bAsset address to their index _bAsset bAsset address _flag Charge transfer fee when its set to 'true', otherwise 'false' /
function setTransferFeesFlag( BassetPersonal[] storage _bAssetPersonal, mapping(address => uint8) storage _bAssetIndexes, address _bAsset, bool _flag
function setTransferFeesFlag( BassetPersonal[] storage _bAssetPersonal, mapping(address => uint8) storage _bAssetIndexes, address _bAsset, bool _flag
31,824
20
// Update a colony's orbitdb address. Can only be called by a colony with a registered subdomain/orbitdb The path of the orbitDB database to be associated with the colony
function updateColonyOrbitDB(string memory orbitdb) public;
function updateColonyOrbitDB(string memory orbitdb) public;
3,459
11
// Signature signers for the early access stage./Removing signers invalidates the corresponding signatures.
EnumerableSet.AddressSet private _signersEarlyAccess;
EnumerableSet.AddressSet private _signersEarlyAccess;
20,386
209
// Methods for minting LP tokens // Return the amount of sUSD should be minted after depositing bTokenAmount into the pool bTokenAmountNormalized - normalized amount of token to be deposited oldBalance - normalized amount of all tokens before the deposit oldTokenBlance - normalized amount of the balance of the token to be deposited in the pool softWeight - percentage that will incur penalty if the resulting token percentage is greater hardWeight - maximum percentage of the token /
function _getMintAmount( uint256 bTokenAmountNormalized, uint256 oldBalance, uint256 oldTokenBalance, uint256 softWeight, uint256 hardWeight ) internal pure returns (uint256 s)
function _getMintAmount( uint256 bTokenAmountNormalized, uint256 oldBalance, uint256 oldTokenBalance, uint256 softWeight, uint256 hardWeight ) internal pure returns (uint256 s)
79,247
8
// Instantly finalizes a single pool that earned rewards in the previous/epoch, crediting it rewards for members and withdrawing operator's/rewards as WETH. This can be called by internal functions that need/to finalize a pool immediately. Does nothing if the pool is already/finalized or did not earn rewards in the previous epoch./poolId The pool ID to finalize.
function finalizePool(bytes32 poolId) external override
function finalizePool(bytes32 poolId) external override
13,403
136
// LogEvent("StartRefund", token.balanceOf(contributor));
uint256 weiRefunded = vault.refundWhenNotClosed(contributor); weiRaised = weiRaised.sub(weiRefunded); calculateWeiForStage(int256(weiRefunded) * -1); RefundRequestCompleted(contributor, weiRefunded, tokenValance);
uint256 weiRefunded = vault.refundWhenNotClosed(contributor); weiRaised = weiRaised.sub(weiRefunded); calculateWeiForStage(int256(weiRefunded) * -1); RefundRequestCompleted(contributor, weiRefunded, tokenValance);
53,085
17
// Send eventual earned darwin to user
uint amountDarwin = masterChef.darwin().balanceOf(address(this)); if (amountDarwin > 0) { masterChef.darwin().transfer(msg.sender, amountDarwin); }
uint amountDarwin = masterChef.darwin().balanceOf(address(this)); if (amountDarwin > 0) { masterChef.darwin().transfer(msg.sender, amountDarwin); }
1,838
24
// dev Decrease the amount of tokens that an owner allowed to a spender.approve should be called when allowed[_spender] == 0. To decrementallowed value is better to use this function to avoid 2 calls (and wait untilthe first transaction is mined)From MonolithDAO Token.sol _spender The address which will spend the funds. _subtractedValue The amount of tokens to decrease the allowance by. /
function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool)
function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool)
8,209
143
// Users Loans by address
mapping(address => PynthLoanStruct[]) public accountsPynthLoans;
mapping(address => PynthLoanStruct[]) public accountsPynthLoans;
50,045
22
// simulate full execution of a UserOperation (including both validation and target execution)this method will always revert with "ExecutionResult".it performs full validation of the UserOperation, but ignores signature error.an optional target address is called after the userop succeeds, and its value is returned(before the entire call is reverted)Note that in order to collect the the success/failure of the target call, it must be executedwith trace enabled to track the emitted events. op the UserOperation to simulate target if nonzero, a target address to call after userop simulation. If called, the targetSuccess and targetResult are set to the return from that call.
function simulateHandleOp(UserOperation calldata op, address target, bytes calldata targetCallData) external;
function simulateHandleOp(UserOperation calldata op, address target, bytes calldata targetCallData) external;
30,743
49
// Use RSR if needed
if (address(trade.sell) == address(0) && address(trade.buy) != address(0)) { IAsset rsrAsset = components.reg.toAsset(components.rsr); uint192 rsrAvailable = rsrAsset.bal(address(components.trader)).plus( rsrAsset.bal(address(components.stRSR)) ); (, uint192 price_) = rsrAsset.price(true); // {UoA/tok} allow fallback prices
if (address(trade.sell) == address(0) && address(trade.buy) != address(0)) { IAsset rsrAsset = components.reg.toAsset(components.rsr); uint192 rsrAvailable = rsrAsset.bal(address(components.trader)).plus( rsrAsset.bal(address(components.stRSR)) ); (, uint192 price_) = rsrAsset.price(true); // {UoA/tok} allow fallback prices
27,026
111
// ERC1155 can call this method during a post transfer event
require(msg.sender == redeemer || msg.sender == address(this), "Unauthorized caller"); uint256 blockTime = block.timestamp; int256 tokensToRedeem = int256(tokensToRedeem_); AccountContext memory context = AccountContextHandler.getAccountContext(redeemer); if (context.mustSettleAssets()) { context = SettleAssetsExternal.settleAccount(redeemer, context); }
require(msg.sender == redeemer || msg.sender == address(this), "Unauthorized caller"); uint256 blockTime = block.timestamp; int256 tokensToRedeem = int256(tokensToRedeem_); AccountContext memory context = AccountContextHandler.getAccountContext(redeemer); if (context.mustSettleAssets()) { context = SettleAssetsExternal.settleAccount(redeemer, context); }
63,051
241
// Saves the amount to `PendingInterestWithdrawal` storage. /
setStoragePendingInterestWithdrawal( _property, _user, withdrawableAmount
setStoragePendingInterestWithdrawal( _property, _user, withdrawableAmount
10,423
7
// Destructor
function remove() { if (msg.sender == owner){ selfdestruct(owner); } }
function remove() { if (msg.sender == owner){ selfdestruct(owner); } }
40,806
8
// This contract implements a Factory pattern to create player tokens for a specific market / sport/
contract PlayerTokenFactory is Ownable { // numerical id of the market uint32 public market_id; // market name eg football string public market; string public version = "0.1"; // counter used to assign token ids uint32 public lastId = 0; // list of token addresses that have been created address[] public tokenList; // token addresses indexed by their id mapping(uint32 => address) public tokenAddr; event AssetCreated ( address indexed creator, address indexed addr, string symbol, uint balance ); /** * @param _market_id id of the market * @param _market name of the market */ constructor(uint32 _market_id, string memory _market) public { market_id = _market_id; market = _market; } /** * This is needed because there is no way to return an array in a solidity method. * You have to call tokenList(i) to get an element of the array */ function getTokenCount() public view returns(uint) { return tokenList.length; } /** * Creates a new PlayerToken and stores the address in tokenList */ function createToken(uint initialBalance, string memory _name, string memory _symbol) public onlyOwner { lastId++; PlayerToken newToken = new PlayerToken(0, lastId, _symbol, _name, market); newToken.mint(owner, initialBalance); newToken.transferOwnership(owner); tokenList.push(address(newToken)); tokenAddr[lastId] = address(newToken); emit AssetCreated(msg.sender, address(newToken), _symbol, initialBalance); } }
contract PlayerTokenFactory is Ownable { // numerical id of the market uint32 public market_id; // market name eg football string public market; string public version = "0.1"; // counter used to assign token ids uint32 public lastId = 0; // list of token addresses that have been created address[] public tokenList; // token addresses indexed by their id mapping(uint32 => address) public tokenAddr; event AssetCreated ( address indexed creator, address indexed addr, string symbol, uint balance ); /** * @param _market_id id of the market * @param _market name of the market */ constructor(uint32 _market_id, string memory _market) public { market_id = _market_id; market = _market; } /** * This is needed because there is no way to return an array in a solidity method. * You have to call tokenList(i) to get an element of the array */ function getTokenCount() public view returns(uint) { return tokenList.length; } /** * Creates a new PlayerToken and stores the address in tokenList */ function createToken(uint initialBalance, string memory _name, string memory _symbol) public onlyOwner { lastId++; PlayerToken newToken = new PlayerToken(0, lastId, _symbol, _name, market); newToken.mint(owner, initialBalance); newToken.transferOwnership(owner); tokenList.push(address(newToken)); tokenAddr[lastId] = address(newToken); emit AssetCreated(msg.sender, address(newToken), _symbol, initialBalance); } }
20,182
184
// Removes the admin role from an address The sender must have the admin role _address EOA or contract affected /
function removeAdminRole(address _address) external { revokeRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleRemoved(_address, _msgSender()); }
function removeAdminRole(address _address) external { revokeRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleRemoved(_address, _msgSender()); }
51,318
9
// Deal with relative offsets
if (_relative == true) { newCursor += _buffer.cursor; }
if (_relative == true) { newCursor += _buffer.cursor; }
11,836
3
// Emits when a stream is successfully cancelled and tokens are transferred back on a pro rata basis. /
event CancelStream(
event CancelStream(
23,956
28
// Get the token ID for a given tier name
function tokenIdByTier(string memory tierName) public view returns (uint256) { require(tiers[tierName].maxSupply >= 0, "Invalid tier name 2"); return _tokenIdCounter.current() - tiers[tierName].maxSupply + tiers[tierName].minted; }
function tokenIdByTier(string memory tierName) public view returns (uint256) { require(tiers[tierName].maxSupply >= 0, "Invalid tier name 2"); return _tokenIdCounter.current() - tiers[tierName].maxSupply + tiers[tierName].minted; }
3,316
99
// @note: to prevent tokens from ever getting "stuck", this contract can only send to itself in a very specific manner. for example, the "withdrawNative" function will output native fuel to a destination. If it was sent to this contract, this function will trigger and know that the msg.sender is the originating kycContract.
if (msg.sender != address(this)) {
if (msg.sender != address(this)) {
21,852
97
// ----------ADMINISTRATOR ONLY FUNCTIONS----------/
{ //require(buyActived && block.timestamp > ROUND0_MIN_DURATION.add(deployedTime), "too early to disable autoBuy"); autoBuy = !autoBuy; }
{ //require(buyActived && block.timestamp > ROUND0_MIN_DURATION.add(deployedTime), "too early to disable autoBuy"); autoBuy = !autoBuy; }
11,228
55
// if head is zero, this bucket was empty should fill head with expireId
b.head = expireId;
b.head = expireId;
80,891
22
// evaluate sale state based on the internal state variables and return
return nextId <= finalId;
return nextId <= finalId;
403
195
// oracle used for calculating the avgAPR with gov tokens
address public oracle;
address public oracle;
19,600
84
// @ Hilmar: maybe do the same for withdrawal
function _depositAndSell(address sellToken, address buyToken, uint256 amount ) private returns(bool)
function _depositAndSell(address sellToken, address buyToken, uint256 amount ) private returns(bool)
28,719
94
// Users most often claim rewards within the same index which can last several months.
endIndex = i - 1; break;
endIndex = i - 1; break;
2,383
3
// Contract responsible for creating metadata from seeds. // /
bool public parametersLocked = false;
bool public parametersLocked = false;
49,517
0
// router address
address public router;
address public router;
44,900
335
// Compound's CCompLikeDelegate Contract CTokens which can 'delegate votes' of their underlying ERC-20 Compound /
contract CCompLikeDelegate is CErc20Delegate { /** * @notice Construct an empty delegate */ constructor() public CErc20Delegate() {} /** * @notice Admin call to delegate the votes of the COMP-like underlying * @param compLikeDelegatee The address to delegate votes to */ function _delegateCompLikeTo(address compLikeDelegatee) external { require(msg.sender == admin, "only the admin may set the comp-like delegate"); CompLike(underlying).delegate(compLikeDelegatee); } }
contract CCompLikeDelegate is CErc20Delegate { /** * @notice Construct an empty delegate */ constructor() public CErc20Delegate() {} /** * @notice Admin call to delegate the votes of the COMP-like underlying * @param compLikeDelegatee The address to delegate votes to */ function _delegateCompLikeTo(address compLikeDelegatee) external { require(msg.sender == admin, "only the admin may set the comp-like delegate"); CompLike(underlying).delegate(compLikeDelegatee); } }
16,150
13
// DEX/ pontus-dev.eth/ DEX.sol with the outline of the coming features/ We want to create an automatic market where our contract will hold reserves of both ETH and 🎈 Balloons. These reserves will provide liquidity that allows anyone to swap between the assets.
contract DEX { IERC20 token; uint256 public totalLiquidity; mapping(address => uint256) public liquidity; ///@notice Emitted when ethToToken() swap transacted event EthToTokenSwap(); ///@notice Emitted when tokenToEth() swap transacted event TokenToEthSwap(); ///@notice Emitted when liquidity provided to DEX and mints LPTs. event LiquidityProvided(); ///@notice Emitted when liquidity removed from DEX and decreases LPT count within DEX. event LiquidityRemoved(); constructor(address token_addr) { token = IERC20(token_addr); //specifies the token address that will hook into the interface and be used through the variable 'token' } ///@notice initializes amount of tokens that will be transferred to the DEX itself from the erc20 contract mintee (and only them based on how Balloons.sol is written). Loads contract up with both ETH and Balloons. ///@param tokens amount to be transferred to DEX ///@return totalLiquidity is the number of LPTs minting as a result of deposits made to DEX contract ///NOTE: since ratio is 1:1, this is fine to initialize the totalLiquidity (wrt to balloons) as equal to eth balance of contract. function init(uint256 tokens) public payable returns (uint256) { require(totalLiquidity == 0, "Dex is already initialized. You cannot initialize more than once"); totalLiquidity = address(this).balance; liquidity[msg.sender] = totalLiquidity; require(token.transferFrom(msg.sender, address(this), tokens)); return totalLiquidity; } ///@notice returns yOutput, or yDelta for xInput (or xDelta) ///@dev Follow along with the [original tutorial](https://medium.com/@austin_48503/%EF%B8%8F-minimum-viable-exchange-d84f30bd0c90) Price section for an understanding of the DEX's pricing model and for a price function to add to your contract. You may need to update the Solidity syntax (e.g. use + instead of .add, * instead of .mul, etc). Deploy when you are done. function price( uint256 input_amount, uint256 input_reserve, uint256 output_reserve ) public view returns (uint256) { uint256 input_amount_with_fee = input_amount * 997; uint256 numerator = input_amount_with_fee * output_reserve; uint256 denominator = input_reserve * 1000 + input_amount_with_fee; return numerator / denominator; } ///@notice returns liquidity for a user. Note this is not needed typically due to the `liquidity()` mapping variable being public and having a getter as a result. This is left though as it is used within the front end code (App.jsx). function getLiquidity(address lp) public view returns (uint256) { return liquidity[lp]; } ///@notice sends Ether to DEX in exchange for $BAL function ethToToken() public payable returns (uint256) { uint256 token_reserve = token.balanceOf(address(this)); uint256 tokens_bought = price(msg.value, address(this).balance - msg.value, token_reserve); require(token.transfer(msg.sender, tokens_bought)); return tokens_bought; } ///@notice sends $BAL tokens to DEX in exchange for Ether function tokenToEth(uint256 tokens) public returns (uint256) { uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_bought = price(tokens, token_reserve, address(this).balance); payable(msg.sender).transfer(eth_bought); require(token.transferFrom(msg.sender, address(this), tokens)); return eth_bought; } ///@notice allows deposits of $BAL and $ETH to liquidity pool ///NOTE: parameter is the msg.value sent with this function call. That amount is used to determine the amount of $BAL needed as well and taken from the depositor. ///NOTE: user has to make sure to give DEX approval to spend their tokens on their behalf by calling approve function prior to this function call. ///NOTE: Equal parts of both assets will be removed from the user's wallet with respect to the price outlined by the AMM. function deposit() public payable returns (uint256) { uint256 eth_reserve = address(this).balance - msg.value; uint256 token_reserve = token.balanceOf(address(this)); uint256 token_amount = ((msg.value * token_reserve) / eth_reserve) + 1; uint256 liquidity_minted = (msg.value * totalLiquidity) / eth_reserve; liquidity[msg.sender] = liquidity[msg.sender] + liquidity_minted; totalLiquidity = totalLiquidity + liquidity_minted; require(token.transferFrom(msg.sender, address(this), token_amount)); return liquidity_minted; } ///@notice allows withdrawal of $BAL and $ETH from liquidity pool ///NOTE: with this current code, the msg caller could end up getting very little back if the liquidity is super low in the pool. I guess they could see that with the UI. function withdraw(uint256 amount) public returns (uint256, uint256) { uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_amount = (amount * address(this).balance) / totalLiquidity; uint256 token_amount = (amount * token_reserve) / totalLiquidity; liquidity[msg.sender] = liquidity[msg.sender] - eth_amount; totalLiquidity = totalLiquidity - eth_amount; payable(msg.sender).transfer(eth_amount); require(token.transfer(msg.sender, token_amount)); return (eth_amount, token_amount); } }
contract DEX { IERC20 token; uint256 public totalLiquidity; mapping(address => uint256) public liquidity; ///@notice Emitted when ethToToken() swap transacted event EthToTokenSwap(); ///@notice Emitted when tokenToEth() swap transacted event TokenToEthSwap(); ///@notice Emitted when liquidity provided to DEX and mints LPTs. event LiquidityProvided(); ///@notice Emitted when liquidity removed from DEX and decreases LPT count within DEX. event LiquidityRemoved(); constructor(address token_addr) { token = IERC20(token_addr); //specifies the token address that will hook into the interface and be used through the variable 'token' } ///@notice initializes amount of tokens that will be transferred to the DEX itself from the erc20 contract mintee (and only them based on how Balloons.sol is written). Loads contract up with both ETH and Balloons. ///@param tokens amount to be transferred to DEX ///@return totalLiquidity is the number of LPTs minting as a result of deposits made to DEX contract ///NOTE: since ratio is 1:1, this is fine to initialize the totalLiquidity (wrt to balloons) as equal to eth balance of contract. function init(uint256 tokens) public payable returns (uint256) { require(totalLiquidity == 0, "Dex is already initialized. You cannot initialize more than once"); totalLiquidity = address(this).balance; liquidity[msg.sender] = totalLiquidity; require(token.transferFrom(msg.sender, address(this), tokens)); return totalLiquidity; } ///@notice returns yOutput, or yDelta for xInput (or xDelta) ///@dev Follow along with the [original tutorial](https://medium.com/@austin_48503/%EF%B8%8F-minimum-viable-exchange-d84f30bd0c90) Price section for an understanding of the DEX's pricing model and for a price function to add to your contract. You may need to update the Solidity syntax (e.g. use + instead of .add, * instead of .mul, etc). Deploy when you are done. function price( uint256 input_amount, uint256 input_reserve, uint256 output_reserve ) public view returns (uint256) { uint256 input_amount_with_fee = input_amount * 997; uint256 numerator = input_amount_with_fee * output_reserve; uint256 denominator = input_reserve * 1000 + input_amount_with_fee; return numerator / denominator; } ///@notice returns liquidity for a user. Note this is not needed typically due to the `liquidity()` mapping variable being public and having a getter as a result. This is left though as it is used within the front end code (App.jsx). function getLiquidity(address lp) public view returns (uint256) { return liquidity[lp]; } ///@notice sends Ether to DEX in exchange for $BAL function ethToToken() public payable returns (uint256) { uint256 token_reserve = token.balanceOf(address(this)); uint256 tokens_bought = price(msg.value, address(this).balance - msg.value, token_reserve); require(token.transfer(msg.sender, tokens_bought)); return tokens_bought; } ///@notice sends $BAL tokens to DEX in exchange for Ether function tokenToEth(uint256 tokens) public returns (uint256) { uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_bought = price(tokens, token_reserve, address(this).balance); payable(msg.sender).transfer(eth_bought); require(token.transferFrom(msg.sender, address(this), tokens)); return eth_bought; } ///@notice allows deposits of $BAL and $ETH to liquidity pool ///NOTE: parameter is the msg.value sent with this function call. That amount is used to determine the amount of $BAL needed as well and taken from the depositor. ///NOTE: user has to make sure to give DEX approval to spend their tokens on their behalf by calling approve function prior to this function call. ///NOTE: Equal parts of both assets will be removed from the user's wallet with respect to the price outlined by the AMM. function deposit() public payable returns (uint256) { uint256 eth_reserve = address(this).balance - msg.value; uint256 token_reserve = token.balanceOf(address(this)); uint256 token_amount = ((msg.value * token_reserve) / eth_reserve) + 1; uint256 liquidity_minted = (msg.value * totalLiquidity) / eth_reserve; liquidity[msg.sender] = liquidity[msg.sender] + liquidity_minted; totalLiquidity = totalLiquidity + liquidity_minted; require(token.transferFrom(msg.sender, address(this), token_amount)); return liquidity_minted; } ///@notice allows withdrawal of $BAL and $ETH from liquidity pool ///NOTE: with this current code, the msg caller could end up getting very little back if the liquidity is super low in the pool. I guess they could see that with the UI. function withdraw(uint256 amount) public returns (uint256, uint256) { uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_amount = (amount * address(this).balance) / totalLiquidity; uint256 token_amount = (amount * token_reserve) / totalLiquidity; liquidity[msg.sender] = liquidity[msg.sender] - eth_amount; totalLiquidity = totalLiquidity - eth_amount; payable(msg.sender).transfer(eth_amount); require(token.transfer(msg.sender, token_amount)); return (eth_amount, token_amount); } }
41,429
17
// TODO: check this. I thought this was already implemented by th.
function onERC721Received( address, address, uint256, bytes calldata
function onERC721Received( address, address, uint256, bytes calldata
13,135
73
// Different amounts to charge as a fee for each protocol.
uint256[] public feePerBase;
uint256[] public feePerBase;
27,435
6
// Send _value amount of tokens from address _from to address _to
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
55,337
1
// Reference to the `CoreBorrow` contract managing the FlashLoan module
function core() external view returns (ICoreBorrow);
function core() external view returns (ICoreBorrow);
18,235
235
// Add a PublicLock template to be used for future calls to `createLock`. This is used to upgrade conytract per version number /
function addLockTemplate(address impl, uint16 version) external;
function addLockTemplate(address impl, uint16 version) external;
16,770
10
// check that the signature is from the matching engine
return recoverSigner(tradeHash, signature) == _matchingEngine;
return recoverSigner(tradeHash, signature) == _matchingEngine;
48,945
9
// map every staked snake ID to reward claimed
mapping(uint => uint) stakedSnakeToRewardPaid;
mapping(uint => uint) stakedSnakeToRewardPaid;
76,479
0
// Constructs the TestnetERC20. _name The name which describes the new token. _symbol The ticker abbreviation of the name. Ideally < 5 chars. _decimals The number of decimals to define token precision. /
constructor( string memory _name, string memory _symbol, uint8 _decimals
constructor( string memory _name, string memory _symbol, uint8 _decimals
30,044
3
// Initialize IStakedTokenIncentivesController _provider the address of the corresponding addresses provider /
function initialize(ILendingPoolAddressesProvider _provider) external initializer { _addressProvider = _provider; }
function initialize(ILendingPoolAddressesProvider _provider) external initializer { _addressProvider = _provider; }
31,080
58
// Function to convert Set Tokens held in vault into underlying components_setThe address of the Set token _quantity The number of tokens to redeem. Should be multiple of natural unit. /
function redeemInVault(
function redeemInVault(
6,999
208
// isStableBorrowRateEnabled = true means users can borrow at a stable rate
bool isStableBorrowRateEnabled;
bool isStableBorrowRateEnabled;
6,871