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
36
// Returns the total amount of tokens minted in the contract. /
function _totalMinted() internal view virtual returns (uint256) { // Counter underflow is impossible as `_currentIndex` does not decrement, // and it is initialized to `_startTokenId()`. unchecked { return _currentIndex - _startTokenId(); } }
function _totalMinted() internal view virtual returns (uint256) { // Counter underflow is impossible as `_currentIndex` does not decrement, // and it is initialized to `_startTokenId()`. unchecked { return _currentIndex - _startTokenId(); } }
1,157
2
// Constant values used in ramping A calculations
uint256 private constant A_PRECISION = 100;
uint256 private constant A_PRECISION = 100;
624
46
// Fires on every unfreeze of tokens_owner address The owner address of unfrozen tokens.amount uint256 The amount of tokens unfrozen /
event TokenUnfreezeEvent(address indexed _owner, uint256 amount); event TokensBurned(address indexed _owner, uint256 _tokens); mapping(address => uint256) internal frozenTokenBalances;
event TokenUnfreezeEvent(address indexed _owner, uint256 amount); event TokensBurned(address indexed _owner, uint256 _tokens); mapping(address => uint256) internal frozenTokenBalances;
51,317
0
// At the core virtualgold is just a data record that is linked to each holders wallet address which stores the amount amount of virtualgold held by each of one them. The value of your virtualgold is always backed by ethereum in this smart contract.
virtualGoldTeam=0xd98F9E1191Ac53B1Af3E7A09Af53E08755B3DE9a; //This is the wallet address of the virtualgold team virtualGoldPrice = 0.000000001 ether; //This is the starting price of virtualgold per microgram. This value keeps increasing after every investment/virtualgold purchase. This value can never depreciate. total = 0; //The total quantity of virtualgold owned by everyone when the contract is deployed is 0
virtualGoldTeam=0xd98F9E1191Ac53B1Af3E7A09Af53E08755B3DE9a; //This is the wallet address of the virtualgold team virtualGoldPrice = 0.000000001 ether; //This is the starting price of virtualgold per microgram. This value keeps increasing after every investment/virtualgold purchase. This value can never depreciate. total = 0; //The total quantity of virtualgold owned by everyone when the contract is deployed is 0
41,278
35
// blocking the reception of a standard coin of network
receive() external payable { require(false, "The contract does not accept the base coin of network."); }
receive() external payable { require(false, "The contract does not accept the base coin of network."); }
10,947
108
// external token transfer_externalToken the token contract_to the destination address_value the amount of tokens to transfer return bool which represents success/
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value) public onlyOwner returns(bool)
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value) public onlyOwner returns(bool)
6,530
15
// Objects balances
mapping (address => mapping(uint256 => uint256)) internal balances;
mapping (address => mapping(uint256 => uint256)) internal balances;
50,947
528
// If using the last_order_id_twamm and it is expired, clear the pending order indicator
if (is_expired && (order_id_override == 0)) pending_twamm_order = false;
if (is_expired && (order_id_override == 0)) pending_twamm_order = false;
37,381
63
// calculate your rewards
function calculateReward(address userAddress) public view returns (uint256 _reward, uint256 _tax) { uint256 cycleStartTime = government.getCycleStartTime(); uint256 amount = 0; uint256 ris3Amount = getUserBalance(userAddress); uint256 percnt = ris3Amount.mul(100000000); // to get percent till 8 decimal places if (percnt != 0 ) { percnt = percnt.div(totalLiquidity); } (uint256 taxRates, uint256 totalRewards, string memory taxPoolUses) = government.getCurrentLaws(); uint256 diff = 0; uint256 govElectionStartTime = government.getGovElectionStartTime(); //rewards can be calculated after staking done only if (now < government.getWithdrawingStartTime() || userRewardInfo[userAddress].lastWithdrawTime >= govElectionStartTime || percnt == 0){ return ( 0, 0 ); } else { //if not withdrawn on current cycle yet if (userRewardInfo[userAddress].lastWithdrawTime < cycleStartTime) { if (now < govElectionStartTime) { diff = now - government.getWithdrawingStartTime(); } else { diff = govElectionStartTime - government.getWithdrawingStartTime(); } } else { if (now < govElectionStartTime) { diff = now - userRewardInfo[userAddress].lastWithdrawTime; } else { diff = govElectionStartTime - userRewardInfo[userAddress].lastWithdrawTime; } } uint256 rewardsEverySecond = totalRewards / 5 / 24 / 60 / 60; //get rewards every second uint256 userRewardPerSecond = rewardsEverySecond.mul(percnt); userRewardPerSecond = userRewardPerSecond.div(100000000); amount = userRewardPerSecond.mul(diff); uint256 tax = amount.mul(taxRates); tax = tax.div(100); return (amount - tax, tax); } }
function calculateReward(address userAddress) public view returns (uint256 _reward, uint256 _tax) { uint256 cycleStartTime = government.getCycleStartTime(); uint256 amount = 0; uint256 ris3Amount = getUserBalance(userAddress); uint256 percnt = ris3Amount.mul(100000000); // to get percent till 8 decimal places if (percnt != 0 ) { percnt = percnt.div(totalLiquidity); } (uint256 taxRates, uint256 totalRewards, string memory taxPoolUses) = government.getCurrentLaws(); uint256 diff = 0; uint256 govElectionStartTime = government.getGovElectionStartTime(); //rewards can be calculated after staking done only if (now < government.getWithdrawingStartTime() || userRewardInfo[userAddress].lastWithdrawTime >= govElectionStartTime || percnt == 0){ return ( 0, 0 ); } else { //if not withdrawn on current cycle yet if (userRewardInfo[userAddress].lastWithdrawTime < cycleStartTime) { if (now < govElectionStartTime) { diff = now - government.getWithdrawingStartTime(); } else { diff = govElectionStartTime - government.getWithdrawingStartTime(); } } else { if (now < govElectionStartTime) { diff = now - userRewardInfo[userAddress].lastWithdrawTime; } else { diff = govElectionStartTime - userRewardInfo[userAddress].lastWithdrawTime; } } uint256 rewardsEverySecond = totalRewards / 5 / 24 / 60 / 60; //get rewards every second uint256 userRewardPerSecond = rewardsEverySecond.mul(percnt); userRewardPerSecond = userRewardPerSecond.div(100000000); amount = userRewardPerSecond.mul(diff); uint256 tax = amount.mul(taxRates); tax = tax.div(100); return (amount - tax, tax); } }
1,466
11
// rebaseFeeRate must be a number between 1 and 99 (in 18 decimal)
require(newRebaseFeeRate < (100 ether) && newRebaseFeeRate > (0 ether), "New rebase fee rate out of range"); emit ParameterChange("rebaseFeeRate", newRebaseFeeRate, _rebaseFeeRate); _rebaseFeeRate = newRebaseFeeRate;
require(newRebaseFeeRate < (100 ether) && newRebaseFeeRate > (0 ether), "New rebase fee rate out of range"); emit ParameterChange("rebaseFeeRate", newRebaseFeeRate, _rebaseFeeRate); _rebaseFeeRate = newRebaseFeeRate;
23,293
33
// This value is only used as the check below which currently never reverts uint16 versionMinor = UnsafeBytesLib.toUint16(encoded, index);
index += 2;
index += 2;
25,471
29
// Calculate the square root of the perfect square of a power of two that is the closest to x.
uint xAux = uint(x); result = 1; if (xAux >= 0x100000000000000000000000000000000) { xAux >>= 128; result <<= 64; }
uint xAux = uint(x); result = 1; if (xAux >= 0x100000000000000000000000000000000) { xAux >>= 128; result <<= 64; }
15,942
382
// discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)](Oracle price for the collateral / Oracle price for the borrow)return Return values are expressed in 1e18 scale /
function calculateDiscountedBorrowDenominatedCollateral( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 supplyCurrent_TargetCollateralAsset
function calculateDiscountedBorrowDenominatedCollateral( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 supplyCurrent_TargetCollateralAsset
17,568
31
// Owner can allow transfers for a particular address. Use for crowdsale contract.
function setTransferAdmin(address _addr, bool _canTransfer) onlyOwner public { transferAdmins[_addr] = _canTransfer; }
function setTransferAdmin(address _addr, bool _canTransfer) onlyOwner public { transferAdmins[_addr] = _canTransfer; }
45,093
277
// Allows users to deposit tokens and burn them in order to protect them from debasing. amount The amount of tokens to deposit and burn. The deposited tokens are burned, reducing the total supply of tokens in circulation. The user's deposit amount is recorded, and the tokens are locked for a period of time, after which the user can withdraw them.Requirements:- The amount must be greater than 0.- The user must not be excluded from debase in order to make a deposit.
* @dev Emits a {Deposit} event with the user's address and deposit amount. */ function deposit(uint amount) external { require(amount > 0, "zero amount"); require(!isExcludedFromDebase[msg.sender], "excluded from debase"); Depositor storage depositor = depositors[msg.sender]; depositor.lockEndsAt = block.timestamp + lockDuration; _burn(msg.sender, amount); totalDeposited += amount; depositor.amount += amount; emit Deposit(msg.sender, amount); }
* @dev Emits a {Deposit} event with the user's address and deposit amount. */ function deposit(uint amount) external { require(amount > 0, "zero amount"); require(!isExcludedFromDebase[msg.sender], "excluded from debase"); Depositor storage depositor = depositors[msg.sender]; depositor.lockEndsAt = block.timestamp + lockDuration; _burn(msg.sender, amount); totalDeposited += amount; depositor.amount += amount; emit Deposit(msg.sender, amount); }
36,136
1
// key : auth, value : duration (blocks)
mapping(address => uint256) internal _authorized_duration;
mapping(address => uint256) internal _authorized_duration;
9,963
52
// Provides information about the current execution context, including thesender of the transaction and its data. While these are generally availablevia msg.sender and msg.data, they should not be accessed in such a directmanner, since when dealing with meta-transactions the account sending andpaying for execution may not be the actual sender (as far as an applicationis concerned). This contract is only required for intermediate, library-like contracts. /
abstract contract Context { function _msgSender() internal view virtual returns(address) { return msg.sender; } function _msgData() internal view virtual returns(bytes calldata) { return msg.data; } }
abstract contract Context { function _msgSender() internal view virtual returns(address) { return msg.sender; } function _msgData() internal view virtual returns(bytes calldata) { return msg.data; } }
26,144
1
// Calculates and returns 'self - other' The function will throw if the operation would result in an underflow.
function exactSub(uint self, uint other) internal pure returns (uint diff) { require(other <= self); diff = self - other; }
function exactSub(uint self, uint other) internal pure returns (uint diff) { require(other <= self); diff = self - other; }
22,876
501
// close on this chain
_closeSecondary(snxBackedDebt, debtSharesSupply);
_closeSecondary(snxBackedDebt, debtSharesSupply);
34,233
149
// Root updaters can update the root
function _onlyRootUpdater() internal view { require(hasRole(ROOT_UPDATER_ROLE, msg.sender), "onlyRootUpdater"); }
function _onlyRootUpdater() internal view { require(hasRole(ROOT_UPDATER_ROLE, msg.sender), "onlyRootUpdater"); }
1,855
19
// If over vesting duration, all tokens vested
if (elapsedYears >= tokenGrant.vestingDuration) { uint256 remainingGrant = tokenGrant.amount.sub(tokenGrant.totalClaimed); uint256 remainingYears = tokenGrant.vestingDuration.sub(tokenGrant.yearsClaimed); return (remainingYears, remainingGrant); } else {
if (elapsedYears >= tokenGrant.vestingDuration) { uint256 remainingGrant = tokenGrant.amount.sub(tokenGrant.totalClaimed); uint256 remainingYears = tokenGrant.vestingDuration.sub(tokenGrant.yearsClaimed); return (remainingYears, remainingGrant); } else {
372
41
// _niftyRegistryContract Points to the repository of authenticated/
constructor(address _niftyRegistryContract) { niftyRegistryContract = _niftyRegistryContract; }
constructor(address _niftyRegistryContract) { niftyRegistryContract = _niftyRegistryContract; }
15,955
189
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
return string(abi.encodePacked(base, tokenId.toString()));
47,391
72
// If applicable, set the last pause time.
if (paused) { lastPauseTime = now; }
if (paused) { lastPauseTime = now; }
133
33
// force reserves to match balances
function sync() external override nonReentrant { _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1); }
function sync() external override nonReentrant { _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1); }
45,440
7
// TokenStorage External storage for tokens.The storage is implemented in a separate contract to maintain statebetween token upgrades. /
contract TokenStorage is Claimable, CanReclaimToken, NoOwner { using TokenStorageLib for TokenStorageLib.TokenStorage; TokenStorageLib.TokenStorage internal tokenStorage; /** * @dev Increases balance of an address. * @param to Address to increase. * @param amount Number of units to add. */ function addBalance(address to, uint amount) external onlyOwner { tokenStorage.addBalance(to, amount); } /** * @dev Decreases balance of an address. * @param from Address to decrease. * @param amount Number of units to subtract. */ function subBalance(address from, uint amount) external onlyOwner { tokenStorage.subBalance(from, amount); } /** * @dev Sets the allowance for a spender. * @param owner Address of the owner of the tokens to spend. * @param spender Address of the spender. * @param amount Qunatity of allowance. */ function setAllowed(address owner, address spender, uint amount) external onlyOwner { tokenStorage.setAllowed(owner, spender, amount); } /** * @dev Returns the supply of tokens. * @return Total supply. */ function getSupply() external view returns (uint) { return tokenStorage.getSupply(); } /** * @dev Returns the balance of an address. * @param who Address to lookup. * @return Number of units. */ function getBalance(address who) external view returns (uint) { return tokenStorage.getBalance(who); } /** * @dev Returns the allowance for a spender. * @param owner Address of the owner of the tokens to spend. * @param spender Address of the spender. * @return Number of units. */ function getAllowed(address owner, address spender) external view returns (uint) { return tokenStorage.getAllowed(owner, spender); } }
contract TokenStorage is Claimable, CanReclaimToken, NoOwner { using TokenStorageLib for TokenStorageLib.TokenStorage; TokenStorageLib.TokenStorage internal tokenStorage; /** * @dev Increases balance of an address. * @param to Address to increase. * @param amount Number of units to add. */ function addBalance(address to, uint amount) external onlyOwner { tokenStorage.addBalance(to, amount); } /** * @dev Decreases balance of an address. * @param from Address to decrease. * @param amount Number of units to subtract. */ function subBalance(address from, uint amount) external onlyOwner { tokenStorage.subBalance(from, amount); } /** * @dev Sets the allowance for a spender. * @param owner Address of the owner of the tokens to spend. * @param spender Address of the spender. * @param amount Qunatity of allowance. */ function setAllowed(address owner, address spender, uint amount) external onlyOwner { tokenStorage.setAllowed(owner, spender, amount); } /** * @dev Returns the supply of tokens. * @return Total supply. */ function getSupply() external view returns (uint) { return tokenStorage.getSupply(); } /** * @dev Returns the balance of an address. * @param who Address to lookup. * @return Number of units. */ function getBalance(address who) external view returns (uint) { return tokenStorage.getBalance(who); } /** * @dev Returns the allowance for a spender. * @param owner Address of the owner of the tokens to spend. * @param spender Address of the spender. * @return Number of units. */ function getAllowed(address owner, address spender) external view returns (uint) { return tokenStorage.getAllowed(owner, spender); } }
13,665
4
// create the pair if it doesn't exist yet
if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) { IUniswapV2Factory(factory).createPair(tokenA, tokenB); }
if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) { IUniswapV2Factory(factory).createPair(tokenA, tokenB); }
26,929
169
// calculate the referrer amount
search.currentReferrerAmount = search.currentLevelDiff * search.levelDiffAmountPerLevel;
search.currentReferrerAmount = search.currentLevelDiff * search.levelDiffAmountPerLevel;
26,764
133
// index Index of transaction to remove. Transaction ordering may have changed since adding. /
function removeTransaction(uint index) external onlyOwner
function removeTransaction(uint index) external onlyOwner
21,427
92
// Credit auctionner balance
pendingWithdrawals[_auctioneer] += auctioneerCut; return true;
pendingWithdrawals[_auctioneer] += auctioneerCut; return true;
7,790
1
// exposing the safe mint functionality
function safeMint(address to, uint256 tokenId) public { require(msg.sender == owner, "NFTBase: Only owner can mint"); _safeMint(to, tokenId); }
function safeMint(address to, uint256 tokenId) public { require(msg.sender == owner, "NFTBase: Only owner can mint"); _safeMint(to, tokenId); }
11,226
76
// Mapping containing which addresses are whitelisted/
mapping (address => bool) public whitelist;
mapping (address => bool) public whitelist;
7,005
223
// Staking State View Functions /
{ require(tokenId <= tokenIdCounter, "not existent"); StakingInfo storage stakingInfo = stakingInfos[tokenId]; if (stakingInfo.unstakeTime > 0) { return 0; } StakingPlan storage stakingPlan = stakingPlans[stakingInfo.stakingPlan]; // calculate compounded rewards of QLT uint256 stakedAmountX96 = stakingInfo.stakedAmount * Q96; uint256 compoundedAmountX96 = stakedAmountX96; uint64 rewardEndTime = Time.current_hour_timestamp(); uint64 lastHarvestTime = stakingInfo.lastHarvestTime; StakingRewardRate[] storage rewardRates = stakingPlan.rewardRates; uint256 i = rewardRates.length; while (i > 0) { i--; uint64 rewardStartTime = rewardRates[i].startTime; uint256 rewardRateX96 = rewardRates[i].rewardRateX96; uint256 nCompounds; if (rewardEndTime < rewardStartTime) { continue; } if (rewardStartTime >= lastHarvestTime) { nCompounds = (rewardEndTime - rewardStartTime) / 1 hours; compoundedAmountX96 = compoundedAmountX96.mulX96( Math.compound(rewardRateX96, nCompounds) ); rewardEndTime = rewardStartTime; } else { nCompounds = (rewardEndTime - lastHarvestTime) / 1 hours; compoundedAmountX96 = compoundedAmountX96.mulX96( Math.compound(rewardRateX96, nCompounds) ); break; } } rewardAmount = (compoundedAmountX96 - stakedAmountX96) / Q96; }
{ require(tokenId <= tokenIdCounter, "not existent"); StakingInfo storage stakingInfo = stakingInfos[tokenId]; if (stakingInfo.unstakeTime > 0) { return 0; } StakingPlan storage stakingPlan = stakingPlans[stakingInfo.stakingPlan]; // calculate compounded rewards of QLT uint256 stakedAmountX96 = stakingInfo.stakedAmount * Q96; uint256 compoundedAmountX96 = stakedAmountX96; uint64 rewardEndTime = Time.current_hour_timestamp(); uint64 lastHarvestTime = stakingInfo.lastHarvestTime; StakingRewardRate[] storage rewardRates = stakingPlan.rewardRates; uint256 i = rewardRates.length; while (i > 0) { i--; uint64 rewardStartTime = rewardRates[i].startTime; uint256 rewardRateX96 = rewardRates[i].rewardRateX96; uint256 nCompounds; if (rewardEndTime < rewardStartTime) { continue; } if (rewardStartTime >= lastHarvestTime) { nCompounds = (rewardEndTime - rewardStartTime) / 1 hours; compoundedAmountX96 = compoundedAmountX96.mulX96( Math.compound(rewardRateX96, nCompounds) ); rewardEndTime = rewardStartTime; } else { nCompounds = (rewardEndTime - lastHarvestTime) / 1 hours; compoundedAmountX96 = compoundedAmountX96.mulX96( Math.compound(rewardRateX96, nCompounds) ); break; } } rewardAmount = (compoundedAmountX96 - stakedAmountX96) / Q96; }
55,790
11
// get the RLP item by index. save gas. /
function getItemByIndex(RLPItem memory item, uint idx) internal pure returns (RLPItem memory) { require(isList(item), "RLPDecoder iterator is not a list"); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < idx; i++) { dataLen = _itemLength(memPtr); memPtr = memPtr + dataLen; } dataLen = _itemLength(memPtr); return RLPItem(dataLen, memPtr); }
function getItemByIndex(RLPItem memory item, uint idx) internal pure returns (RLPItem memory) { require(isList(item), "RLPDecoder iterator is not a list"); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < idx; i++) { dataLen = _itemLength(memPtr); memPtr = memPtr + dataLen; } dataLen = _itemLength(memPtr); return RLPItem(dataLen, memPtr); }
22,280
444
// compound the cumulated interest to the borrow balance and then subtracting the payback amount
if (borrowRateMode == CoreLibrary.InterestRateMode.STABLE) { reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _balanceIncrease, user.stableBorrowRate ); reserve.decreaseTotalBorrowsStableAndUpdateAverageRate( _paybackAmountMinusFees, user.stableBorrowRate ); } else {
if (borrowRateMode == CoreLibrary.InterestRateMode.STABLE) { reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _balanceIncrease, user.stableBorrowRate ); reserve.decreaseTotalBorrowsStableAndUpdateAverageRate( _paybackAmountMinusFees, user.stableBorrowRate ); } else {
7,074
25
// replace selector with last selector
if (oldFacet.selectorPosition != selectorCount - 1) { bytes4 lastSelector = ds.selectors[selectorCount - 1]; ds.selectors[oldFacet.selectorPosition] = lastSelector; ds.facets[lastSelector].selectorPosition = oldFacet.selectorPosition; }
if (oldFacet.selectorPosition != selectorCount - 1) { bytes4 lastSelector = ds.selectors[selectorCount - 1]; ds.selectors[oldFacet.selectorPosition] = lastSelector; ds.facets[lastSelector].selectorPosition = oldFacet.selectorPosition; }
78,269
161
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], amount); emit Mint(to, scaledAmount); emit Transfer(address(0), to, scaledAmount);
_moveDelegates(address(0), _delegates[to], amount); emit Mint(to, scaledAmount); emit Transfer(address(0), to, scaledAmount);
79,476
30
// Throws if called by any account other than the owner. /
modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; }
modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; }
505
138
// src// pragma solidity >=0.8.10; /
/* import {IUniswapV2Router02} from "./IUniswapV2Router02.sol"; */ /* import {IUniswapV2Factory} from "./IUniswapV2Factory.sol"; */ /* import {IUniswapV2Pair} from "./IUniswapV2Pair.sol"; */ /* import {IERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; */ /* import {ERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol"; */ /* import {Ownable} from "lib/openzeppelin-contracts/contracts/access/Ownable.sol"; */ /* import {SafeMath} from "lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol"; */ contract AntiFragileDAO is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated( address indexed newWallet, address indexed oldWallet ); event devWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("AntiFragile Dao", "CHAOS") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 2; uint256 _buyLiquidityFee = 2; uint256 _buyDevFee = 8; uint256 _sellMarketingFee = 2; uint256 _sellLiquidityFee = 2; uint256 _sellDevFee = 8; uint256 totalSupply = 1_000_000_000 * 1e18; maxTransactionAmount = 10_000_000 * 1e18; // 1% from total supply maxTransactionAmountTxn maxWallet = 20_000_000 * 1e18; // 2% from total supply maxWallet swapTokensAtAmount = (totalSupply * 5) / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0x944aedC4A159dBea627faF0e2E93CDb12A8B1FFF); // set as marketing wallet devWallet = address(0x944aedC4A159dBea627faF0e2E93CDb12A8B1FFF); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable {} // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); require( newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply." ); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%" ); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function updateBuyFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } //when sell else if ( automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } else if (!_isExcludedMaxTransactionAmount[to]) { require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if (takeFee) { // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success, ) = address(devWallet).call{value: ethForDev}(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require( _frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes" ); require( _percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
/* import {IUniswapV2Router02} from "./IUniswapV2Router02.sol"; */ /* import {IUniswapV2Factory} from "./IUniswapV2Factory.sol"; */ /* import {IUniswapV2Pair} from "./IUniswapV2Pair.sol"; */ /* import {IERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; */ /* import {ERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol"; */ /* import {Ownable} from "lib/openzeppelin-contracts/contracts/access/Ownable.sol"; */ /* import {SafeMath} from "lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol"; */ contract AntiFragileDAO is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated( address indexed newWallet, address indexed oldWallet ); event devWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("AntiFragile Dao", "CHAOS") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 2; uint256 _buyLiquidityFee = 2; uint256 _buyDevFee = 8; uint256 _sellMarketingFee = 2; uint256 _sellLiquidityFee = 2; uint256 _sellDevFee = 8; uint256 totalSupply = 1_000_000_000 * 1e18; maxTransactionAmount = 10_000_000 * 1e18; // 1% from total supply maxTransactionAmountTxn maxWallet = 20_000_000 * 1e18; // 2% from total supply maxWallet swapTokensAtAmount = (totalSupply * 5) / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0x944aedC4A159dBea627faF0e2E93CDb12A8B1FFF); // set as marketing wallet devWallet = address(0x944aedC4A159dBea627faF0e2E93CDb12A8B1FFF); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable {} // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); require( newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply." ); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%" ); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function updateBuyFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } //when sell else if ( automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } else if (!_isExcludedMaxTransactionAmount[to]) { require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if (takeFee) { // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success, ) = address(devWallet).call{value: ethForDev}(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require( _frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes" ); require( _percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
50,785
73
// Checks that amount desired can be purchased, then adds purchased amount to buyer and to total sold.
consumeBlaq(msg.sender, amount); _tokensSold += amount;
consumeBlaq(msg.sender, amount); _tokensSold += amount;
24,000
273
// Sets provenance once it's calculated
function setProvenanceHash(string memory provenanceHash) public onlyOwner { SUBSTANDARD_PROVENANCE = provenanceHash; }
function setProvenanceHash(string memory provenanceHash) public onlyOwner { SUBSTANDARD_PROVENANCE = provenanceHash; }
31,388
35
// computes "MAX_WEIGHTa / (a + b)" and "MAX_WEIGHTb / (a + b)", assuming that "a <= b". /
function accurateWeights(uint256 _a, uint256 _b) public pure returns (uint32, uint32)
function accurateWeights(uint256 _a, uint256 _b) public pure returns (uint32, uint32)
1,509
2
// Perform tasks (clubbed all functions into one to reduce external calls & SAVE GAS FEE) Breakdown of functions written below
manager.performTasks();
manager.performTasks();
20,720
6
// Check if strategy has tokens from panic
if (_wantAmt > wantAmt) { _vaultWithdraw(_wantAmt - wantAmt); wantAmt = IERC20(wantAddress).balanceOf(address(this)); }
if (_wantAmt > wantAmt) { _vaultWithdraw(_wantAmt - wantAmt); wantAmt = IERC20(wantAddress).balanceOf(address(this)); }
1,898
15
// Stores the parameters for a settlement after liquidation process
struct SettleParams { FixedPoint.Unsigned feeAttenuation; FixedPoint.Unsigned settlementPrice; FixedPoint.Unsigned tokenRedemptionValue; FixedPoint.Unsigned collateral; FixedPoint.Unsigned disputerDisputeReward; FixedPoint.Unsigned sponsorDisputeReward; FixedPoint.Unsigned disputeBondAmount; FixedPoint.Unsigned finalFee; FixedPoint.Unsigned withdrawalAmount; }
struct SettleParams { FixedPoint.Unsigned feeAttenuation; FixedPoint.Unsigned settlementPrice; FixedPoint.Unsigned tokenRedemptionValue; FixedPoint.Unsigned collateral; FixedPoint.Unsigned disputerDisputeReward; FixedPoint.Unsigned sponsorDisputeReward; FixedPoint.Unsigned disputeBondAmount; FixedPoint.Unsigned finalFee; FixedPoint.Unsigned withdrawalAmount; }
9,578
121
// True if epoch has been wound down already
mapping(uint256=>bool) public epoch_wound_down; uint256 public last_deploy; // Last run of Hourly Deploy uint256 public deploy_interval; // Hourly deploy interval
mapping(uint256=>bool) public epoch_wound_down; uint256 public last_deploy; // Last run of Hourly Deploy uint256 public deploy_interval; // Hourly deploy interval
5,609
32
// Returns the number of vesting schedules managed by this contract.return the number of vesting schedules /
function getVestingSchedulesCount() public view returns (uint256) { return vestingSchedulesIds.length; }
function getVestingSchedulesCount() public view returns (uint256) { return vestingSchedulesIds.length; }
15,901
11
// unlocks a slot on an avatar avatarId the avatar to upgrade slot 0-12 inclusive for the slot to unlockreturn the id of the new avatar (old one is burned) /
function unlock(uint256 avatarId, uint16 slot) external nonReentrant onlyUnlocked returns (uint256) { require(ownerOf(avatarId) == _msgSender(), "Invalid avatar"); require(slot < EthlingUtils.MAX_SLOTS(), "Invalid slot"); uint256 newAvatarId = EthlingUtils.addSlot(avatarId, slot); avatars[newAvatarId] = EthlingUtils.copySlotValues(avatars[avatarId], newAvatarId); delete avatars[avatarId]; changeToken.burn(_msgSender(), UNLOCK_COST); _burn(avatarId); _safeMint(_msgSender(), newAvatarId); emit AvatarSlotUnlocked(avatarId, newAvatarId); }
function unlock(uint256 avatarId, uint16 slot) external nonReentrant onlyUnlocked returns (uint256) { require(ownerOf(avatarId) == _msgSender(), "Invalid avatar"); require(slot < EthlingUtils.MAX_SLOTS(), "Invalid slot"); uint256 newAvatarId = EthlingUtils.addSlot(avatarId, slot); avatars[newAvatarId] = EthlingUtils.copySlotValues(avatars[avatarId], newAvatarId); delete avatars[avatarId]; changeToken.burn(_msgSender(), UNLOCK_COST); _burn(avatarId); _safeMint(_msgSender(), newAvatarId); emit AvatarSlotUnlocked(avatarId, newAvatarId); }
10,086
62
// allows to burn tokens from own balance only allows burning tokens until minimum supply is reached value amount of tokens to burn /
function burn(uint256 value) public { _burn(_msgSender(), value); require(totalSupply() >= minSupply, "total supply exceeds min supply"); }
function burn(uint256 value) public { _burn(_msgSender(), value); require(totalSupply() >= minSupply, "total supply exceeds min supply"); }
7,182
19
// Log account that triggered the election cycle as well as the block timestamp
emit ElectionCycleTriggered(msg.sender, block.timestamp);
emit ElectionCycleTriggered(msg.sender, block.timestamp);
21,450
107
// Value used as divisor with the VIX, commonly used for many financial indices
uint256 public divisor;
uint256 public divisor;
5,173
53
// Core pool will pull the `balance` of token from this contract into the pool. Core pool will also make a state change: update the `_records` mapping with a new record.
optionPool_.bind(token_, balance, denorm); emit PoolBoundTokenUpdate(msg.sender, token_, balance, denorm);
optionPool_.bind(token_, balance, denorm); emit PoolBoundTokenUpdate(msg.sender, token_, balance, denorm);
40,097
4
// Cross-chain Functions// Complete a deposit from L1 to L2, and credits funds to the recipient's balance of thisL2 token. This call will fail if it did not originate from a corresponding deposit inL1StandardTokenBridge. _l1Token Address for the l1 token this is called with _l2Token Address for the l2 token this is called with _from Account to pull the deposit from on L2. _to Address to receive the withdrawal at _amount Amount of the token to withdraw _data Data provider by the sender on L1. This data is provided solely as a convenience for external contracts. Aside from enforcing a maximum
function finalizeDeposit(
function finalizeDeposit(
17,464
30
// after 1,270,500 tokens burnt, supply is expanded by 637,500 tokens
if(_tBurnCycle >= (1275000 * _DECIMALFACTOR)){ uint256 _tRebaseDelta = 637500 * _DECIMALFACTOR; _tBurnCycle = _tBurnCycle.sub((1275000 * _DECIMALFACTOR)); _tTradeCycle = 0; _setBurnFee(500); _rebase(_tRebaseDelta); }
if(_tBurnCycle >= (1275000 * _DECIMALFACTOR)){ uint256 _tRebaseDelta = 637500 * _DECIMALFACTOR; _tBurnCycle = _tBurnCycle.sub((1275000 * _DECIMALFACTOR)); _tTradeCycle = 0; _setBurnFee(500); _rebase(_tRebaseDelta); }
28,109
4
// approve the position manager up to the maximum token amounts
TransferHelper.safeApprove(params.token0, nonfungiblePositionManager, amount0V2ToMigrate); TransferHelper.safeApprove(params.token1, nonfungiblePositionManager, amount1V2ToMigrate);
TransferHelper.safeApprove(params.token0, nonfungiblePositionManager, amount0V2ToMigrate); TransferHelper.safeApprove(params.token1, nonfungiblePositionManager, amount1V2ToMigrate);
15,549
72
// getNumFulfillments() returns the number of fulfillments for a given milestone/_bountyId the index of the bounty/ return Returns the number of fulfillments
function getNumFulfillments(uint _bountyId) public constant validateBountyArrayIndex(_bountyId) returns (uint)
function getNumFulfillments(uint _bountyId) public constant validateBountyArrayIndex(_bountyId) returns (uint)
6,851
6
// check if exceeding current limit
if(amount > currentBalance()) { amount = currentBalance(); tranches = amount / oneTrancheAmount(); }
if(amount > currentBalance()) { amount = currentBalance(); tranches = amount / oneTrancheAmount(); }
4,659
19
// View function to see pending AMDX on frontend./_pid The index of the pool. See `poolInfo`./_user Address of user./ return pending AMDX reward for a given user.
function pendingAmdx(uint256 _pid, address _user) external view returns (uint256 pending) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accAmdxPerShare = pool.accAmdxPerShare; if (block.number > pool.lastRewardBlock && pool.totalLp != 0) { uint256 blocks = block.number.sub(pool.lastRewardBlock); uint256 amdxReward = blocks.mul(AMDX_PER_BLOCK).mul(pool.allocPoint) / totalAllocPoint; accAmdxPerShare = accAmdxPerShare.add(amdxReward.mul(ACC_AMDX_PRECISION) / pool.totalLp); } pending = int256(user.amount.mul(accAmdxPerShare) / ACC_AMDX_PRECISION).sub(user.rewardDebt).toUInt256(); }
function pendingAmdx(uint256 _pid, address _user) external view returns (uint256 pending) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accAmdxPerShare = pool.accAmdxPerShare; if (block.number > pool.lastRewardBlock && pool.totalLp != 0) { uint256 blocks = block.number.sub(pool.lastRewardBlock); uint256 amdxReward = blocks.mul(AMDX_PER_BLOCK).mul(pool.allocPoint) / totalAllocPoint; accAmdxPerShare = accAmdxPerShare.add(amdxReward.mul(ACC_AMDX_PRECISION) / pool.totalLp); } pending = int256(user.amount.mul(accAmdxPerShare) / ACC_AMDX_PRECISION).sub(user.rewardDebt).toUInt256(); }
13,136
3
// Lot object
struct Lot { address nft; address payable seller; uint256 tokenId; Types offerType; uint256 price; uint256 stopPrice; uint256 reservePrice; uint256 auctionStart; uint256 auctionEnd; bool isSold; bool isCanceled; }
struct Lot { address nft; address payable seller; uint256 tokenId; Types offerType; uint256 price; uint256 stopPrice; uint256 reservePrice; uint256 auctionStart; uint256 auctionEnd; bool isSold; bool isCanceled; }
57,781
166
// built by mice, for everyone/
contract Randomice is ERC721, Ownable, ReentrancyGuard { using Strings for uint256; string public baseURI; uint256 public cost = 0.025 ether; uint256 public minted; uint256 public maxSupply = 6969; //nice uint256 public maxMint = 10; bool public status = false; address miceAddr = 0xbad6186E92002E312078b5a1dAfd5ddf63d3f731; //Anonymice address doodlesAddr = 0x8a90CAb2b38dba80c64b7734e58Ee1dB38B8992e; //Doodles address babyMiceAddr = 0x15Cc16BfE6fAC624247490AA29B6D632Be549F00; //Baby Mice mapping(address => bool) public mintlist; constructor() ERC721("RandoMice", "RMICE") {} //checks if address owns at least one token from either of the qualifying collections function isHolder(address _wallet) public view returns (bool) { ERC721 miceToken = ERC721(miceAddr); uint256 _miceBalance = miceToken.balanceOf(_wallet); ERC721 doodlesToken = ERC721(doodlesAddr); uint256 _doodlesBalance = doodlesToken.balanceOf(_wallet); ERC721 babyMiceToken = ERC721(babyMiceAddr); uint256 _babyMiceBalance = babyMiceToken.balanceOf(_wallet); return (_miceBalance + _doodlesBalance + _babyMiceBalance > 0); } //public mint function mint(uint256 _mintAmount) public payable nonReentrant{ require(status, "Sale inactive" ); require(msg.sender == tx.origin, "No contracts!"); require(_mintAmount <= maxMint, "Too many" ); require(minted + _mintAmount <= maxSupply, "Would excced supply" ); require(msg.value >= cost * _mintAmount, "Not enough ETH"); for (uint256 i = 0; i < _mintAmount; i++) { minted++; _safeMint(msg.sender, minted); } } //free claim for qualifying holders function claim(address _wallet) external nonReentrant { require(status, "Sale inactive" ); require(msg.sender == tx.origin, "No contracts!"); require(minted + 1 <= maxSupply, "Would excced supply" ); (bool _holder) = isHolder(_wallet); require(_holder, "Must own at least one qualifying NFT to claim!"); require(mintlist[_wallet] != true, "Already claimed!"); mintlist[_wallet] = true; minted++; _safeMint(msg.sender, minted); } //giveaways are nice function gift(uint[] calldata quantity, address[] calldata recipient) external onlyOwner{ require(quantity.length == recipient.length, "Provide quantities and recipients" ); uint totalQuantity = 0; for(uint i = 0; i < quantity.length; i++){ totalQuantity += quantity[i]; } require( minted + totalQuantity <= maxSupply, "Too many" ); delete totalQuantity; for(uint i = 0; i < recipient.length; i++){ for(uint j = 0; j < quantity[i]; j++){ minted++; _safeMint(recipient[i], minted); } } } //metadata function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Nonexistent token"); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, (tokenId).toString())) : ""; } //setters function setMiceAddress(address _miceAddr) external onlyOwner { miceAddr = _miceAddr; } function setDoodlesAddress(address _doodlesAddr) external onlyOwner { doodlesAddr = _doodlesAddr; } function setBabyMiceAddress(address _babyMiceAddr) external onlyOwner { babyMiceAddr = _babyMiceAddr; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setMaxMintAmount(uint256 _newMaxMintAmount) public onlyOwner { maxMint = _newMaxMintAmount; } function setmaxSupply(uint256 _newMaxSupply) public onlyOwner { maxSupply = _newMaxSupply; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } //admin functions function _baseURI() internal view override returns (string memory) { return baseURI; } function flipSaleStatus() public onlyOwner { status = !status; } function withdraw() public payable onlyOwner { (bool success, ) = payable(msg.sender).call{value: address(this).balance}(""); require(success); } }
contract Randomice is ERC721, Ownable, ReentrancyGuard { using Strings for uint256; string public baseURI; uint256 public cost = 0.025 ether; uint256 public minted; uint256 public maxSupply = 6969; //nice uint256 public maxMint = 10; bool public status = false; address miceAddr = 0xbad6186E92002E312078b5a1dAfd5ddf63d3f731; //Anonymice address doodlesAddr = 0x8a90CAb2b38dba80c64b7734e58Ee1dB38B8992e; //Doodles address babyMiceAddr = 0x15Cc16BfE6fAC624247490AA29B6D632Be549F00; //Baby Mice mapping(address => bool) public mintlist; constructor() ERC721("RandoMice", "RMICE") {} //checks if address owns at least one token from either of the qualifying collections function isHolder(address _wallet) public view returns (bool) { ERC721 miceToken = ERC721(miceAddr); uint256 _miceBalance = miceToken.balanceOf(_wallet); ERC721 doodlesToken = ERC721(doodlesAddr); uint256 _doodlesBalance = doodlesToken.balanceOf(_wallet); ERC721 babyMiceToken = ERC721(babyMiceAddr); uint256 _babyMiceBalance = babyMiceToken.balanceOf(_wallet); return (_miceBalance + _doodlesBalance + _babyMiceBalance > 0); } //public mint function mint(uint256 _mintAmount) public payable nonReentrant{ require(status, "Sale inactive" ); require(msg.sender == tx.origin, "No contracts!"); require(_mintAmount <= maxMint, "Too many" ); require(minted + _mintAmount <= maxSupply, "Would excced supply" ); require(msg.value >= cost * _mintAmount, "Not enough ETH"); for (uint256 i = 0; i < _mintAmount; i++) { minted++; _safeMint(msg.sender, minted); } } //free claim for qualifying holders function claim(address _wallet) external nonReentrant { require(status, "Sale inactive" ); require(msg.sender == tx.origin, "No contracts!"); require(minted + 1 <= maxSupply, "Would excced supply" ); (bool _holder) = isHolder(_wallet); require(_holder, "Must own at least one qualifying NFT to claim!"); require(mintlist[_wallet] != true, "Already claimed!"); mintlist[_wallet] = true; minted++; _safeMint(msg.sender, minted); } //giveaways are nice function gift(uint[] calldata quantity, address[] calldata recipient) external onlyOwner{ require(quantity.length == recipient.length, "Provide quantities and recipients" ); uint totalQuantity = 0; for(uint i = 0; i < quantity.length; i++){ totalQuantity += quantity[i]; } require( minted + totalQuantity <= maxSupply, "Too many" ); delete totalQuantity; for(uint i = 0; i < recipient.length; i++){ for(uint j = 0; j < quantity[i]; j++){ minted++; _safeMint(recipient[i], minted); } } } //metadata function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Nonexistent token"); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, (tokenId).toString())) : ""; } //setters function setMiceAddress(address _miceAddr) external onlyOwner { miceAddr = _miceAddr; } function setDoodlesAddress(address _doodlesAddr) external onlyOwner { doodlesAddr = _doodlesAddr; } function setBabyMiceAddress(address _babyMiceAddr) external onlyOwner { babyMiceAddr = _babyMiceAddr; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setMaxMintAmount(uint256 _newMaxMintAmount) public onlyOwner { maxMint = _newMaxMintAmount; } function setmaxSupply(uint256 _newMaxSupply) public onlyOwner { maxSupply = _newMaxSupply; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } //admin functions function _baseURI() internal view override returns (string memory) { return baseURI; } function flipSaleStatus() public onlyOwner { status = !status; } function withdraw() public payable onlyOwner { (bool success, ) = payable(msg.sender).call{value: address(this).balance}(""); require(success); } }
77,035
504
// Give an account access to this role./
function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; }
function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; }
25,077
384
// Validate message format
_originalMsg._validateMessageFormat();
_originalMsg._validateMessageFormat();
16,979
219
// Switches to a new {IRelayHub} instance. This method is added for future-proofing: there's no reason to notuse the default instance. IMPORTANT: After upgrading, the {GSNRecipient} will no longer be able to receive relayed calls from the old{IRelayHub} instance. Additionally, all funds should be previously withdrawn via {_withdrawDeposits}. /
function _upgradeRelayHub(address newRelayHub) internal { address currentRelayHub = _relayHub; require(newRelayHub != address(0), "GSNRecipient: new RelayHub is the zero address"); require(newRelayHub != currentRelayHub, "GSNRecipient: new RelayHub is the current one"); emit RelayHubChanged(currentRelayHub, newRelayHub); _relayHub = newRelayHub; }
function _upgradeRelayHub(address newRelayHub) internal { address currentRelayHub = _relayHub; require(newRelayHub != address(0), "GSNRecipient: new RelayHub is the zero address"); require(newRelayHub != currentRelayHub, "GSNRecipient: new RelayHub is the current one"); emit RelayHubChanged(currentRelayHub, newRelayHub); _relayHub = newRelayHub; }
37,339
147
// Executes the Auto Redistribution event by isolating the bAsset from the Basket _basketStruct containing core basket info _bAssetPersonalBasset data storage array _bAssetAddress of the ERC20 token to isolate _belowPegBool to describe whether the bAsset deviated below peg (t)or above (f) /
function handlePegLoss( MassetStructs.BasketState storage _basket, MassetStructs.BassetPersonal[] storage _bAssetPersonal, mapping(address => uint8) storage _bAssetIndexes, address _bAsset, bool _belowPeg
function handlePegLoss( MassetStructs.BasketState storage _basket, MassetStructs.BassetPersonal[] storage _bAssetPersonal, mapping(address => uint8) storage _bAssetIndexes, address _bAsset, bool _belowPeg
15,784
2
// Voter[] vtr_list; /
constructor() ERC721("Real Estate Agent", "REA") { creater = msg.sender; prices = new uint256[](4); maxCounts = new uint256[](4); currentCounts = new uint256[](4); prices[1] = 0.1 ether; prices[2] = 0.05 ether; prices[3] = 0.01 ether; maxCounts[1] = 11; maxCounts[2] = 50; maxCounts[3] = 50; /////proposalMgr = Proposal(); /* vtr_address = new address[](100); categoty = new uint256[](100); */ }
constructor() ERC721("Real Estate Agent", "REA") { creater = msg.sender; prices = new uint256[](4); maxCounts = new uint256[](4); currentCounts = new uint256[](4); prices[1] = 0.1 ether; prices[2] = 0.05 ether; prices[3] = 0.01 ether; maxCounts[1] = 11; maxCounts[2] = 50; maxCounts[3] = 50; /////proposalMgr = Proposal(); /* vtr_address = new address[](100); categoty = new uint256[](100); */ }
21,356
5
// does the customer purchase exceed the max Founder quota?
(FounderAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= FounderMaxPurchase_ );
(FounderAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= FounderMaxPurchase_ );
48,194
1
// ============ Properties ============
mapping(address => bool) public isWatcher;
mapping(address => bool) public isWatcher;
26,631
2
// compute the return for the amount of tokens provided
(uint256 sourceToDestRate, uint256 sourceToDestPrecision) = IPriceFeeds(priceFeeds).queryRate(address(_path[0]), address(_path[1])); uint256 actualReturn = _amount.mul(sourceToDestRate).div(sourceToDestPrecision); require(actualReturn >= _minReturn, "insufficient source tokens provided"); TestToken(address(_path[0])).burn(address(msg.sender), _amount); TestToken(address(_path[1])).mint(address(_beneficiary), actualReturn); return actualReturn;
(uint256 sourceToDestRate, uint256 sourceToDestPrecision) = IPriceFeeds(priceFeeds).queryRate(address(_path[0]), address(_path[1])); uint256 actualReturn = _amount.mul(sourceToDestRate).div(sourceToDestPrecision); require(actualReturn >= _minReturn, "insufficient source tokens provided"); TestToken(address(_path[0])).burn(address(msg.sender), _amount); TestToken(address(_path[1])).mint(address(_beneficiary), actualReturn); return actualReturn;
27,792
97
// calculate fee:
(uint256 transferToAmount, uint256 transferToFeeDistributorAmount) = calculateAmountsAfterFee(sender, recipient, amount); uint256 timeNow = block.timestamp; if(timeNow < transData[sender] + 10 minutes){ revert("CAN ONLY TRADE 5 DUCK PER 10 MIN"); }
(uint256 transferToAmount, uint256 transferToFeeDistributorAmount) = calculateAmountsAfterFee(sender, recipient, amount); uint256 timeNow = block.timestamp; if(timeNow < transData[sender] + 10 minutes){ revert("CAN ONLY TRADE 5 DUCK PER 10 MIN"); }
14,307
37
// Set approved borrowers
for (uint256 i = 0; i < _approvedBorrowers.length; ++i) { approvedBorrowers[_approvedBorrowers[i]] = true; }
for (uint256 i = 0; i < _approvedBorrowers.length; ++i) { approvedBorrowers[_approvedBorrowers[i]] = true; }
48,549
39
// store subjects
mapping(address => uint128[]) public studentSubjects;
mapping(address => uint128[]) public studentSubjects;
24,582
525
// Check if the deposit has indeed exceeded the time limit of if the exchange is in withdrawal mode
require( block.timestamp >= deposit.timestamp + S.maxAgeDepositUntilWithdrawable || S.isInWithdrawalMode(), "DEPOSIT_NOT_WITHDRAWABLE_YET" ); uint amount = deposit.amount;
require( block.timestamp >= deposit.timestamp + S.maxAgeDepositUntilWithdrawable || S.isInWithdrawalMode(), "DEPOSIT_NOT_WITHDRAWABLE_YET" ); uint amount = deposit.amount;
9,390
77
// When more calls in the same block, only the first one takes effect, so for the following calls, nothing updates.
if (block.number != accrualBlockNumber) { InterestLocalVars memory _vars; _vars.currentCash = _getCurrentCash(); _vars.totalBorrows = totalBorrows; _vars.totalReserves = totalReserves;
if (block.number != accrualBlockNumber) { InterestLocalVars memory _vars; _vars.currentCash = _getCurrentCash(); _vars.totalBorrows = totalBorrows; _vars.totalReserves = totalReserves;
71,411
2
// bring everything back one index
for (uint i = self[0] + 1; i < self.length ; ++i) { self[i-1] = self[i]; }
for (uint i = self[0] + 1; i < self.length ; ++i) { self[i-1] = self[i]; }
17,741
10
// Publishes an instruction for the delivery provider at `deliveryProviderAddress`to relay a payload and VAAs specified by `vaaKeys` to the address `targetAddress` on chain `targetChain`with `msg.value` equal toreceiverValue + (arbitrary amount that is paid for by paymentForExtraReceiverValue of this chain's wei) in targetChain wei. Any refunds (from leftover gas) will be sent to `refundAddress` on chain `refundChain``targetAddress` must implement the IWormholeReceiver interface This function must be called with `msg.value` equal toquoteDeliveryPrice(targetChain, receiverValue, encodedExecutionParameters, deliveryProviderAddress) + paymentForExtraReceiverValuetargetChain in Wormhole Chain ID format targetAddress address to call on targetChain (that implements IWormholeReceiver), in Wormhole bytes32 format payload arbitrary bytes to pass in as
function send(
function send(
15,599
645
// The top byte of ret has already been cleared to make room for the new digit. Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched.
ret |= utf8Digit << (31 * bitsPerByte);
ret |= utf8Digit << (31 * bitsPerByte);
12,186
8
// Enables a module that can add transactions to the queue/module Address of the module to be enabled/This can only be called by the owner
function enableModule(address module) public onlyOwner { require( module != address(0) && module != SENTINEL_MODULES, "Invalid module" ); require(modules[module] == address(0), "Module already enabled"); modules[module] = modules[SENTINEL_MODULES]; modules[SENTINEL_MODULES] = module; emit EnabledModule(module); }
function enableModule(address module) public onlyOwner { require( module != address(0) && module != SENTINEL_MODULES, "Invalid module" ); require(modules[module] == address(0), "Module already enabled"); modules[module] = modules[SENTINEL_MODULES]; modules[SENTINEL_MODULES] = module; emit EnabledModule(module); }
28,226
27
// Only `owner` can update the config if it didn't start yet. /
function updateConfig(Config memory config) public onlyOwner notCancelled beforeStarted { _updateConfig(config); }
function updateConfig(Config memory config) public onlyOwner notCancelled beforeStarted { _updateConfig(config); }
43,635
2
// a settings contract controlled by governance
address public immutable settings;
address public immutable settings;
63,011
15
// Check to see if the duration is too long and if it is set the duration.
(,, m.parentExpiry) = nameWrappers[nameWrapperVersion].getData(uint256(parentNode)); if (m.nodeExpiry + duration > m.parentExpiry) { duration = m.parentExpiry - m.nodeExpiry; }
(,, m.parentExpiry) = nameWrappers[nameWrapperVersion].getData(uint256(parentNode)); if (m.nodeExpiry + duration > m.parentExpiry) { duration = m.parentExpiry - m.nodeExpiry; }
13,914
23
// Returns the ExtensionManager storage.
function _extensionManagerStorage() internal pure returns (ExtensionManagerStorage.Data storage data) { data = ExtensionManagerStorage.data(); }
function _extensionManagerStorage() internal pure returns (ExtensionManagerStorage.Data storage data) { data = ExtensionManagerStorage.data(); }
31,057
3
// check current expiry
uint256 currentExpiryTime = s_localAccessList[user][data];
uint256 currentExpiryTime = s_localAccessList[user][data];
7,648
293
// contracts/Pool.sol/ pragma solidity 0.6.11; // import "lib/openzeppelin-contracts/contracts/token/ERC20/SafeERC20.sol"; // import "./interfaces/IBPool.sol"; // import "./interfaces/IDebtLocker.sol"; // import "./interfaces/IMapleGlobals.sol"; // import "./interfaces/ILiquidityLocker.sol"; // import "./interfaces/ILiquidityLockerFactory.sol"; // import "./interfaces/ILoan.sol"; // import "./interfaces/ILoanFactory.sol"; // import "./interfaces/IPoolFactory.sol"; // import "./interfaces/IStakeLocker.sol"; // import "./interfaces/IStakeLockerFactory.sol"; // import "./library/PoolLib.sol"; // import "./token/PoolFDT.sol"; //Pool maintains all accounting and functionality related to Pools.
contract Pool is PoolFDT { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 constant WAD = 10 ** 18; uint8 public constant DL_FACTORY = 1; // Factory type of `DebtLockerFactory`. IERC20 public immutable liquidityAsset; // The asset deposited by Lenders into the LiquidityLocker, for funding Loans. address public immutable poolDelegate; // The Pool Delegate address, maintains full authority over the Pool. address public immutable liquidityLocker; // The LiquidityLocker owned by this contract address public immutable stakeAsset; // The address of the asset deposited by Stakers into the StakeLocker (BPTs), for liquidation during default events. address public immutable stakeLocker; // The address of the StakeLocker, escrowing `stakeAsset`. address public immutable superFactory; // The factory that deployed this Loan. uint256 private immutable liquidityAssetDecimals; // The precision for the Liquidity Asset (i.e. `decimals()`). uint256 public stakingFee; // The fee Stakers earn (in basis points). uint256 public immutable delegateFee; // The fee the Pool Delegate earns (in basis points). uint256 public principalOut; // The sum of all outstanding principal on Loans. uint256 public liquidityCap; // The amount of liquidity tokens accepted by the Pool. uint256 public lockupPeriod; // The period of time from an account's deposit date during which they cannot withdraw any funds. bool public openToPublic; // Boolean opening Pool to public for LP deposits enum State { Initialized, Finalized, Deactivated } State public poolState; mapping(address => uint256) public depositDate; // Used for withdraw penalty calculation. mapping(address => mapping(address => address)) public debtLockers; // Address of the DebtLocker corresponding to `[Loan][DebtLockerFactory]`. mapping(address => bool) public poolAdmins; // The Pool Admin addresses that have permission to do certain operations in case of disaster management. mapping(address => bool) public allowedLiquidityProviders; // Mapping that contains the list of addresses that have early access to the pool. mapping(address => uint256) public withdrawCooldown; // The timestamp of when individual LPs have notified of their intent to withdraw. mapping(address => mapping(address => uint256)) public custodyAllowance; // The amount of PoolFDTs that are "locked" at a certain address. mapping(address => uint256) public totalCustodyAllowance; // The total amount of PoolFDTs that are "locked" for a given account. Cannot be greater than an account's balance. event LoanFunded(address indexed loan, address debtLocker, uint256 amountFunded); event Claim(address indexed loan, uint256 interest, uint256 principal, uint256 fee, uint256 stakeLockerPortion, uint256 poolDelegatePortion); event BalanceUpdated(address indexed liquidityProvider, address indexed token, uint256 balance); event CustodyTransfer(address indexed custodian, address indexed from, address indexed to, uint256 amount); event CustodyAllowanceChanged(address indexed liquidityProvider, address indexed custodian, uint256 oldAllowance, uint256 newAllowance); event LPStatusChanged(address indexed liquidityProvider, bool status); event LiquidityCapSet(uint256 newLiquidityCap); event LockupPeriodSet(uint256 newLockupPeriod); event StakingFeeSet(uint256 newStakingFee); event PoolStateChanged(State state); event Cooldown(address indexed liquidityProvider, uint256 cooldown); event PoolOpenedToPublic(bool isOpen); event PoolAdminSet(address indexed poolAdmin, bool allowed); event DepositDateUpdated(address indexed liquidityProvider, uint256 depositDate); event TotalCustodyAllowanceUpdated(address indexed liquidityProvider, uint256 newTotalAllowance); event DefaultSuffered( address indexed loan, uint256 defaultSuffered, uint256 bptsBurned, uint256 bptsReturned, uint256 liquidityAssetRecoveredFromBurn ); /** Universal accounting law: fdtTotalSupply = liquidityLockerBal + principalOut - interestSum + poolLosses fdtTotalSupply + interestSum - poolLosses = liquidityLockerBal + principalOut */ /** @dev Constructor for a Pool. @dev It emits a `PoolStateChanged` event. @param _poolDelegate Address that has manager privileges of the Pool. @param _liquidityAsset Asset used to fund the Pool, It gets escrowed in LiquidityLocker. @param _stakeAsset Asset escrowed in StakeLocker. @param _slFactory Factory used to instantiate the StakeLocker. @param _llFactory Factory used to instantiate the LiquidityLocker. @param _stakingFee Fee that Stakers earn on interest, in basis points. @param _delegateFee Fee that the Pool Delegate earns on interest, in basis points. @param _liquidityCap Max amount of Liquidity Asset accepted by the Pool. @param name Name of Pool token. @param symbol Symbol of Pool token. */ constructor( address _poolDelegate, address _liquidityAsset, address _stakeAsset, address _slFactory, address _llFactory, uint256 _stakingFee, uint256 _delegateFee, uint256 _liquidityCap, string memory name, string memory symbol ) PoolFDT(name, symbol) public { // Conduct sanity checks on Pool parameters. PoolLib.poolSanityChecks(_globals(msg.sender), _liquidityAsset, _stakeAsset, _stakingFee, _delegateFee); // Assign variables relating to the Liquidity Asset. liquidityAsset = IERC20(_liquidityAsset); liquidityAssetDecimals = ERC20(_liquidityAsset).decimals(); // Assign state variables. stakeAsset = _stakeAsset; poolDelegate = _poolDelegate; stakingFee = _stakingFee; delegateFee = _delegateFee; superFactory = msg.sender; liquidityCap = _liquidityCap; // Instantiate the LiquidityLocker and the StakeLocker. stakeLocker = address(IStakeLockerFactory(_slFactory).newLocker(_stakeAsset, _liquidityAsset)); liquidityLocker = address(ILiquidityLockerFactory(_llFactory).newLocker(_liquidityAsset)); lockupPeriod = 180 days; emit PoolStateChanged(State.Initialized); } /*******************************/ /*** Pool Delegate Functions ***/ /*******************************/ /** @dev Finalizes the Pool, enabling deposits. Checks the amount the Pool Delegate deposited to the StakeLocker. Only the Pool Delegate can call this function. @dev It emits a `PoolStateChanged` event. */ function finalize() external { _isValidDelegateAndProtocolNotPaused(); _isValidState(State.Initialized); (,, bool stakeSufficient,,) = getInitialStakeRequirements(); require(stakeSufficient, "P:INSUF_STAKE"); poolState = State.Finalized; emit PoolStateChanged(poolState); } /** @dev Funds a Loan for an amount, utilizing the supplied DebtLockerFactory for DebtLockers. Only the Pool Delegate can call this function. @dev It emits a `LoanFunded` event. @dev It emits a `BalanceUpdated` event. @param loan Address of the Loan to fund. @param dlFactory Address of the DebtLockerFactory to utilize. @param amt Amount to fund the Loan. */ function fundLoan(address loan, address dlFactory, uint256 amt) external { _isValidDelegateAndProtocolNotPaused(); _isValidState(State.Finalized); principalOut = principalOut.add(amt); PoolLib.fundLoan(debtLockers, superFactory, liquidityLocker, loan, dlFactory, amt); _emitBalanceUpdatedEvent(); } /** @dev Liquidates a Loan. The Pool Delegate could liquidate the Loan only when the Loan completes its grace period. The Pool Delegate can claim its proportion of recovered funds from the liquidation using the `claim()` function. Only the Pool Delegate can call this function. @param loan Address of the Loan to liquidate. @param dlFactory Address of the DebtLockerFactory that is used to pull corresponding DebtLocker. */ function triggerDefault(address loan, address dlFactory) external { _isValidDelegateAndProtocolNotPaused(); IDebtLocker(debtLockers[loan][dlFactory]).triggerDefault(); } /** @dev Claims available funds for the Loan through a specified DebtLockerFactory. Only the Pool Delegate or a Pool Admin can call this function. @dev It emits two `BalanceUpdated` events. @dev It emits a `Claim` event. @param loan Address of the loan to claim from. @param dlFactory Address of the DebtLockerFactory. @return claimInfo The claim details. claimInfo [0] = Total amount claimed claimInfo [1] = Interest portion claimed claimInfo [2] = Principal portion claimed claimInfo [3] = Fee portion claimed claimInfo [4] = Excess portion claimed claimInfo [5] = Recovered portion claimed (from liquidations) claimInfo [6] = Default suffered */ function claim(address loan, address dlFactory) external returns (uint256[7] memory claimInfo) { _whenProtocolNotPaused(); _isValidDelegateOrPoolAdmin(); claimInfo = IDebtLocker(debtLockers[loan][dlFactory]).claim(); (uint256 poolDelegatePortion, uint256 stakeLockerPortion, uint256 principalClaim, uint256 interestClaim) = PoolLib.calculateClaimAndPortions(claimInfo, delegateFee, stakingFee); // Subtract outstanding principal by the principal claimed plus excess returned. // Considers possible `principalClaim` overflow if Liquidity Asset is transferred directly into the Loan. if (principalClaim <= principalOut) { principalOut = principalOut - principalClaim; } else { interestClaim = interestClaim.add(principalClaim - principalOut); // Distribute `principalClaim` overflow as interest to LPs. principalClaim = principalOut; // Set `principalClaim` to `principalOut` so correct amount gets transferred. principalOut = 0; // Set `principalOut` to zero to avoid subtraction overflow. } // Accounts for rounding error in StakeLocker / Pool Delegate / LiquidityLocker interest split. interestSum = interestSum.add(interestClaim); _transferLiquidityAsset(poolDelegate, poolDelegatePortion); // Transfer the fee and portion of interest to the Pool Delegate. _transferLiquidityAsset(stakeLocker, stakeLockerPortion); // Transfer the portion of interest to the StakeLocker. // Transfer remaining claim (remaining interest + principal + excess + recovered) to the LiquidityLocker. // Dust will accrue in the Pool, but this ensures that state variables are in sync with the LiquidityLocker balance updates. // Not using `balanceOf` in case of external address transferring the Liquidity Asset directly into Pool. // Ensures that internal accounting is exactly reflective of balance change. _transferLiquidityAsset(liquidityLocker, principalClaim.add(interestClaim)); // Handle default if defaultSuffered > 0. if (claimInfo[6] > 0) _handleDefault(loan, claimInfo[6]); // Update funds received for StakeLockerFDTs. IStakeLocker(stakeLocker).updateFundsReceived(); // Update funds received for PoolFDTs. updateFundsReceived(); _emitBalanceUpdatedEvent(); emit BalanceUpdated(stakeLocker, address(liquidityAsset), liquidityAsset.balanceOf(stakeLocker)); emit Claim(loan, interestClaim, principalClaim, claimInfo[3], stakeLockerPortion, poolDelegatePortion); } /** @dev Handles if a claim has been made and there is a non-zero defaultSuffered amount. @dev It emits a `DefaultSuffered` event. @param loan Address of a Loan that has defaulted. @param defaultSuffered Losses suffered from default after liquidation. */ function _handleDefault(address loan, uint256 defaultSuffered) internal { (uint256 bptsBurned, uint256 postBurnBptBal, uint256 liquidityAssetRecoveredFromBurn) = PoolLib.handleDefault(liquidityAsset, stakeLocker, stakeAsset, defaultSuffered); // If BPT burn is not enough to cover full default amount, pass on losses to LPs with PoolFDT loss accounting. if (defaultSuffered > liquidityAssetRecoveredFromBurn) { poolLosses = poolLosses.add(defaultSuffered - liquidityAssetRecoveredFromBurn); updateLossesReceived(); } // Transfer Liquidity Asset from burn to LiquidityLocker. liquidityAsset.safeTransfer(liquidityLocker, liquidityAssetRecoveredFromBurn); principalOut = principalOut.sub(defaultSuffered); // Subtract rest of the Loan's principal from `principalOut`. emit DefaultSuffered( loan, // The Loan that suffered the default. defaultSuffered, // Total default suffered from the Loan by the Pool after liquidation. bptsBurned, // Amount of BPTs burned from StakeLocker. postBurnBptBal, // Remaining BPTs in StakeLocker post-burn. liquidityAssetRecoveredFromBurn // Amount of Liquidity Asset recovered from burning BPTs. ); } /** @dev Triggers deactivation, permanently shutting down the Pool. Must have less than 100 USD worth of Liquidity Asset `principalOut`. Only the Pool Delegate can call this function. @dev It emits a `PoolStateChanged` event. */ function deactivate() external { _isValidDelegateAndProtocolNotPaused(); _isValidState(State.Finalized); PoolLib.validateDeactivation(_globals(superFactory), principalOut, address(liquidityAsset)); poolState = State.Deactivated; emit PoolStateChanged(poolState); } /**************************************/ /*** Pool Delegate Setter Functions ***/ /**************************************/ /** @dev Sets the liquidity cap. Only the Pool Delegate or a Pool Admin can call this function. @dev It emits a `LiquidityCapSet` event. @param newLiquidityCap New liquidity cap value. */ function setLiquidityCap(uint256 newLiquidityCap) external { _whenProtocolNotPaused(); _isValidDelegateOrPoolAdmin(); liquidityCap = newLiquidityCap; emit LiquidityCapSet(newLiquidityCap); } /** @dev Sets the lockup period. Only the Pool Delegate can call this function. @dev It emits a `LockupPeriodSet` event. @param newLockupPeriod New lockup period used to restrict the withdrawals. */ function setLockupPeriod(uint256 newLockupPeriod) external { _isValidDelegateAndProtocolNotPaused(); require(newLockupPeriod <= lockupPeriod, "P:BAD_VALUE"); lockupPeriod = newLockupPeriod; emit LockupPeriodSet(newLockupPeriod); } /** @dev Sets the staking fee. Only the Pool Delegate can call this function. @dev It emits a `StakingFeeSet` event. @param newStakingFee New staking fee. */ function setStakingFee(uint256 newStakingFee) external { _isValidDelegateAndProtocolNotPaused(); require(newStakingFee.add(delegateFee) <= 10_000, "P:BAD_FEE"); stakingFee = newStakingFee; emit StakingFeeSet(newStakingFee); } /** @dev Sets the account status in the Pool's allowlist. Only the Pool Delegate can call this function. @dev It emits an `LPStatusChanged` event. @param account The address to set status for. @param status The status of an account in the allowlist. */ function setAllowList(address account, bool status) external { _isValidDelegateAndProtocolNotPaused(); allowedLiquidityProviders[account] = status; emit LPStatusChanged(account, status); } /** @dev Sets a Pool Admin. Only the Pool Delegate can call this function. @dev It emits a `PoolAdminSet` event. @param poolAdmin An address being allowed or disallowed as a Pool Admin. @param allowed Status of a Pool Admin. */ function setPoolAdmin(address poolAdmin, bool allowed) external { _isValidDelegateAndProtocolNotPaused(); poolAdmins[poolAdmin] = allowed; emit PoolAdminSet(poolAdmin, allowed); } /** @dev Sets whether the Pool is open to the public. Only the Pool Delegate can call this function. @dev It emits a `PoolOpenedToPublic` event. @param open Public pool access status. */ function setOpenToPublic(bool open) external { _isValidDelegateAndProtocolNotPaused(); openToPublic = open; emit PoolOpenedToPublic(open); } /************************************/ /*** Liquidity Provider Functions ***/ /************************************/ /** @dev Handles Liquidity Providers depositing of Liquidity Asset into the LiquidityLocker, minting PoolFDTs. @dev It emits a `DepositDateUpdated` event. @dev It emits a `BalanceUpdated` event. @dev It emits a `Cooldown` event. @param amt Amount of Liquidity Asset to deposit. */ function deposit(uint256 amt) external { _whenProtocolNotPaused(); _isValidState(State.Finalized); require(isDepositAllowed(amt), "P:DEP_NOT_ALLOWED"); withdrawCooldown[msg.sender] = uint256(0); // Reset the LP's withdraw cooldown if they had previously intended to withdraw. uint256 wad = _toWad(amt); PoolLib.updateDepositDate(depositDate, balanceOf(msg.sender), wad, msg.sender); liquidityAsset.safeTransferFrom(msg.sender, liquidityLocker, amt); _mint(msg.sender, wad); _emitBalanceUpdatedEvent(); emit Cooldown(msg.sender, uint256(0)); } /** @dev Activates the cooldown period to withdraw. It can't be called if the account is not providing liquidity. @dev It emits a `Cooldown` event. **/ function intendToWithdraw() external { require(balanceOf(msg.sender) != uint256(0), "P:ZERO_BAL"); withdrawCooldown[msg.sender] = block.timestamp; emit Cooldown(msg.sender, block.timestamp); } /** @dev Cancels an initiated withdrawal by resetting the account's withdraw cooldown. @dev It emits a `Cooldown` event. **/ function cancelWithdraw() external { require(withdrawCooldown[msg.sender] != uint256(0), "P:NOT_WITHDRAWING"); withdrawCooldown[msg.sender] = uint256(0); emit Cooldown(msg.sender, uint256(0)); } /** @dev Checks that the account can withdraw an amount. @param account The address of the account. @param wad The amount to withdraw. */ function _canWithdraw(address account, uint256 wad) internal view { require(depositDate[account].add(lockupPeriod) <= block.timestamp, "P:FUNDS_LOCKED"); // Restrict withdrawal during lockup period require(balanceOf(account).sub(wad) >= totalCustodyAllowance[account], "P:INSUF_TRANS_BAL"); // Account can only withdraw tokens that aren't custodied } /** @dev Handles Liquidity Providers withdrawing of Liquidity Asset from the LiquidityLocker, burning PoolFDTs. @dev It emits two `BalanceUpdated` event. @param amt Amount of Liquidity Asset to withdraw. */ function withdraw(uint256 amt) external { _whenProtocolNotPaused(); uint256 wad = _toWad(amt); (uint256 lpCooldownPeriod, uint256 lpWithdrawWindow) = _globals(superFactory).getLpCooldownParams(); _canWithdraw(msg.sender, wad); require((block.timestamp - (withdrawCooldown[msg.sender] + lpCooldownPeriod)) <= lpWithdrawWindow, "P:WITHDRAW_NOT_ALLOWED"); _burn(msg.sender, wad); // Burn the corresponding PoolFDTs balance. withdrawFunds(); // Transfer full entitled interest, decrement `interestSum`. // Transfer amount that is due after realized losses are accounted for. // Recognized losses are absorbed by the LP. _transferLiquidityLockerFunds(msg.sender, amt.sub(_recognizeLosses())); _emitBalanceUpdatedEvent(); } /** @dev Transfers PoolFDTs. @param from Address sending PoolFDTs. @param to Address receiving PoolFDTs. @param wad Amount of PoolFDTs to transfer. */ function _transfer(address from, address to, uint256 wad) internal override { _whenProtocolNotPaused(); (uint256 lpCooldownPeriod, uint256 lpWithdrawWindow) = _globals(superFactory).getLpCooldownParams(); _canWithdraw(from, wad); require(block.timestamp > (withdrawCooldown[to] + lpCooldownPeriod + lpWithdrawWindow), "P:TO_NOT_ALLOWED"); // Recipient must not be currently withdrawing. require(recognizableLossesOf(from) == uint256(0), "P:RECOG_LOSSES"); // If an LP has unrecognized losses, they must recognize losses using `withdraw`. PoolLib.updateDepositDate(depositDate, balanceOf(to), wad, to); super._transfer(from, to, wad); } /** @dev Withdraws all claimable interest from the LiquidityLocker for an account using `interestSum` accounting. @dev It emits a `BalanceUpdated` event. */ function withdrawFunds() public override { _whenProtocolNotPaused(); uint256 withdrawableFunds = _prepareWithdraw(); if (withdrawableFunds == uint256(0)) return; _transferLiquidityLockerFunds(msg.sender, withdrawableFunds); _emitBalanceUpdatedEvent(); interestSum = interestSum.sub(withdrawableFunds); _updateFundsTokenBalance(); } /** @dev Increases the custody allowance for a given Custodian corresponding to the calling account (`msg.sender`). @dev It emits a `CustodyAllowanceChanged` event. @dev It emits a `TotalCustodyAllowanceUpdated` event. @param custodian Address which will act as Custodian of a given amount for an account. @param amount Number of additional FDTs to be custodied by the Custodian. */ function increaseCustodyAllowance(address custodian, uint256 amount) external { uint256 oldAllowance = custodyAllowance[msg.sender][custodian]; uint256 newAllowance = oldAllowance.add(amount); uint256 newTotalAllowance = totalCustodyAllowance[msg.sender].add(amount); PoolLib.increaseCustodyAllowanceChecks(custodian, amount, newTotalAllowance, balanceOf(msg.sender)); custodyAllowance[msg.sender][custodian] = newAllowance; totalCustodyAllowance[msg.sender] = newTotalAllowance; emit CustodyAllowanceChanged(msg.sender, custodian, oldAllowance, newAllowance); emit TotalCustodyAllowanceUpdated(msg.sender, newTotalAllowance); } /** @dev Transfers custodied PoolFDTs back to the account. @dev `from` and `to` should always be equal in this implementation. @dev This means that the Custodian can only decrease their own allowance and unlock funds for the original owner. @dev It emits a `CustodyTransfer` event. @dev It emits a `CustodyAllowanceChanged` event. @dev It emits a `TotalCustodyAllowanceUpdated` event. @param from Address which holds the PoolFDTs. @param to Address which will be the new owner of the amount of PoolFDTs. @param amount Amount of PoolFDTs transferred. */ function transferByCustodian(address from, address to, uint256 amount) external { uint256 oldAllowance = custodyAllowance[from][msg.sender]; uint256 newAllowance = oldAllowance.sub(amount); PoolLib.transferByCustodianChecks(from, to, amount); custodyAllowance[from][msg.sender] = newAllowance; uint256 newTotalAllowance = totalCustodyAllowance[from].sub(amount); totalCustodyAllowance[from] = newTotalAllowance; emit CustodyTransfer(msg.sender, from, to, amount); emit CustodyAllowanceChanged(from, msg.sender, oldAllowance, newAllowance); emit TotalCustodyAllowanceUpdated(msg.sender, newTotalAllowance); } /**************************/ /*** Governor Functions ***/ /**************************/ /** @dev Transfers any locked funds to the Governor. Only the Governor can call this function. @param token Address of the token to be reclaimed. */ function reclaimERC20(address token) external { PoolLib.reclaimERC20(token, address(liquidityAsset), _globals(superFactory)); } /*************************/ /*** Getter Functions ***/ /*************************/ /** @dev Calculates the value of BPT in units of Liquidity Asset. @param _bPool Address of Balancer pool. @param _liquidityAsset Asset used by Pool for liquidity to fund Loans. @param _staker Address that deposited BPTs to StakeLocker. @param _stakeLocker Escrows BPTs deposited by Staker. @return USDC value of staker BPTs. */ function BPTVal( address _bPool, address _liquidityAsset, address _staker, address _stakeLocker ) external view returns (uint256) { return PoolLib.BPTVal(_bPool, _liquidityAsset, _staker, _stakeLocker); } /** @dev Checks that the given deposit amount is acceptable based on current liquidityCap. @param depositAmt Amount of tokens (i.e liquidityAsset type) the account is trying to deposit. */ function isDepositAllowed(uint256 depositAmt) public view returns (bool) { return (openToPublic || allowedLiquidityProviders[msg.sender]) && _balanceOfLiquidityLocker().add(principalOut).add(depositAmt) <= liquidityCap; } /** @dev Returns information on the stake requirements. @return [0] = Min amount of Liquidity Asset coverage from staking required. [1] = Present amount of Liquidity Asset coverage from the Pool Delegate stake. [2] = If enough stake is present from the Pool Delegate for finalization. [3] = Staked BPTs required for minimum Liquidity Asset coverage. [4] = Current staked BPTs. */ function getInitialStakeRequirements() public view returns (uint256, uint256, bool, uint256, uint256) { return PoolLib.getInitialStakeRequirements(_globals(superFactory), stakeAsset, address(liquidityAsset), poolDelegate, stakeLocker); } /** @dev Calculates BPTs required if burning BPTs for the Liquidity Asset, given supplied `tokenAmountOutRequired`. @param _bPool The Balancer pool that issues the BPTs. @param _liquidityAsset Swap out asset (e.g. USDC) to receive when burning BPTs. @param _staker Address that deposited BPTs to StakeLocker. @param _stakeLocker Escrows BPTs deposited by Staker. @param _liquidityAssetAmountRequired Amount of Liquidity Asset required to recover. @return [0] = poolAmountIn required. [1] = poolAmountIn currently staked. */ function getPoolSharesRequired( address _bPool, address _liquidityAsset, address _staker, address _stakeLocker, uint256 _liquidityAssetAmountRequired ) external view returns (uint256, uint256) { return PoolLib.getPoolSharesRequired(_bPool, _liquidityAsset, _staker, _stakeLocker, _liquidityAssetAmountRequired); } /** @dev Checks that the Pool state is `Finalized`. @return bool Boolean value indicating if Pool is in a Finalized state. */ function isPoolFinalized() external view returns (bool) { return poolState == State.Finalized; } /************************/ /*** Helper Functions ***/ /************************/ /** @dev Converts to WAD precision. @param amt Amount to convert. */ function _toWad(uint256 amt) internal view returns (uint256) { return amt.mul(WAD).div(10 ** liquidityAssetDecimals); } /** @dev Returns the balance of this Pool's LiquidityLocker. @return Balance of LiquidityLocker. */ function _balanceOfLiquidityLocker() internal view returns (uint256) { return liquidityAsset.balanceOf(liquidityLocker); } /** @dev Checks that the current state of Pool matches the provided state. @param _state Enum of desired Pool state. */ function _isValidState(State _state) internal view { require(poolState == _state, "P:BAD_STATE"); } /** @dev Checks that `msg.sender` is the Pool Delegate. */ function _isValidDelegate() internal view { require(msg.sender == poolDelegate, "P:NOT_DEL"); } /** @dev Returns the MapleGlobals instance. */ function _globals(address poolFactory) internal view returns (IMapleGlobals) { return IMapleGlobals(IPoolFactory(poolFactory).globals()); } /** @dev Emits a `BalanceUpdated` event for LiquidityLocker. @dev It emits a `BalanceUpdated` event. */ function _emitBalanceUpdatedEvent() internal { emit BalanceUpdated(liquidityLocker, address(liquidityAsset), _balanceOfLiquidityLocker()); } /** @dev Transfers Liquidity Asset to given `to` address, from self (i.e. `address(this)`). @param to Address to transfer liquidityAsset. @param value Amount of liquidity asset that gets transferred. */ function _transferLiquidityAsset(address to, uint256 value) internal { liquidityAsset.safeTransfer(to, value); } /** @dev Checks that `msg.sender` is the Pool Delegate or a Pool Admin. */ function _isValidDelegateOrPoolAdmin() internal view { require(msg.sender == poolDelegate || poolAdmins[msg.sender], "P:NOT_DEL_OR_ADMIN"); } /** @dev Checks that the protocol is not in a paused state. */ function _whenProtocolNotPaused() internal view { require(!_globals(superFactory).protocolPaused(), "P:PROTO_PAUSED"); } /** @dev Checks that `msg.sender` is the Pool Delegate and that the protocol is not in a paused state. */ function _isValidDelegateAndProtocolNotPaused() internal view { _isValidDelegate(); _whenProtocolNotPaused(); } function _transferLiquidityLockerFunds(address to, uint256 value) internal { ILiquidityLocker(liquidityLocker).transfer(to, value); } }
contract Pool is PoolFDT { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 constant WAD = 10 ** 18; uint8 public constant DL_FACTORY = 1; // Factory type of `DebtLockerFactory`. IERC20 public immutable liquidityAsset; // The asset deposited by Lenders into the LiquidityLocker, for funding Loans. address public immutable poolDelegate; // The Pool Delegate address, maintains full authority over the Pool. address public immutable liquidityLocker; // The LiquidityLocker owned by this contract address public immutable stakeAsset; // The address of the asset deposited by Stakers into the StakeLocker (BPTs), for liquidation during default events. address public immutable stakeLocker; // The address of the StakeLocker, escrowing `stakeAsset`. address public immutable superFactory; // The factory that deployed this Loan. uint256 private immutable liquidityAssetDecimals; // The precision for the Liquidity Asset (i.e. `decimals()`). uint256 public stakingFee; // The fee Stakers earn (in basis points). uint256 public immutable delegateFee; // The fee the Pool Delegate earns (in basis points). uint256 public principalOut; // The sum of all outstanding principal on Loans. uint256 public liquidityCap; // The amount of liquidity tokens accepted by the Pool. uint256 public lockupPeriod; // The period of time from an account's deposit date during which they cannot withdraw any funds. bool public openToPublic; // Boolean opening Pool to public for LP deposits enum State { Initialized, Finalized, Deactivated } State public poolState; mapping(address => uint256) public depositDate; // Used for withdraw penalty calculation. mapping(address => mapping(address => address)) public debtLockers; // Address of the DebtLocker corresponding to `[Loan][DebtLockerFactory]`. mapping(address => bool) public poolAdmins; // The Pool Admin addresses that have permission to do certain operations in case of disaster management. mapping(address => bool) public allowedLiquidityProviders; // Mapping that contains the list of addresses that have early access to the pool. mapping(address => uint256) public withdrawCooldown; // The timestamp of when individual LPs have notified of their intent to withdraw. mapping(address => mapping(address => uint256)) public custodyAllowance; // The amount of PoolFDTs that are "locked" at a certain address. mapping(address => uint256) public totalCustodyAllowance; // The total amount of PoolFDTs that are "locked" for a given account. Cannot be greater than an account's balance. event LoanFunded(address indexed loan, address debtLocker, uint256 amountFunded); event Claim(address indexed loan, uint256 interest, uint256 principal, uint256 fee, uint256 stakeLockerPortion, uint256 poolDelegatePortion); event BalanceUpdated(address indexed liquidityProvider, address indexed token, uint256 balance); event CustodyTransfer(address indexed custodian, address indexed from, address indexed to, uint256 amount); event CustodyAllowanceChanged(address indexed liquidityProvider, address indexed custodian, uint256 oldAllowance, uint256 newAllowance); event LPStatusChanged(address indexed liquidityProvider, bool status); event LiquidityCapSet(uint256 newLiquidityCap); event LockupPeriodSet(uint256 newLockupPeriod); event StakingFeeSet(uint256 newStakingFee); event PoolStateChanged(State state); event Cooldown(address indexed liquidityProvider, uint256 cooldown); event PoolOpenedToPublic(bool isOpen); event PoolAdminSet(address indexed poolAdmin, bool allowed); event DepositDateUpdated(address indexed liquidityProvider, uint256 depositDate); event TotalCustodyAllowanceUpdated(address indexed liquidityProvider, uint256 newTotalAllowance); event DefaultSuffered( address indexed loan, uint256 defaultSuffered, uint256 bptsBurned, uint256 bptsReturned, uint256 liquidityAssetRecoveredFromBurn ); /** Universal accounting law: fdtTotalSupply = liquidityLockerBal + principalOut - interestSum + poolLosses fdtTotalSupply + interestSum - poolLosses = liquidityLockerBal + principalOut */ /** @dev Constructor for a Pool. @dev It emits a `PoolStateChanged` event. @param _poolDelegate Address that has manager privileges of the Pool. @param _liquidityAsset Asset used to fund the Pool, It gets escrowed in LiquidityLocker. @param _stakeAsset Asset escrowed in StakeLocker. @param _slFactory Factory used to instantiate the StakeLocker. @param _llFactory Factory used to instantiate the LiquidityLocker. @param _stakingFee Fee that Stakers earn on interest, in basis points. @param _delegateFee Fee that the Pool Delegate earns on interest, in basis points. @param _liquidityCap Max amount of Liquidity Asset accepted by the Pool. @param name Name of Pool token. @param symbol Symbol of Pool token. */ constructor( address _poolDelegate, address _liquidityAsset, address _stakeAsset, address _slFactory, address _llFactory, uint256 _stakingFee, uint256 _delegateFee, uint256 _liquidityCap, string memory name, string memory symbol ) PoolFDT(name, symbol) public { // Conduct sanity checks on Pool parameters. PoolLib.poolSanityChecks(_globals(msg.sender), _liquidityAsset, _stakeAsset, _stakingFee, _delegateFee); // Assign variables relating to the Liquidity Asset. liquidityAsset = IERC20(_liquidityAsset); liquidityAssetDecimals = ERC20(_liquidityAsset).decimals(); // Assign state variables. stakeAsset = _stakeAsset; poolDelegate = _poolDelegate; stakingFee = _stakingFee; delegateFee = _delegateFee; superFactory = msg.sender; liquidityCap = _liquidityCap; // Instantiate the LiquidityLocker and the StakeLocker. stakeLocker = address(IStakeLockerFactory(_slFactory).newLocker(_stakeAsset, _liquidityAsset)); liquidityLocker = address(ILiquidityLockerFactory(_llFactory).newLocker(_liquidityAsset)); lockupPeriod = 180 days; emit PoolStateChanged(State.Initialized); } /*******************************/ /*** Pool Delegate Functions ***/ /*******************************/ /** @dev Finalizes the Pool, enabling deposits. Checks the amount the Pool Delegate deposited to the StakeLocker. Only the Pool Delegate can call this function. @dev It emits a `PoolStateChanged` event. */ function finalize() external { _isValidDelegateAndProtocolNotPaused(); _isValidState(State.Initialized); (,, bool stakeSufficient,,) = getInitialStakeRequirements(); require(stakeSufficient, "P:INSUF_STAKE"); poolState = State.Finalized; emit PoolStateChanged(poolState); } /** @dev Funds a Loan for an amount, utilizing the supplied DebtLockerFactory for DebtLockers. Only the Pool Delegate can call this function. @dev It emits a `LoanFunded` event. @dev It emits a `BalanceUpdated` event. @param loan Address of the Loan to fund. @param dlFactory Address of the DebtLockerFactory to utilize. @param amt Amount to fund the Loan. */ function fundLoan(address loan, address dlFactory, uint256 amt) external { _isValidDelegateAndProtocolNotPaused(); _isValidState(State.Finalized); principalOut = principalOut.add(amt); PoolLib.fundLoan(debtLockers, superFactory, liquidityLocker, loan, dlFactory, amt); _emitBalanceUpdatedEvent(); } /** @dev Liquidates a Loan. The Pool Delegate could liquidate the Loan only when the Loan completes its grace period. The Pool Delegate can claim its proportion of recovered funds from the liquidation using the `claim()` function. Only the Pool Delegate can call this function. @param loan Address of the Loan to liquidate. @param dlFactory Address of the DebtLockerFactory that is used to pull corresponding DebtLocker. */ function triggerDefault(address loan, address dlFactory) external { _isValidDelegateAndProtocolNotPaused(); IDebtLocker(debtLockers[loan][dlFactory]).triggerDefault(); } /** @dev Claims available funds for the Loan through a specified DebtLockerFactory. Only the Pool Delegate or a Pool Admin can call this function. @dev It emits two `BalanceUpdated` events. @dev It emits a `Claim` event. @param loan Address of the loan to claim from. @param dlFactory Address of the DebtLockerFactory. @return claimInfo The claim details. claimInfo [0] = Total amount claimed claimInfo [1] = Interest portion claimed claimInfo [2] = Principal portion claimed claimInfo [3] = Fee portion claimed claimInfo [4] = Excess portion claimed claimInfo [5] = Recovered portion claimed (from liquidations) claimInfo [6] = Default suffered */ function claim(address loan, address dlFactory) external returns (uint256[7] memory claimInfo) { _whenProtocolNotPaused(); _isValidDelegateOrPoolAdmin(); claimInfo = IDebtLocker(debtLockers[loan][dlFactory]).claim(); (uint256 poolDelegatePortion, uint256 stakeLockerPortion, uint256 principalClaim, uint256 interestClaim) = PoolLib.calculateClaimAndPortions(claimInfo, delegateFee, stakingFee); // Subtract outstanding principal by the principal claimed plus excess returned. // Considers possible `principalClaim` overflow if Liquidity Asset is transferred directly into the Loan. if (principalClaim <= principalOut) { principalOut = principalOut - principalClaim; } else { interestClaim = interestClaim.add(principalClaim - principalOut); // Distribute `principalClaim` overflow as interest to LPs. principalClaim = principalOut; // Set `principalClaim` to `principalOut` so correct amount gets transferred. principalOut = 0; // Set `principalOut` to zero to avoid subtraction overflow. } // Accounts for rounding error in StakeLocker / Pool Delegate / LiquidityLocker interest split. interestSum = interestSum.add(interestClaim); _transferLiquidityAsset(poolDelegate, poolDelegatePortion); // Transfer the fee and portion of interest to the Pool Delegate. _transferLiquidityAsset(stakeLocker, stakeLockerPortion); // Transfer the portion of interest to the StakeLocker. // Transfer remaining claim (remaining interest + principal + excess + recovered) to the LiquidityLocker. // Dust will accrue in the Pool, but this ensures that state variables are in sync with the LiquidityLocker balance updates. // Not using `balanceOf` in case of external address transferring the Liquidity Asset directly into Pool. // Ensures that internal accounting is exactly reflective of balance change. _transferLiquidityAsset(liquidityLocker, principalClaim.add(interestClaim)); // Handle default if defaultSuffered > 0. if (claimInfo[6] > 0) _handleDefault(loan, claimInfo[6]); // Update funds received for StakeLockerFDTs. IStakeLocker(stakeLocker).updateFundsReceived(); // Update funds received for PoolFDTs. updateFundsReceived(); _emitBalanceUpdatedEvent(); emit BalanceUpdated(stakeLocker, address(liquidityAsset), liquidityAsset.balanceOf(stakeLocker)); emit Claim(loan, interestClaim, principalClaim, claimInfo[3], stakeLockerPortion, poolDelegatePortion); } /** @dev Handles if a claim has been made and there is a non-zero defaultSuffered amount. @dev It emits a `DefaultSuffered` event. @param loan Address of a Loan that has defaulted. @param defaultSuffered Losses suffered from default after liquidation. */ function _handleDefault(address loan, uint256 defaultSuffered) internal { (uint256 bptsBurned, uint256 postBurnBptBal, uint256 liquidityAssetRecoveredFromBurn) = PoolLib.handleDefault(liquidityAsset, stakeLocker, stakeAsset, defaultSuffered); // If BPT burn is not enough to cover full default amount, pass on losses to LPs with PoolFDT loss accounting. if (defaultSuffered > liquidityAssetRecoveredFromBurn) { poolLosses = poolLosses.add(defaultSuffered - liquidityAssetRecoveredFromBurn); updateLossesReceived(); } // Transfer Liquidity Asset from burn to LiquidityLocker. liquidityAsset.safeTransfer(liquidityLocker, liquidityAssetRecoveredFromBurn); principalOut = principalOut.sub(defaultSuffered); // Subtract rest of the Loan's principal from `principalOut`. emit DefaultSuffered( loan, // The Loan that suffered the default. defaultSuffered, // Total default suffered from the Loan by the Pool after liquidation. bptsBurned, // Amount of BPTs burned from StakeLocker. postBurnBptBal, // Remaining BPTs in StakeLocker post-burn. liquidityAssetRecoveredFromBurn // Amount of Liquidity Asset recovered from burning BPTs. ); } /** @dev Triggers deactivation, permanently shutting down the Pool. Must have less than 100 USD worth of Liquidity Asset `principalOut`. Only the Pool Delegate can call this function. @dev It emits a `PoolStateChanged` event. */ function deactivate() external { _isValidDelegateAndProtocolNotPaused(); _isValidState(State.Finalized); PoolLib.validateDeactivation(_globals(superFactory), principalOut, address(liquidityAsset)); poolState = State.Deactivated; emit PoolStateChanged(poolState); } /**************************************/ /*** Pool Delegate Setter Functions ***/ /**************************************/ /** @dev Sets the liquidity cap. Only the Pool Delegate or a Pool Admin can call this function. @dev It emits a `LiquidityCapSet` event. @param newLiquidityCap New liquidity cap value. */ function setLiquidityCap(uint256 newLiquidityCap) external { _whenProtocolNotPaused(); _isValidDelegateOrPoolAdmin(); liquidityCap = newLiquidityCap; emit LiquidityCapSet(newLiquidityCap); } /** @dev Sets the lockup period. Only the Pool Delegate can call this function. @dev It emits a `LockupPeriodSet` event. @param newLockupPeriod New lockup period used to restrict the withdrawals. */ function setLockupPeriod(uint256 newLockupPeriod) external { _isValidDelegateAndProtocolNotPaused(); require(newLockupPeriod <= lockupPeriod, "P:BAD_VALUE"); lockupPeriod = newLockupPeriod; emit LockupPeriodSet(newLockupPeriod); } /** @dev Sets the staking fee. Only the Pool Delegate can call this function. @dev It emits a `StakingFeeSet` event. @param newStakingFee New staking fee. */ function setStakingFee(uint256 newStakingFee) external { _isValidDelegateAndProtocolNotPaused(); require(newStakingFee.add(delegateFee) <= 10_000, "P:BAD_FEE"); stakingFee = newStakingFee; emit StakingFeeSet(newStakingFee); } /** @dev Sets the account status in the Pool's allowlist. Only the Pool Delegate can call this function. @dev It emits an `LPStatusChanged` event. @param account The address to set status for. @param status The status of an account in the allowlist. */ function setAllowList(address account, bool status) external { _isValidDelegateAndProtocolNotPaused(); allowedLiquidityProviders[account] = status; emit LPStatusChanged(account, status); } /** @dev Sets a Pool Admin. Only the Pool Delegate can call this function. @dev It emits a `PoolAdminSet` event. @param poolAdmin An address being allowed or disallowed as a Pool Admin. @param allowed Status of a Pool Admin. */ function setPoolAdmin(address poolAdmin, bool allowed) external { _isValidDelegateAndProtocolNotPaused(); poolAdmins[poolAdmin] = allowed; emit PoolAdminSet(poolAdmin, allowed); } /** @dev Sets whether the Pool is open to the public. Only the Pool Delegate can call this function. @dev It emits a `PoolOpenedToPublic` event. @param open Public pool access status. */ function setOpenToPublic(bool open) external { _isValidDelegateAndProtocolNotPaused(); openToPublic = open; emit PoolOpenedToPublic(open); } /************************************/ /*** Liquidity Provider Functions ***/ /************************************/ /** @dev Handles Liquidity Providers depositing of Liquidity Asset into the LiquidityLocker, minting PoolFDTs. @dev It emits a `DepositDateUpdated` event. @dev It emits a `BalanceUpdated` event. @dev It emits a `Cooldown` event. @param amt Amount of Liquidity Asset to deposit. */ function deposit(uint256 amt) external { _whenProtocolNotPaused(); _isValidState(State.Finalized); require(isDepositAllowed(amt), "P:DEP_NOT_ALLOWED"); withdrawCooldown[msg.sender] = uint256(0); // Reset the LP's withdraw cooldown if they had previously intended to withdraw. uint256 wad = _toWad(amt); PoolLib.updateDepositDate(depositDate, balanceOf(msg.sender), wad, msg.sender); liquidityAsset.safeTransferFrom(msg.sender, liquidityLocker, amt); _mint(msg.sender, wad); _emitBalanceUpdatedEvent(); emit Cooldown(msg.sender, uint256(0)); } /** @dev Activates the cooldown period to withdraw. It can't be called if the account is not providing liquidity. @dev It emits a `Cooldown` event. **/ function intendToWithdraw() external { require(balanceOf(msg.sender) != uint256(0), "P:ZERO_BAL"); withdrawCooldown[msg.sender] = block.timestamp; emit Cooldown(msg.sender, block.timestamp); } /** @dev Cancels an initiated withdrawal by resetting the account's withdraw cooldown. @dev It emits a `Cooldown` event. **/ function cancelWithdraw() external { require(withdrawCooldown[msg.sender] != uint256(0), "P:NOT_WITHDRAWING"); withdrawCooldown[msg.sender] = uint256(0); emit Cooldown(msg.sender, uint256(0)); } /** @dev Checks that the account can withdraw an amount. @param account The address of the account. @param wad The amount to withdraw. */ function _canWithdraw(address account, uint256 wad) internal view { require(depositDate[account].add(lockupPeriod) <= block.timestamp, "P:FUNDS_LOCKED"); // Restrict withdrawal during lockup period require(balanceOf(account).sub(wad) >= totalCustodyAllowance[account], "P:INSUF_TRANS_BAL"); // Account can only withdraw tokens that aren't custodied } /** @dev Handles Liquidity Providers withdrawing of Liquidity Asset from the LiquidityLocker, burning PoolFDTs. @dev It emits two `BalanceUpdated` event. @param amt Amount of Liquidity Asset to withdraw. */ function withdraw(uint256 amt) external { _whenProtocolNotPaused(); uint256 wad = _toWad(amt); (uint256 lpCooldownPeriod, uint256 lpWithdrawWindow) = _globals(superFactory).getLpCooldownParams(); _canWithdraw(msg.sender, wad); require((block.timestamp - (withdrawCooldown[msg.sender] + lpCooldownPeriod)) <= lpWithdrawWindow, "P:WITHDRAW_NOT_ALLOWED"); _burn(msg.sender, wad); // Burn the corresponding PoolFDTs balance. withdrawFunds(); // Transfer full entitled interest, decrement `interestSum`. // Transfer amount that is due after realized losses are accounted for. // Recognized losses are absorbed by the LP. _transferLiquidityLockerFunds(msg.sender, amt.sub(_recognizeLosses())); _emitBalanceUpdatedEvent(); } /** @dev Transfers PoolFDTs. @param from Address sending PoolFDTs. @param to Address receiving PoolFDTs. @param wad Amount of PoolFDTs to transfer. */ function _transfer(address from, address to, uint256 wad) internal override { _whenProtocolNotPaused(); (uint256 lpCooldownPeriod, uint256 lpWithdrawWindow) = _globals(superFactory).getLpCooldownParams(); _canWithdraw(from, wad); require(block.timestamp > (withdrawCooldown[to] + lpCooldownPeriod + lpWithdrawWindow), "P:TO_NOT_ALLOWED"); // Recipient must not be currently withdrawing. require(recognizableLossesOf(from) == uint256(0), "P:RECOG_LOSSES"); // If an LP has unrecognized losses, they must recognize losses using `withdraw`. PoolLib.updateDepositDate(depositDate, balanceOf(to), wad, to); super._transfer(from, to, wad); } /** @dev Withdraws all claimable interest from the LiquidityLocker for an account using `interestSum` accounting. @dev It emits a `BalanceUpdated` event. */ function withdrawFunds() public override { _whenProtocolNotPaused(); uint256 withdrawableFunds = _prepareWithdraw(); if (withdrawableFunds == uint256(0)) return; _transferLiquidityLockerFunds(msg.sender, withdrawableFunds); _emitBalanceUpdatedEvent(); interestSum = interestSum.sub(withdrawableFunds); _updateFundsTokenBalance(); } /** @dev Increases the custody allowance for a given Custodian corresponding to the calling account (`msg.sender`). @dev It emits a `CustodyAllowanceChanged` event. @dev It emits a `TotalCustodyAllowanceUpdated` event. @param custodian Address which will act as Custodian of a given amount for an account. @param amount Number of additional FDTs to be custodied by the Custodian. */ function increaseCustodyAllowance(address custodian, uint256 amount) external { uint256 oldAllowance = custodyAllowance[msg.sender][custodian]; uint256 newAllowance = oldAllowance.add(amount); uint256 newTotalAllowance = totalCustodyAllowance[msg.sender].add(amount); PoolLib.increaseCustodyAllowanceChecks(custodian, amount, newTotalAllowance, balanceOf(msg.sender)); custodyAllowance[msg.sender][custodian] = newAllowance; totalCustodyAllowance[msg.sender] = newTotalAllowance; emit CustodyAllowanceChanged(msg.sender, custodian, oldAllowance, newAllowance); emit TotalCustodyAllowanceUpdated(msg.sender, newTotalAllowance); } /** @dev Transfers custodied PoolFDTs back to the account. @dev `from` and `to` should always be equal in this implementation. @dev This means that the Custodian can only decrease their own allowance and unlock funds for the original owner. @dev It emits a `CustodyTransfer` event. @dev It emits a `CustodyAllowanceChanged` event. @dev It emits a `TotalCustodyAllowanceUpdated` event. @param from Address which holds the PoolFDTs. @param to Address which will be the new owner of the amount of PoolFDTs. @param amount Amount of PoolFDTs transferred. */ function transferByCustodian(address from, address to, uint256 amount) external { uint256 oldAllowance = custodyAllowance[from][msg.sender]; uint256 newAllowance = oldAllowance.sub(amount); PoolLib.transferByCustodianChecks(from, to, amount); custodyAllowance[from][msg.sender] = newAllowance; uint256 newTotalAllowance = totalCustodyAllowance[from].sub(amount); totalCustodyAllowance[from] = newTotalAllowance; emit CustodyTransfer(msg.sender, from, to, amount); emit CustodyAllowanceChanged(from, msg.sender, oldAllowance, newAllowance); emit TotalCustodyAllowanceUpdated(msg.sender, newTotalAllowance); } /**************************/ /*** Governor Functions ***/ /**************************/ /** @dev Transfers any locked funds to the Governor. Only the Governor can call this function. @param token Address of the token to be reclaimed. */ function reclaimERC20(address token) external { PoolLib.reclaimERC20(token, address(liquidityAsset), _globals(superFactory)); } /*************************/ /*** Getter Functions ***/ /*************************/ /** @dev Calculates the value of BPT in units of Liquidity Asset. @param _bPool Address of Balancer pool. @param _liquidityAsset Asset used by Pool for liquidity to fund Loans. @param _staker Address that deposited BPTs to StakeLocker. @param _stakeLocker Escrows BPTs deposited by Staker. @return USDC value of staker BPTs. */ function BPTVal( address _bPool, address _liquidityAsset, address _staker, address _stakeLocker ) external view returns (uint256) { return PoolLib.BPTVal(_bPool, _liquidityAsset, _staker, _stakeLocker); } /** @dev Checks that the given deposit amount is acceptable based on current liquidityCap. @param depositAmt Amount of tokens (i.e liquidityAsset type) the account is trying to deposit. */ function isDepositAllowed(uint256 depositAmt) public view returns (bool) { return (openToPublic || allowedLiquidityProviders[msg.sender]) && _balanceOfLiquidityLocker().add(principalOut).add(depositAmt) <= liquidityCap; } /** @dev Returns information on the stake requirements. @return [0] = Min amount of Liquidity Asset coverage from staking required. [1] = Present amount of Liquidity Asset coverage from the Pool Delegate stake. [2] = If enough stake is present from the Pool Delegate for finalization. [3] = Staked BPTs required for minimum Liquidity Asset coverage. [4] = Current staked BPTs. */ function getInitialStakeRequirements() public view returns (uint256, uint256, bool, uint256, uint256) { return PoolLib.getInitialStakeRequirements(_globals(superFactory), stakeAsset, address(liquidityAsset), poolDelegate, stakeLocker); } /** @dev Calculates BPTs required if burning BPTs for the Liquidity Asset, given supplied `tokenAmountOutRequired`. @param _bPool The Balancer pool that issues the BPTs. @param _liquidityAsset Swap out asset (e.g. USDC) to receive when burning BPTs. @param _staker Address that deposited BPTs to StakeLocker. @param _stakeLocker Escrows BPTs deposited by Staker. @param _liquidityAssetAmountRequired Amount of Liquidity Asset required to recover. @return [0] = poolAmountIn required. [1] = poolAmountIn currently staked. */ function getPoolSharesRequired( address _bPool, address _liquidityAsset, address _staker, address _stakeLocker, uint256 _liquidityAssetAmountRequired ) external view returns (uint256, uint256) { return PoolLib.getPoolSharesRequired(_bPool, _liquidityAsset, _staker, _stakeLocker, _liquidityAssetAmountRequired); } /** @dev Checks that the Pool state is `Finalized`. @return bool Boolean value indicating if Pool is in a Finalized state. */ function isPoolFinalized() external view returns (bool) { return poolState == State.Finalized; } /************************/ /*** Helper Functions ***/ /************************/ /** @dev Converts to WAD precision. @param amt Amount to convert. */ function _toWad(uint256 amt) internal view returns (uint256) { return amt.mul(WAD).div(10 ** liquidityAssetDecimals); } /** @dev Returns the balance of this Pool's LiquidityLocker. @return Balance of LiquidityLocker. */ function _balanceOfLiquidityLocker() internal view returns (uint256) { return liquidityAsset.balanceOf(liquidityLocker); } /** @dev Checks that the current state of Pool matches the provided state. @param _state Enum of desired Pool state. */ function _isValidState(State _state) internal view { require(poolState == _state, "P:BAD_STATE"); } /** @dev Checks that `msg.sender` is the Pool Delegate. */ function _isValidDelegate() internal view { require(msg.sender == poolDelegate, "P:NOT_DEL"); } /** @dev Returns the MapleGlobals instance. */ function _globals(address poolFactory) internal view returns (IMapleGlobals) { return IMapleGlobals(IPoolFactory(poolFactory).globals()); } /** @dev Emits a `BalanceUpdated` event for LiquidityLocker. @dev It emits a `BalanceUpdated` event. */ function _emitBalanceUpdatedEvent() internal { emit BalanceUpdated(liquidityLocker, address(liquidityAsset), _balanceOfLiquidityLocker()); } /** @dev Transfers Liquidity Asset to given `to` address, from self (i.e. `address(this)`). @param to Address to transfer liquidityAsset. @param value Amount of liquidity asset that gets transferred. */ function _transferLiquidityAsset(address to, uint256 value) internal { liquidityAsset.safeTransfer(to, value); } /** @dev Checks that `msg.sender` is the Pool Delegate or a Pool Admin. */ function _isValidDelegateOrPoolAdmin() internal view { require(msg.sender == poolDelegate || poolAdmins[msg.sender], "P:NOT_DEL_OR_ADMIN"); } /** @dev Checks that the protocol is not in a paused state. */ function _whenProtocolNotPaused() internal view { require(!_globals(superFactory).protocolPaused(), "P:PROTO_PAUSED"); } /** @dev Checks that `msg.sender` is the Pool Delegate and that the protocol is not in a paused state. */ function _isValidDelegateAndProtocolNotPaused() internal view { _isValidDelegate(); _whenProtocolNotPaused(); } function _transferLiquidityLockerFunds(address to, uint256 value) internal { ILiquidityLocker(liquidityLocker).transfer(to, value); } }
60,233
85
// We need to manually run the static call since the getter cannot be flagged as view bytes4(keccak256("implementation()")) == 0x5c60da1b
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b"); require(success); return abi.decode(returndata, (address));
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b"); require(success); return abi.decode(returndata, (address));
9,561
0
// FAWC max supply will be 10k NFTs. Upon launch, we will temporarily lower this to500 to hard-cap a limited presale. After that, we will bump it back to 10k. The setMaxSupply() function below can never allow more than 10k.
uint public maxSupply = 10000; uint public mintPrice = 0.2 ether; uint public promoPrice = 0.2 ether; bool public presaleIsLive = false; string public provenanceHash; uint public reservedNFTs; bool public saleIsLive = false; uint public transactionLimit = 10; // ETH-mint limit uint public walletLimit = 50; // Not universally used ...
uint public maxSupply = 10000; uint public mintPrice = 0.2 ether; uint public promoPrice = 0.2 ether; bool public presaleIsLive = false; string public provenanceHash; uint public reservedNFTs; bool public saleIsLive = false; uint public transactionLimit = 10; // ETH-mint limit uint public walletLimit = 50; // Not universally used ...
30,765
11
// STOP or JUMP or RETURN or INVALID (Note: REVERT is blacklisted, so not included here) We are now inside unreachable code until we hit a JUMPDEST!
do { _pc++; assembly { opNum := byte(0, mload(_pc)) }
do { _pc++; assembly { opNum := byte(0, mload(_pc)) }
24,669
346
// Emitted when a Safe is gibbed./user The user who gibbed the Safe./to The recipient of the impounded collateral./assetAmount The amount of underling tokens impounded.
event SafeGibbed(address indexed user, address indexed to, uint256 assetAmount);
event SafeGibbed(address indexed user, address indexed to, uint256 assetAmount);
80,778
177
// it is not allowed to pass messages while other messages are processed
require(messageId() == bytes32(0)); require(_gas >= getMinimumGasUsage(_data) && _gas <= maxGasPerTx()); bytes32 _messageId; bytes memory header = _packHeader(_contract, _gas, _dataType); _setNonce(_nonce() + 1); assembly { _messageId := mload(add(header, 32))
require(messageId() == bytes32(0)); require(_gas >= getMinimumGasUsage(_data) && _gas <= maxGasPerTx()); bytes32 _messageId; bytes memory header = _packHeader(_contract, _gas, _dataType); _setNonce(_nonce() + 1); assembly { _messageId := mload(add(header, 32))
7,734
2
// Redemption errors
error InvalidCampaignId(); error CampaignAlreadyExists(); error InvalidCaller(address caller); error NotActive(uint256 currentTimestamp, uint256 startTime, uint256 endTime); error MaxRedemptionsReached(uint256 total, uint256 max); error MaxCampaignRedemptionsReached(uint256 total, uint256 max); error RedeemMismatchedLengths(); error TraitValueUnchanged(bytes32 traitKey, bytes32 value); error InvalidConsiderationLength(uint256 got, uint256 want); error InvalidConsiderationItem(address got, address want);
error InvalidCampaignId(); error CampaignAlreadyExists(); error InvalidCaller(address caller); error NotActive(uint256 currentTimestamp, uint256 startTime, uint256 endTime); error MaxRedemptionsReached(uint256 total, uint256 max); error MaxCampaignRedemptionsReached(uint256 total, uint256 max); error RedeemMismatchedLengths(); error TraitValueUnchanged(bytes32 traitKey, bytes32 value); error InvalidConsiderationLength(uint256 got, uint256 want); error InvalidConsiderationItem(address got, address want);
9,995
69
// Settlement only happens when state == Disputed and will only happen once per liquidation. If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.Disputed) { return; }
if (liquidation.state != Status.Disputed) { return; }
19,195
69
// iterate through future sequences until a price update is found sequence corresponding to current timestamp used as upper bound
uint256 currentPriceUpdateSequenceId = block.timestamp / (256 hours); while (sequence == 0 && sequenceId <= currentPriceUpdateSequenceId) { sequence = l.priceUpdateSequences[++sequenceId]; }
uint256 currentPriceUpdateSequenceId = block.timestamp / (256 hours); while (sequence == 0 && sequenceId <= currentPriceUpdateSequenceId) { sequence = l.priceUpdateSequences[++sequenceId]; }
51,299
52
// Returns whether `spender` is allowed to consume `tokenId`. Requirements: - `tokenId` must exist. /
function isConsumerOf(address spender, uint256 tokenId) internal view returns (bool)
function isConsumerOf(address spender, uint256 tokenId) internal view returns (bool)
17,119
25
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
assembly { word:= mload(mload(add(self, 32))) }
4,181
10
// The element is removed from the linked list, but the node retains/ information on which predecessor it had, so that a node in the chain/ can be reached by following the predecessor chain of deleted elements.
function removeKeepHistory(Data storage self, bytes32 elementToRemove) internal returns (bool)
function removeKeepHistory(Data storage self, bytes32 elementToRemove) internal returns (bool)
34,228
44
// mint OHM needed and store amount of rewards for distribution
send_ = value.sub( _profit ); IERC20Mintable( OHM ).mint( msg.sender, send_ ); totalReserves = totalReserves.add( value ); emit ReservesUpdated( totalReserves ); emit Deposit( _token, _amount, value );
send_ = value.sub( _profit ); IERC20Mintable( OHM ).mint( msg.sender, send_ ); totalReserves = totalReserves.add( value ); emit ReservesUpdated( totalReserves ); emit Deposit( _token, _amount, value );
15,304
1
// Transfers a given amount of currency.
function transferCurrency( address _currency, address _from, address _to, uint256 _amount ) internal { if (_amount == 0) { return; }
function transferCurrency( address _currency, address _from, address _to, uint256 _amount ) internal { if (_amount == 0) { return; }
2,833
12
// safe to cast because amount is positive
_mint(dst, uint104(wrapperPostPrinc - wrapperPrePrinc));
_mint(dst, uint104(wrapperPostPrinc - wrapperPrePrinc));
7,909
284
// create a bool to track if we have a non number character
bool _hasNonNumber;
bool _hasNonNumber;
33,428
105
// fallback function can be used to buy tokens /
receive() external payable { buyTokens(); }
receive() external payable { buyTokens(); }
4,578
54
// Sets the developer wallet. developerWallet The new developer wallet. /
function setDeveloperWallet( address developerWallet
function setDeveloperWallet( address developerWallet
30,895