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
81
// ERC223 function in contract &39;ContractReceiver&39;
function tokenFallback(address from, uint value, bytes data) { TokenFallback(from, value, data); }
function tokenFallback(address from, uint value, bytes data) { TokenFallback(from, value, data); }
43,742
62
// whether a buyer bought tokens through other currencies
mapping (address => bool) public isExternalBuyer; address public admin;
mapping (address => bool) public isExternalBuyer; address public admin;
54,691
37
// Claim all available rewards. Rewards accumulate linearly.return rewards The amount of accumulated rewards since the last reward claim.Each element of the array specified rewards for the correspondingindexed deposit. /
function claimAll() external override whenNotPaused updateRewards returns (uint256[] memory rewards) { // Individually claim for each stake UserStake[] storage userStakes = stakes[msg.sender]; rewards = new uint256[](userStakes.length); for (uint256 i = 0; i < userStakes.length; i++) { rewards[i] = _claim(i); } }
function claimAll() external override whenNotPaused updateRewards returns (uint256[] memory rewards) { // Individually claim for each stake UserStake[] storage userStakes = stakes[msg.sender]; rewards = new uint256[](userStakes.length); for (uint256 i = 0; i < userStakes.length; i++) { rewards[i] = _claim(i); } }
27,858
510
// --- Data structures ---
enum Status { nonExistent, active, closedByOwner }
enum Status { nonExistent, active, closedByOwner }
15,157
134
// Clear approvals from the previous owner.
assembly { if approvedAddress {
assembly { if approvedAddress {
27,624
64
// RFQ Limit Order mixin
abstract contract OrderRFQMixin is EIP712, AmountCalculator, Permitable { using SafeERC20 for IERC20; /// @notice Emitted when RFQ gets filled event OrderFilledRFQ( bytes32 orderHash, uint256 makingAmount ); struct OrderRFQ { uint256 info; // lowest 64 bits is the order id, next 64 bits is the expiration timestamp IERC20 makerAsset; IERC20 takerAsset; address maker; address allowedSender; // equals to Zero address on public orders uint256 makingAmount; uint256 takingAmount; } bytes32 constant public LIMIT_ORDER_RFQ_TYPEHASH = keccak256( "OrderRFQ(uint256 info,address makerAsset,address takerAsset,address maker,address allowedSender,uint256 makingAmount,uint256 takingAmount)" ); mapping(address => mapping(uint256 => uint256)) private _invalidator; /// @notice Returns bitmask for double-spend invalidators based on lowest byte of order.info and filled quotes /// @return Result Each bit represents whether corresponding was already invalidated function invalidatorForOrderRFQ(address maker, uint256 slot) external view returns(uint256) { return _invalidator[maker][slot]; } /// @notice Cancels order's quote function cancelOrderRFQ(uint256 orderInfo) external { _invalidateOrder(msg.sender, orderInfo); } /// @notice Fills order's quote, fully or partially (whichever is possible) /// @param order Order quote to fill /// @param signature Signature to confirm quote ownership /// @param makingAmount Making amount /// @param takingAmount Taking amount function fillOrderRFQ( OrderRFQ memory order, bytes calldata signature, uint256 makingAmount, uint256 takingAmount ) external returns(uint256, uint256) { return fillOrderRFQTo(order, signature, makingAmount, takingAmount, msg.sender); } /// @notice Fills Same as `fillOrderRFQ` but calls permit first, /// allowing to approve token spending and make a swap in one transaction. /// Also allows to specify funds destination instead of `msg.sender` /// @param order Order quote to fill /// @param signature Signature to confirm quote ownership /// @param makingAmount Making amount /// @param takingAmount Taking amount /// @param target Address that will receive swap funds /// @param permit Should consist of abiencoded token address and encoded `IERC20Permit.permit` call. /// @dev See tests for examples function fillOrderRFQToWithPermit( OrderRFQ memory order, bytes calldata signature, uint256 makingAmount, uint256 takingAmount, address target, bytes calldata permit ) external returns(uint256, uint256) { _permit(address(order.takerAsset), permit); return fillOrderRFQTo(order, signature, makingAmount, takingAmount, target); } /// @notice Same as `fillOrderRFQ` but allows to specify funds destination instead of `msg.sender` /// @param order Order quote to fill /// @param signature Signature to confirm quote ownership /// @param makingAmount Making amount /// @param takingAmount Taking amount /// @param target Address that will receive swap funds function fillOrderRFQTo( OrderRFQ memory order, bytes calldata signature, uint256 makingAmount, uint256 takingAmount, address target ) public returns(uint256, uint256) { require(target != address(0), "LOP: zero target is forbidden"); address maker = order.maker; // Validate order require(order.allowedSender == address(0) || order.allowedSender == msg.sender, "LOP: private order"); bytes32 orderHash = _hashTypedDataV4(keccak256(abi.encode(LIMIT_ORDER_RFQ_TYPEHASH, order))); require(SignatureChecker.isValidSignatureNow(maker, orderHash, signature), "LOP: bad signature"); { // Stack too deep uint256 info = order.info; // Check time expiration uint256 expiration = uint128(info) >> 64; require(expiration == 0 || block.timestamp <= expiration, "LOP: order expired"); // solhint-disable-line not-rely-on-time _invalidateOrder(maker, info); } { // stack too deep uint256 orderMakingAmount = order.makingAmount; uint256 orderTakingAmount = order.takingAmount; // Compute partial fill if needed if (takingAmount == 0 && makingAmount == 0) { // Two zeros means whole order makingAmount = orderMakingAmount; takingAmount = orderTakingAmount; } else if (takingAmount == 0) { require(makingAmount <= orderMakingAmount, "LOP: making amount exceeded"); takingAmount = getTakerAmount(orderMakingAmount, orderTakingAmount, makingAmount); } else if (makingAmount == 0) { require(takingAmount <= orderTakingAmount, "LOP: taking amount exceeded"); makingAmount = getMakerAmount(orderMakingAmount, orderTakingAmount, takingAmount); } else { revert("LOP: both amounts are non-zero"); } } require(makingAmount > 0 && takingAmount > 0, "LOP: can't swap 0 amount"); // Maker => Taker, Taker => Maker order.makerAsset.safeTransferFrom(maker, target, makingAmount); order.takerAsset.safeTransferFrom(msg.sender, maker, takingAmount); emit OrderFilledRFQ(orderHash, makingAmount); return (makingAmount, takingAmount); } function _invalidateOrder(address maker, uint256 orderInfo) private { uint256 invalidatorSlot = uint64(orderInfo) >> 8; uint256 invalidatorBit = 1 << uint8(orderInfo); mapping(uint256 => uint256) storage invalidatorStorage = _invalidator[maker]; uint256 invalidator = invalidatorStorage[invalidatorSlot]; require(invalidator & invalidatorBit == 0, "LOP: invalidated order"); invalidatorStorage[invalidatorSlot] = invalidator | invalidatorBit; } }
abstract contract OrderRFQMixin is EIP712, AmountCalculator, Permitable { using SafeERC20 for IERC20; /// @notice Emitted when RFQ gets filled event OrderFilledRFQ( bytes32 orderHash, uint256 makingAmount ); struct OrderRFQ { uint256 info; // lowest 64 bits is the order id, next 64 bits is the expiration timestamp IERC20 makerAsset; IERC20 takerAsset; address maker; address allowedSender; // equals to Zero address on public orders uint256 makingAmount; uint256 takingAmount; } bytes32 constant public LIMIT_ORDER_RFQ_TYPEHASH = keccak256( "OrderRFQ(uint256 info,address makerAsset,address takerAsset,address maker,address allowedSender,uint256 makingAmount,uint256 takingAmount)" ); mapping(address => mapping(uint256 => uint256)) private _invalidator; /// @notice Returns bitmask for double-spend invalidators based on lowest byte of order.info and filled quotes /// @return Result Each bit represents whether corresponding was already invalidated function invalidatorForOrderRFQ(address maker, uint256 slot) external view returns(uint256) { return _invalidator[maker][slot]; } /// @notice Cancels order's quote function cancelOrderRFQ(uint256 orderInfo) external { _invalidateOrder(msg.sender, orderInfo); } /// @notice Fills order's quote, fully or partially (whichever is possible) /// @param order Order quote to fill /// @param signature Signature to confirm quote ownership /// @param makingAmount Making amount /// @param takingAmount Taking amount function fillOrderRFQ( OrderRFQ memory order, bytes calldata signature, uint256 makingAmount, uint256 takingAmount ) external returns(uint256, uint256) { return fillOrderRFQTo(order, signature, makingAmount, takingAmount, msg.sender); } /// @notice Fills Same as `fillOrderRFQ` but calls permit first, /// allowing to approve token spending and make a swap in one transaction. /// Also allows to specify funds destination instead of `msg.sender` /// @param order Order quote to fill /// @param signature Signature to confirm quote ownership /// @param makingAmount Making amount /// @param takingAmount Taking amount /// @param target Address that will receive swap funds /// @param permit Should consist of abiencoded token address and encoded `IERC20Permit.permit` call. /// @dev See tests for examples function fillOrderRFQToWithPermit( OrderRFQ memory order, bytes calldata signature, uint256 makingAmount, uint256 takingAmount, address target, bytes calldata permit ) external returns(uint256, uint256) { _permit(address(order.takerAsset), permit); return fillOrderRFQTo(order, signature, makingAmount, takingAmount, target); } /// @notice Same as `fillOrderRFQ` but allows to specify funds destination instead of `msg.sender` /// @param order Order quote to fill /// @param signature Signature to confirm quote ownership /// @param makingAmount Making amount /// @param takingAmount Taking amount /// @param target Address that will receive swap funds function fillOrderRFQTo( OrderRFQ memory order, bytes calldata signature, uint256 makingAmount, uint256 takingAmount, address target ) public returns(uint256, uint256) { require(target != address(0), "LOP: zero target is forbidden"); address maker = order.maker; // Validate order require(order.allowedSender == address(0) || order.allowedSender == msg.sender, "LOP: private order"); bytes32 orderHash = _hashTypedDataV4(keccak256(abi.encode(LIMIT_ORDER_RFQ_TYPEHASH, order))); require(SignatureChecker.isValidSignatureNow(maker, orderHash, signature), "LOP: bad signature"); { // Stack too deep uint256 info = order.info; // Check time expiration uint256 expiration = uint128(info) >> 64; require(expiration == 0 || block.timestamp <= expiration, "LOP: order expired"); // solhint-disable-line not-rely-on-time _invalidateOrder(maker, info); } { // stack too deep uint256 orderMakingAmount = order.makingAmount; uint256 orderTakingAmount = order.takingAmount; // Compute partial fill if needed if (takingAmount == 0 && makingAmount == 0) { // Two zeros means whole order makingAmount = orderMakingAmount; takingAmount = orderTakingAmount; } else if (takingAmount == 0) { require(makingAmount <= orderMakingAmount, "LOP: making amount exceeded"); takingAmount = getTakerAmount(orderMakingAmount, orderTakingAmount, makingAmount); } else if (makingAmount == 0) { require(takingAmount <= orderTakingAmount, "LOP: taking amount exceeded"); makingAmount = getMakerAmount(orderMakingAmount, orderTakingAmount, takingAmount); } else { revert("LOP: both amounts are non-zero"); } } require(makingAmount > 0 && takingAmount > 0, "LOP: can't swap 0 amount"); // Maker => Taker, Taker => Maker order.makerAsset.safeTransferFrom(maker, target, makingAmount); order.takerAsset.safeTransferFrom(msg.sender, maker, takingAmount); emit OrderFilledRFQ(orderHash, makingAmount); return (makingAmount, takingAmount); } function _invalidateOrder(address maker, uint256 orderInfo) private { uint256 invalidatorSlot = uint64(orderInfo) >> 8; uint256 invalidatorBit = 1 << uint8(orderInfo); mapping(uint256 => uint256) storage invalidatorStorage = _invalidator[maker]; uint256 invalidator = invalidatorStorage[invalidatorSlot]; require(invalidator & invalidatorBit == 0, "LOP: invalidated order"); invalidatorStorage[invalidatorSlot] = invalidator | invalidatorBit; } }
49,459
192
// import { ISetToken } from "./ISetToken.sol";
function getRequiredComponentIssuanceUnits( ISetToken _setToken, uint256 _quantity ) external view returns(address[] memory, uint256[] memory, uint256[] memory); function getRequiredComponentRedemptionUnits( ISetToken _setToken, uint256 _quantity ) external view returns(address[] memory, uint256[] memory, uint256[] memory);
function getRequiredComponentIssuanceUnits( ISetToken _setToken, uint256 _quantity ) external view returns(address[] memory, uint256[] memory, uint256[] memory); function getRequiredComponentRedemptionUnits( ISetToken _setToken, uint256 _quantity ) external view returns(address[] memory, uint256[] memory, uint256[] memory);
40,889
6
// Guard function that forces a revert if the tx sender is unauthorized.Always authorizes org owner. Can also authorize org members.membersAllowed if true, revert when sender is non-owner and non-member, else revert when sender is non-owner/
function requireAuthorization(bytes32 orgId, bool membersAllowed) internal view { require(msg.sender == orgsById[orgId].owner || (membersAllowed && orgsById[orgId].members[msg.sender] > 0) , "unauthorized invocation"); }
function requireAuthorization(bytes32 orgId, bool membersAllowed) internal view { require(msg.sender == orgsById[orgId].owner || (membersAllowed && orgsById[orgId].members[msg.sender] > 0) , "unauthorized invocation"); }
10,359
4
// GETTERS/
function getType() public view returns (AuctionType) { return _type; }
function getType() public view returns (AuctionType) { return _type; }
10,498
247
// Adjust token rewards for staking
tokenRewardForStaking += (newMultiplier * adjustedRewardPerBlockForStaking);
tokenRewardForStaking += (newMultiplier * adjustedRewardPerBlockForStaking);
52,880
140
// Fix first deployment bug /
function setSlotAmount(address account, uint256 amount) external onlyAdmin { bulkLookup[account].amount = amount; }
function setSlotAmount(address account, uint256 amount) external onlyAdmin { bulkLookup[account].amount = amount; }
41,409
27
// Locks tokens for listing during challenge
listings[domainHash].unstakedDeposit -= deposit; _Challenge(_domain, deposit, pollID); return pollID;
listings[domainHash].unstakedDeposit -= deposit; _Challenge(_domain, deposit, pollID); return pollID;
33,378
97
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; }
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; }
1,593
38
// Main Contract call this function to setup mini game./
function setupMiniGame( uint256 /*_miningWarRoundNumber*/, uint256 /*_miningWarDeadline*/ ) public
function setupMiniGame( uint256 /*_miningWarRoundNumber*/, uint256 /*_miningWarDeadline*/ ) public
14,868
225
// calculate the amount of tokens the customer receives over his purchase
_fee = _amountOfTokens * (_dividends * magnitude / _totalSupply);
_fee = _amountOfTokens * (_dividends * magnitude / _totalSupply);
31,597
47
// cleanCtxisAgreement(agreementClass)
returns(bytes memory returnedData);
returns(bytes memory returnedData);
12,743
96
// Registers `_label` username to `ensNode` setting msg.sender as owner. _owner Address registering the user and paying registry price. _label Choosen unowned username hash. _account Optional address to set at public resolver. _pubkeyA Optional pubkey part A to set at public resolver. _pubkeyB Optional pubkey part B to set at public resolver. /
function registerUser( address _owner, bytes32 _label, address _account, bytes32 _pubkeyA, bytes32 _pubkeyB ) internal returns(bytes32 namehash)
function registerUser( address _owner, bytes32 _label, address _account, bytes32 _pubkeyA, bytes32 _pubkeyB ) internal returns(bytes32 namehash)
51,147
9
// createAlarm A root key holder can call this method to create an alarm clock. This method will revert if the root key isn't held, the snooze key ID is not within the trust's key ring, or if there happens to bea duplicate event for some reason. If the snoozeInterval is zero, then the snoozeKeyId is considered invalid.In these cases, snoozeKeyId is likely "0", but it's meaningless in the contextof a zero snooze interval - as it means that an alarm can not be snoozed.The base case in this scenario is the the alarm expired and can be challenged,but the alarm
function createAlarm(uint256 rootKeyId, bytes32 description, uint256 alarmTime, uint256 snoozeInterval, uint256 snoozeKeyId) external returns (bytes32) {
function createAlarm(uint256 rootKeyId, bytes32 description, uint256 alarmTime, uint256 snoozeInterval, uint256 snoozeKeyId) external returns (bytes32) {
12,525
15
// Get a snapshot of the account's balances, and the cached exchange rate This is used by controller to more efficiently perform liquidity checks. account Address of the account to snapshotreturn (possible error, token balance, borrow balance, exchange rate mantissa) /
function getAccountSnapshot(address account) external view override returns (uint, uint, uint, uint) { uint pTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), pTokenBalance, borrowBalance, exchangeRateMantissa); }
function getAccountSnapshot(address account) external view override returns (uint, uint, uint, uint) { uint pTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), pTokenBalance, borrowBalance, exchangeRateMantissa); }
39,408
10
// remove the guarantee
delete guarantees[index]; guaranteesCount--;
delete guarantees[index]; guaranteesCount--;
41,119
23
// revert token
TransferHelper.safeTransfer(order.sellToken,order.user,order.amountIn);
TransferHelper.safeTransfer(order.sellToken,order.user,order.amountIn);
34,792
153
// BWE
contract ANAL is ERC20, Ownable { /// STATE VARIABLES /// /// @notice Address of UniswapV2Router IUniswapV2Router02 public immutable uniswapV2Router; /// @notice Address of QWN/ETH LP address public immutable uniswapV2Pair; /// @notice Burn address address public constant deadAddress = address(0xdead); /// @notice WETH address address public immutable WETH; /// @notice QWN treasury address public treasury; /// @notice Team wallet address address public teamWallet; bool private swapping; /// @notice Bool if trading is active bool public tradingActive = false; /// @notice Bool if swap is enabled bool public swapEnabled = false; /// @notice Bool if limits are in effect bool public limitsInEffect = true; /// @notice Current max wallet amount (If limits in effect) uint256 public maxWallet; /// @notice Current max transaction amount (If limits in effect) uint256 public maxTransactionAmount; /// @notice Current percent of supply to swap tokens at (i.e. 5 = 0.05%) uint256 public swapPercent; /// @notice Current buy side total fees uint256 public buyTotalFees; /// @notice Current buy side backing fee uint256 public buyBackingFee; /// @notice Current buy side liquidity fee uint256 public buyLiquidityFee; /// @notice Current buy side team fee uint256 public buyTeamFee; /// @notice Current sell side total fees uint256 public sellTotalFees; /// @notice Current sell side backing fee uint256 public sellBackingFee; /// @notice Current sell side liquidity fee uint256 public sellLiquidityFee; /// @notice Current sell side team fee uint256 public sellTeamFee; /// @notice Current tokens going for backing uint256 public tokensForBacking; /// @notice Current tokens going for liquidity uint256 public tokensForLiquidity; /// @notice Current tokens going for tean uint256 public tokensForTeam; /// MAPPINGS /// /// @dev Bool if address is excluded from fees mapping(address => bool) private _isExcludedFromFees; /// @notice Bool if address is excluded from max transaction amount mapping(address => bool) public _isExcludedMaxTransactionAmount; /// @notice Bool if address is AMM pair mapping(address => bool) public automatedMarketMakerPairs; /// EVENTS /// event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event teamWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); /// CONSTRUCTOR /// constructor() ERC20("We Love Anal", "CANADA") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); WETH = _uniswapV2Router.WETH(); uint256 startingSupply_ = 25000000000000; uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyBackingFee = 2; uint256 _buyLiquidityFee = 1; uint256 _buyTeamFee = 2; uint256 _sellBackingFee = 2; uint256 _sellLiquidityFee = 1; uint256 _sellTeamFee = 2; maxWallet = 3 * 250 * 1e9; // 3% maxTransactionAmount = 3 * 250 * 1e9; // 3% swapPercent = 25; // 0.25% buyBackingFee = _buyBackingFee; buyLiquidityFee = _buyLiquidityFee; buyTeamFee = _buyTeamFee; buyTotalFees = buyBackingFee + buyLiquidityFee + buyTeamFee; sellBackingFee = _sellBackingFee; sellLiquidityFee = _sellLiquidityFee; sellTeamFee = _sellTeamFee; sellTotalFees = sellBackingFee + sellLiquidityFee + sellTeamFee; teamWallet = owner(); // set as team 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(msg.sender, startingSupply_); } receive() external payable {} /// AMM PAIR /// /// @notice Sets if address is AMM pair /// @param pair Address of pair /// @param value Bool if AMM pair function setAutomatedMarketMakerPair( address pair, bool value ) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } /// @dev Internal function to set `vlaue` of `pair` function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } /// INTERNAL TRANSFER /// /// @dev Internal function to burn `amount` from `account` function _burnFrom(address account, uint256 amount) internal { uint256 decreasedAllowance_ = allowance(account, msg.sender) - amount; _approve(account, msg.sender, decreasedAllowance_); _burn(account, amount); } /// @dev Internal function to transfer - handles fee logic 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." ); } //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; } 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 * sellTotalFees) / 100; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForBacking += (fees * sellBackingFee) / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = (amount * buyTotalFees) / 100; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForBacking += (fees * buyBackingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } /// INTERNAL FUNCTION /// /// @dev INTERNAL function to swap `tokenAmount` for ETH /// @dev Invoked in `swapBack()` function swapTokensForEth(uint256 tokenAmount) internal { // 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 ); } /// @dev INTERNAL function to add `tokenAmount` and `ethAmount` to LP /// @dev Invoked in `swapBack()` function addLiquidity(uint256 tokenAmount, uint256 ethAmount) internal { // 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 treasury, block.timestamp ); } /// @dev INTERNAL function to transfer fees properly /// @dev Invoked in `_transfer()` function swapBack() internal { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForBacking + tokensForTeam; 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 - liquidityTokens; uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance - initialETHBalance; uint256 ethForBacking = (ethBalance * tokensForBacking) / totalTokensToSwap - (tokensForLiquidity / 2); uint256 ethForTeam = (ethBalance * tokensForTeam) / totalTokensToSwap - (tokensForLiquidity / 2); uint256 ethForLiquidity = ethBalance - ethForBacking - ethForTeam; tokensForLiquidity = 0; tokensForBacking = 0; tokensForTeam = 0; (success, ) = address(teamWallet).call{value: ethForTeam}(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } uint256 _balance = address(this).balance; IWETH(WETH).deposit{value: _balance}(); IERC20(WETH).transfer(treasury, _balance); } /// VIEW FUNCTION /// /// @notice Returns decimals for QWN (9) function decimals() public view virtual override returns (uint8) { return 9; } /// @notice Returns if address is excluded from fees function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } /// @notice Returns at what percent of supply to swap tokens at function swapTokensAtAmount() public view returns (uint256 amount_) { amount_ = (totalSupply() * swapPercent) / 10000; } /// TREASURY FUNCTION /// /// @notice Mint QWN (Only by treasury) /// @param account Address to mint QWN to /// @param amount Amount to mint function mint(address account, uint256 amount) external { require(msg.sender == treasury, "msg.sender not treasury"); _mint(account, amount); } /// USER FUNCTIONS /// /// @notice Burn QWN /// @param account Address to burn QWN from /// @param amount Amount to QWN to burn function burnFrom(address account, uint256 amount) external { _burnFrom(account, amount); } /// @notice Burn QWN /// @param amount Amount to QWN to burn function burn(uint256 amount) external { _burn(msg.sender, amount); } /// OWNER FUNCTIONS /// /// @notice Set address of treasury function setTreasury(address _treasury) external onlyOwner { treasury = _treasury; excludeFromFees(_treasury, true); excludeFromMaxTransaction(_treasury, true); } /// @notice Enable trading - once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; } /// @notice Update percent of supply to swap tokens at function updateSwapTokensAtPercent( uint256 newPercent ) external onlyOwner returns (bool) { require( newPercent >= 1, "Swap amount cannot be lower than 0.01% total supply." ); require( newPercent <= 50, "Swap amount cannot be higher than 0.50% total supply." ); swapPercent = newPercent; return true; } /// @notice Update swap enabled /// @dev Only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } /// @notice Update buy side fees function updateBuyFees( uint256 _backingFee, uint256 _liquidityFee, uint256 _teamFee ) external onlyOwner { buyBackingFee = _backingFee; buyLiquidityFee = _liquidityFee; buyTeamFee = _teamFee; buyTotalFees = buyBackingFee + buyLiquidityFee + buyTeamFee; require(buyTotalFees <= 5, "Buy fees must be <= 5."); } /// @notice Update sell side fees function updateSellFees( uint256 _backingFee, uint256 _liquidityFee, uint256 _teamFee ) external onlyOwner { sellBackingFee = _backingFee; sellLiquidityFee = _liquidityFee; sellTeamFee = _teamFee; sellTotalFees = sellBackingFee + sellLiquidityFee + sellTeamFee; require(sellTotalFees <= 5, "Sell fees must be <= 5."); } /// @notice Set if an address is excluded from fees function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } /// @notice Set if an address is excluded from max transaction function excludeFromMaxTransaction( address updAds, bool isEx ) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } /// @notice Update team wallet function updateTeamWallet(address newWallet) external onlyOwner { emit teamWalletUpdated(newWallet, teamWallet); teamWallet = newWallet; excludeFromFees(newWallet, true); excludeFromMaxTransaction(newWallet, true); } /// @notice Remove limits in palce function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } /// @notice Withdraw stuck QWN from contract function withdrawStuckQWN() external onlyOwner { uint256 balance = IERC20(address(this)).balanceOf(address(this)); IERC20(address(this)).transfer(msg.sender, balance); payable(msg.sender).transfer(address(this).balance); } /// @notice Withdraw stuck token from contract function withdrawStuckToken( address _token, address _to ) external onlyOwner { require(_token != address(0), "_token address cannot be 0"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); IERC20(_token).transfer(_to, _contractBalance); } /// @notice Withdraw stuck ETH from contract function withdrawStuckEth(address toAddr) external onlyOwner { (bool success, ) = toAddr.call{value: address(this).balance}(""); require(success); } }
contract ANAL is ERC20, Ownable { /// STATE VARIABLES /// /// @notice Address of UniswapV2Router IUniswapV2Router02 public immutable uniswapV2Router; /// @notice Address of QWN/ETH LP address public immutable uniswapV2Pair; /// @notice Burn address address public constant deadAddress = address(0xdead); /// @notice WETH address address public immutable WETH; /// @notice QWN treasury address public treasury; /// @notice Team wallet address address public teamWallet; bool private swapping; /// @notice Bool if trading is active bool public tradingActive = false; /// @notice Bool if swap is enabled bool public swapEnabled = false; /// @notice Bool if limits are in effect bool public limitsInEffect = true; /// @notice Current max wallet amount (If limits in effect) uint256 public maxWallet; /// @notice Current max transaction amount (If limits in effect) uint256 public maxTransactionAmount; /// @notice Current percent of supply to swap tokens at (i.e. 5 = 0.05%) uint256 public swapPercent; /// @notice Current buy side total fees uint256 public buyTotalFees; /// @notice Current buy side backing fee uint256 public buyBackingFee; /// @notice Current buy side liquidity fee uint256 public buyLiquidityFee; /// @notice Current buy side team fee uint256 public buyTeamFee; /// @notice Current sell side total fees uint256 public sellTotalFees; /// @notice Current sell side backing fee uint256 public sellBackingFee; /// @notice Current sell side liquidity fee uint256 public sellLiquidityFee; /// @notice Current sell side team fee uint256 public sellTeamFee; /// @notice Current tokens going for backing uint256 public tokensForBacking; /// @notice Current tokens going for liquidity uint256 public tokensForLiquidity; /// @notice Current tokens going for tean uint256 public tokensForTeam; /// MAPPINGS /// /// @dev Bool if address is excluded from fees mapping(address => bool) private _isExcludedFromFees; /// @notice Bool if address is excluded from max transaction amount mapping(address => bool) public _isExcludedMaxTransactionAmount; /// @notice Bool if address is AMM pair mapping(address => bool) public automatedMarketMakerPairs; /// EVENTS /// event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event teamWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); /// CONSTRUCTOR /// constructor() ERC20("We Love Anal", "CANADA") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); WETH = _uniswapV2Router.WETH(); uint256 startingSupply_ = 25000000000000; uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyBackingFee = 2; uint256 _buyLiquidityFee = 1; uint256 _buyTeamFee = 2; uint256 _sellBackingFee = 2; uint256 _sellLiquidityFee = 1; uint256 _sellTeamFee = 2; maxWallet = 3 * 250 * 1e9; // 3% maxTransactionAmount = 3 * 250 * 1e9; // 3% swapPercent = 25; // 0.25% buyBackingFee = _buyBackingFee; buyLiquidityFee = _buyLiquidityFee; buyTeamFee = _buyTeamFee; buyTotalFees = buyBackingFee + buyLiquidityFee + buyTeamFee; sellBackingFee = _sellBackingFee; sellLiquidityFee = _sellLiquidityFee; sellTeamFee = _sellTeamFee; sellTotalFees = sellBackingFee + sellLiquidityFee + sellTeamFee; teamWallet = owner(); // set as team 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(msg.sender, startingSupply_); } receive() external payable {} /// AMM PAIR /// /// @notice Sets if address is AMM pair /// @param pair Address of pair /// @param value Bool if AMM pair function setAutomatedMarketMakerPair( address pair, bool value ) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } /// @dev Internal function to set `vlaue` of `pair` function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } /// INTERNAL TRANSFER /// /// @dev Internal function to burn `amount` from `account` function _burnFrom(address account, uint256 amount) internal { uint256 decreasedAllowance_ = allowance(account, msg.sender) - amount; _approve(account, msg.sender, decreasedAllowance_); _burn(account, amount); } /// @dev Internal function to transfer - handles fee logic 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." ); } //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; } 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 * sellTotalFees) / 100; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForBacking += (fees * sellBackingFee) / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = (amount * buyTotalFees) / 100; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForBacking += (fees * buyBackingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } /// INTERNAL FUNCTION /// /// @dev INTERNAL function to swap `tokenAmount` for ETH /// @dev Invoked in `swapBack()` function swapTokensForEth(uint256 tokenAmount) internal { // 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 ); } /// @dev INTERNAL function to add `tokenAmount` and `ethAmount` to LP /// @dev Invoked in `swapBack()` function addLiquidity(uint256 tokenAmount, uint256 ethAmount) internal { // 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 treasury, block.timestamp ); } /// @dev INTERNAL function to transfer fees properly /// @dev Invoked in `_transfer()` function swapBack() internal { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForBacking + tokensForTeam; 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 - liquidityTokens; uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance - initialETHBalance; uint256 ethForBacking = (ethBalance * tokensForBacking) / totalTokensToSwap - (tokensForLiquidity / 2); uint256 ethForTeam = (ethBalance * tokensForTeam) / totalTokensToSwap - (tokensForLiquidity / 2); uint256 ethForLiquidity = ethBalance - ethForBacking - ethForTeam; tokensForLiquidity = 0; tokensForBacking = 0; tokensForTeam = 0; (success, ) = address(teamWallet).call{value: ethForTeam}(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } uint256 _balance = address(this).balance; IWETH(WETH).deposit{value: _balance}(); IERC20(WETH).transfer(treasury, _balance); } /// VIEW FUNCTION /// /// @notice Returns decimals for QWN (9) function decimals() public view virtual override returns (uint8) { return 9; } /// @notice Returns if address is excluded from fees function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } /// @notice Returns at what percent of supply to swap tokens at function swapTokensAtAmount() public view returns (uint256 amount_) { amount_ = (totalSupply() * swapPercent) / 10000; } /// TREASURY FUNCTION /// /// @notice Mint QWN (Only by treasury) /// @param account Address to mint QWN to /// @param amount Amount to mint function mint(address account, uint256 amount) external { require(msg.sender == treasury, "msg.sender not treasury"); _mint(account, amount); } /// USER FUNCTIONS /// /// @notice Burn QWN /// @param account Address to burn QWN from /// @param amount Amount to QWN to burn function burnFrom(address account, uint256 amount) external { _burnFrom(account, amount); } /// @notice Burn QWN /// @param amount Amount to QWN to burn function burn(uint256 amount) external { _burn(msg.sender, amount); } /// OWNER FUNCTIONS /// /// @notice Set address of treasury function setTreasury(address _treasury) external onlyOwner { treasury = _treasury; excludeFromFees(_treasury, true); excludeFromMaxTransaction(_treasury, true); } /// @notice Enable trading - once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; } /// @notice Update percent of supply to swap tokens at function updateSwapTokensAtPercent( uint256 newPercent ) external onlyOwner returns (bool) { require( newPercent >= 1, "Swap amount cannot be lower than 0.01% total supply." ); require( newPercent <= 50, "Swap amount cannot be higher than 0.50% total supply." ); swapPercent = newPercent; return true; } /// @notice Update swap enabled /// @dev Only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } /// @notice Update buy side fees function updateBuyFees( uint256 _backingFee, uint256 _liquidityFee, uint256 _teamFee ) external onlyOwner { buyBackingFee = _backingFee; buyLiquidityFee = _liquidityFee; buyTeamFee = _teamFee; buyTotalFees = buyBackingFee + buyLiquidityFee + buyTeamFee; require(buyTotalFees <= 5, "Buy fees must be <= 5."); } /// @notice Update sell side fees function updateSellFees( uint256 _backingFee, uint256 _liquidityFee, uint256 _teamFee ) external onlyOwner { sellBackingFee = _backingFee; sellLiquidityFee = _liquidityFee; sellTeamFee = _teamFee; sellTotalFees = sellBackingFee + sellLiquidityFee + sellTeamFee; require(sellTotalFees <= 5, "Sell fees must be <= 5."); } /// @notice Set if an address is excluded from fees function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } /// @notice Set if an address is excluded from max transaction function excludeFromMaxTransaction( address updAds, bool isEx ) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } /// @notice Update team wallet function updateTeamWallet(address newWallet) external onlyOwner { emit teamWalletUpdated(newWallet, teamWallet); teamWallet = newWallet; excludeFromFees(newWallet, true); excludeFromMaxTransaction(newWallet, true); } /// @notice Remove limits in palce function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } /// @notice Withdraw stuck QWN from contract function withdrawStuckQWN() external onlyOwner { uint256 balance = IERC20(address(this)).balanceOf(address(this)); IERC20(address(this)).transfer(msg.sender, balance); payable(msg.sender).transfer(address(this).balance); } /// @notice Withdraw stuck token from contract function withdrawStuckToken( address _token, address _to ) external onlyOwner { require(_token != address(0), "_token address cannot be 0"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); IERC20(_token).transfer(_to, _contractBalance); } /// @notice Withdraw stuck ETH from contract function withdrawStuckEth(address toAddr) external onlyOwner { (bool success, ) = toAddr.call{value: address(this).balance}(""); require(success); } }
24,913
2
// Adds to the overall amount of tokens generated in the contract /
function _addSupply(uint256 supply) internal virtual { _supply += supply; }
function _addSupply(uint256 supply) internal virtual { _supply += supply; }
42,374
2
// Get 1000 free DAI
function getFreeDai() external{ _mint(msg.sender, 10000*1e18); }
function getFreeDai() external{ _mint(msg.sender, 10000*1e18); }
17,664
24
// COPIED FROM https:github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol Copyright 2020 Compound Labs, Inc. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived
contract Timelock { using SafeMath for uint; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); uint public constant GRACE_PERIOD = 14 days; uint public constant MINIMUM_DELAY = 2 days; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; bool public admin_initialized; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_) public { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; admin_initialized = false; } // XXX: function() external payable { } receive() external payable { } function setDelay(uint delay_) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { // allows one time setting of admin for deployment purposes if (admin_initialized) { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); } else { require(msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin."); admin_initialized = true; } pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) { require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{value: value}(callData); require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint) { // solium-disable-next-line security/no-block-members return block.timestamp; } }
contract Timelock { using SafeMath for uint; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); uint public constant GRACE_PERIOD = 14 days; uint public constant MINIMUM_DELAY = 2 days; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; bool public admin_initialized; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_) public { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; admin_initialized = false; } // XXX: function() external payable { } receive() external payable { } function setDelay(uint delay_) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { // allows one time setting of admin for deployment purposes if (admin_initialized) { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); } else { require(msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin."); admin_initialized = true; } pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) { require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{value: value}(callData); require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint) { // solium-disable-next-line security/no-block-members return block.timestamp; } }
45,039
5
// Gets the Foundation treasury contract. This call is used in the royalty registry contract.return treasuryAddress The address of the Foundation treasury contract. /
function getFoundationTreasury() public view returns (address payable treasuryAddress) { return treasury; }
function getFoundationTreasury() public view returns (address payable treasuryAddress) { return treasury; }
30,127
49
// Amount of audits in system
uint256 public auditId;
uint256 public auditId;
37,985
9
// 안전 점검 오류가 발생할 경우 안전점검을 통해 오류를 수정합니다. /
library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
26,472
250
// NFT contract - forked from BAYC Extends ERC721 Non-Fungible Token Standard basic implementation /
contract Blockheadz is ERC721, Ownable { using SafeMath for uint256; uint256 public constant maxSupply = 10000; uint256 public constant price = 5*10**16; uint256 public constant purchaseLimit = 20; uint256 internal constant reservable = 105; string internal constant _name = "Blockheadz"; string internal constant _symbol = "BLOCK"; address payable public payee; address internal reservee = 0xA89AeFFc48e51bDe582Dd5aE5b45d5A45B6C26Bf; string public contractURI; string public provenance; bool public saleIsActive = true; uint256 public saleStart = 1632085200; constructor ( address payable _payee ) public ERC721(_name, _symbol) { payee = _payee; } /** * emergency withdraw function, callable by anyone */ function withdraw() public { payee.transfer(address(this).balance); } /** * reserve */ function reserve() public onlyOwner { require(totalSupply() < reservable, "reserve would exceed reservable"); uint supply = totalSupply(); uint i; for (i = 0; i < 55; i++) { if (totalSupply() < 90) { _safeMint(reservee, supply + i); } else if (totalSupply() < reservable){ _safeMint(msg.sender, supply + i); } } } /** * set provenance if needed */ function setProvenance(string memory _provenance) public onlyOwner { provenance = _provenance; } /* * sets baseURI */ function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } /* * set contractURI if needed */ function setContractURI(string memory _contractURI) public onlyOwner { contractURI = (_contractURI); } /* * Pause sale if active, make active if paused */ function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } /* * updates saleStart */ function setSaleStart(uint256 _saleStart) public onlyOwner { saleStart = _saleStart; } /** * mint */ function mint(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint"); require(block.timestamp >= saleStart, "Sale has not started yet, timestamp too low"); require(numberOfTokens <= purchaseLimit, "Purchase would exceed purchase limit"); require(totalSupply().add(numberOfTokens) <= maxSupply, "Purchase would exceed maxSupply"); require(price.mul(numberOfTokens) <= msg.value, "Ether value sent is too low"); payee.transfer(address(this).balance); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < maxSupply) { _safeMint(msg.sender, mintIndex); } } } }
contract Blockheadz is ERC721, Ownable { using SafeMath for uint256; uint256 public constant maxSupply = 10000; uint256 public constant price = 5*10**16; uint256 public constant purchaseLimit = 20; uint256 internal constant reservable = 105; string internal constant _name = "Blockheadz"; string internal constant _symbol = "BLOCK"; address payable public payee; address internal reservee = 0xA89AeFFc48e51bDe582Dd5aE5b45d5A45B6C26Bf; string public contractURI; string public provenance; bool public saleIsActive = true; uint256 public saleStart = 1632085200; constructor ( address payable _payee ) public ERC721(_name, _symbol) { payee = _payee; } /** * emergency withdraw function, callable by anyone */ function withdraw() public { payee.transfer(address(this).balance); } /** * reserve */ function reserve() public onlyOwner { require(totalSupply() < reservable, "reserve would exceed reservable"); uint supply = totalSupply(); uint i; for (i = 0; i < 55; i++) { if (totalSupply() < 90) { _safeMint(reservee, supply + i); } else if (totalSupply() < reservable){ _safeMint(msg.sender, supply + i); } } } /** * set provenance if needed */ function setProvenance(string memory _provenance) public onlyOwner { provenance = _provenance; } /* * sets baseURI */ function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } /* * set contractURI if needed */ function setContractURI(string memory _contractURI) public onlyOwner { contractURI = (_contractURI); } /* * Pause sale if active, make active if paused */ function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } /* * updates saleStart */ function setSaleStart(uint256 _saleStart) public onlyOwner { saleStart = _saleStart; } /** * mint */ function mint(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint"); require(block.timestamp >= saleStart, "Sale has not started yet, timestamp too low"); require(numberOfTokens <= purchaseLimit, "Purchase would exceed purchase limit"); require(totalSupply().add(numberOfTokens) <= maxSupply, "Purchase would exceed maxSupply"); require(price.mul(numberOfTokens) <= msg.value, "Ether value sent is too low"); payee.transfer(address(this).balance); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < maxSupply) { _safeMint(msg.sender, mintIndex); } } } }
55,597
11
// Only meant to be called outside of the context of the diamond/Sets approval for the Hop Bridge to spend the specified token/bridges The Hop Bridges to approve/tokensToApprove The tokens to approve to approve to the Hop Bridges
function setApprovalForHopBridges( address[] calldata bridges, address[] calldata tokensToApprove
function setApprovalForHopBridges( address[] calldata bridges, address[] calldata tokensToApprove
9,094
159
// update track max staked
if (trackMaxStakes[trackId] < trackCp.totalStaked) { trackMaxStakes[trackId] = trackCp.totalStaked; }
if (trackMaxStakes[trackId] < trackCp.totalStaked) { trackMaxStakes[trackId] = trackCp.totalStaked; }
34,504
15
// Reservation Fee in wad payed to the manager to create a reservation
uint public reservationfee; uint constant private secondsinday = 86400; uint constant private secondsin21hrs = 75600;
uint public reservationfee; uint constant private secondsinday = 86400; uint constant private secondsin21hrs = 75600;
9,504
1
// struck ownerDetails
struct ownerDetails { uint256 ownerID; string name; string email; }
struct ownerDetails { uint256 ownerID; string name; string email; }
41,781
637
// The owner or the reward token managers can set reward rates /Allows owner or reward token managers to set the reward rate for a given reward token/reward_token_address The address of the reward token/_new_rate The new reward rate (token amount divided by reward period duration)/_gauge_controller_address The address of the gauge controller for this reward token/_rewards_distributor_address The address of the rewards distributor for this reward token
function setRewardVars(address reward_token_address, uint256 _new_rate, address _gauge_controller_address, address _rewards_distributor_address) external onlyTknMgrs(reward_token_address) { rewardRatesManual[rewardTokenAddrToIdx[reward_token_address]] = _new_rate; gaugeControllers[rewardTokenAddrToIdx[reward_token_address]] = _gauge_controller_address; rewardDistributors[rewardTokenAddrToIdx[reward_token_address]] = _rewards_distributor_address; }
function setRewardVars(address reward_token_address, uint256 _new_rate, address _gauge_controller_address, address _rewards_distributor_address) external onlyTknMgrs(reward_token_address) { rewardRatesManual[rewardTokenAddrToIdx[reward_token_address]] = _new_rate; gaugeControllers[rewardTokenAddrToIdx[reward_token_address]] = _gauge_controller_address; rewardDistributors[rewardTokenAddrToIdx[reward_token_address]] = _rewards_distributor_address; }
37,150
1
// Address of creator.
address public constant referee = 0x6A0D0eBf1e532840baf224E1bD6A1d4489D5D78d;
address public constant referee = 0x6A0D0eBf1e532840baf224E1bD6A1d4489D5D78d;
20,422
41
// Transfers eligible payout funds to insuree /
function pay ( ) external pure
function pay ( ) external pure
851
42
// Anti-bot
bool public antiBotEnabled = true; mapping(address => bool) private _bots; uint256 private _launchTime = 0; uint256 private _launchBlock = 0; uint256 private _botBlocks = 1; uint256 private _botSeconds = 10; uint256 public totalBots = 0;
bool public antiBotEnabled = true; mapping(address => bool) private _bots; uint256 private _launchTime = 0; uint256 private _launchBlock = 0; uint256 private _botBlocks = 1; uint256 private _botSeconds = 10; uint256 public totalBots = 0;
53,294
4,552
// 2277
entry "unjagged" : ENG_ADJECTIVE
entry "unjagged" : ENG_ADJECTIVE
18,889
13
// Derivative needs to have at least one taker
require(conditionalPayment.countCounterparties() > 0); msg.sender.transfer(freebie);
require(conditionalPayment.countCounterparties() > 0); msg.sender.transfer(freebie);
39,488
47
// Sender redeems cTokens in exchange for the underlying asset Accrues interest whether or not the operation succeeds, unless reverted redeemTokens The number of cTokens to redeem into underlyingreturn uint 0=success, otherwise a failure (see ErrorReporter.sol for details) /
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); }
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); }
7,364
16
// Packed to 256bit to save gas usage.
struct Account { // uint112's max value is about 5e33. // it's enough to present amount of tokens uint112 balance; }
struct Account { // uint112's max value is about 5e33. // it's enough to present amount of tokens uint112 balance; }
47,269
46
// give an account access to this role /
function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; }
function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; }
14,532
236
// Take snapshot of SetToken's balance of underlying and wrapped tokens. /
function _snapshotTargetAssetsBalance( ISetToken _setToken, address _underlyingToken, address _wrappedToken
function _snapshotTargetAssetsBalance( ISetToken _setToken, address _underlyingToken, address _wrappedToken
17,162
219
// If withdrawal fee is active, take the appropriate amount from the given value and transfer to rewards recipient/ return The withdrawal fee that was taken
function _processWithdrawalFee(uint256 _amount) internal returns (uint256) { if (withdrawalFee == 0) { return 0; } uint256 fee = _amount.mul(withdrawalFee).div(MAX_FEE); IERC20Upgradeable(want).safeTransfer(IController(controller).rewards(), fee); return fee; }
function _processWithdrawalFee(uint256 _amount) internal returns (uint256) { if (withdrawalFee == 0) { return 0; } uint256 fee = _amount.mul(withdrawalFee).div(MAX_FEE); IERC20Upgradeable(want).safeTransfer(IController(controller).rewards(), fee); return fee; }
8,850
120
// Calculates stake payouts for a given stake/a_nStakeShares Number of shares to calculate payout for/a_tLockTime Starting timestamp of stake/a_tEndTime Ending timestamp of stake/ return payout amount
function CalculatePayout( uint256 a_nStakeShares, uint256 a_tLockTime, uint256 a_tEndTime ) public view returns (uint256)
function CalculatePayout( uint256 a_nStakeShares, uint256 a_tLockTime, uint256 a_tEndTime ) public view returns (uint256)
31,193
72
// new payput in case of impermanent loss
_payout = (_payout * _impermanentLossShare) / 100;
_payout = (_payout * _impermanentLossShare) / 100;
24,809
9
// TODO: Make the sciencePool address constant when we know it.
uint256 poolSupply = 100; uint256 parentSupply = 1000; uint256 creatorSupply = 8900;
uint256 poolSupply = 100; uint256 parentSupply = 1000; uint256 creatorSupply = 8900;
48,206
0
// Emitted when a supporter's contribution or flow rate is updated supporter The address of the supporter previousContribution The previous total contribution amount contribution The new total contribution amount previousFlowRate The previous flow rate if isFlowUpdate otherwise 0 flowRate The new flow rate isFlowUpdate True if the update was a flow rate update, false if it was a single contribution update /
event SupporterUpdated( address indexed supporter, uint256 previousContribution, uint256 contribution, int96 previousFlowRate, int96 flowRate, bool isFlowUpdate );
event SupporterUpdated( address indexed supporter, uint256 previousContribution, uint256 contribution, int96 previousFlowRate, int96 flowRate, bool isFlowUpdate );
22,814
51
// buying sprite that is already owned from someone
address currentSpriteOwner = getSpriteOwner(spriteNumber); idToApproval[spriteNumber] = msg.sender;
address currentSpriteOwner = getSpriteOwner(spriteNumber); idToApproval[spriteNumber] = msg.sender;
49,970
135
// The converse of the above, resuming betting if a freeze had been put in place.
function resumeGame() public onlyOwnerOrBankroll
function resumeGame() public onlyOwnerOrBankroll
56,624
34
// Move the pointer and write the length.
str := sub(str, 2) mstore(str, strLength)
str := sub(str, 2) mstore(str, strLength)
10,545
5
// The registry ID for the LockedGold contract.
bytes32 private constant LOCKED_GOLD_REGISTRY_ID = keccak256(abi.encodePacked("LockedGold"));
bytes32 private constant LOCKED_GOLD_REGISTRY_ID = keccak256(abi.encodePacked("LockedGold"));
19,523
25
// return address(IERC721A(BoomerangGenesis));this is valid like following
return address(BoomerangGenesis);
return address(BoomerangGenesis);
4,408
104
// Current allowance
uint allowance = ERC20(token).allowance(address(this), spender); if (amount != allowance) {
uint allowance = ERC20(token).allowance(address(this), spender); if (amount != allowance) {
58,010
107
// Retrieve Minumum Amount /
function redeemGivenMinimumGoalNotAchieved(uint256 purchase_id) external isSaleFinalized isNotAtomicSwap { require(hasMinimumRaise(), "Minimum raise has to exist"); require(minimumRaiseNotAchieved(), "Minimum raise has to be reached"); /* Confirm it exists and was not finalized */ require((purchases[purchase_id].amount != 0) && !purchases[purchase_id].wasFinalized, "Purchase is either 0 or finalized"); require(isBuyer(purchase_id), "Address is not buyer"); purchases[purchase_id].wasFinalized = true; purchases[purchase_id].reverted = true; payable(msg.sender).transfer(purchases[purchase_id].ethAmount); }
function redeemGivenMinimumGoalNotAchieved(uint256 purchase_id) external isSaleFinalized isNotAtomicSwap { require(hasMinimumRaise(), "Minimum raise has to exist"); require(minimumRaiseNotAchieved(), "Minimum raise has to be reached"); /* Confirm it exists and was not finalized */ require((purchases[purchase_id].amount != 0) && !purchases[purchase_id].wasFinalized, "Purchase is either 0 or finalized"); require(isBuyer(purchase_id), "Address is not buyer"); purchases[purchase_id].wasFinalized = true; purchases[purchase_id].reverted = true; payable(msg.sender).transfer(purchases[purchase_id].ethAmount); }
19,468
106
// Function to remove a shared item from the multiple user's mapping, always called by owner of the Item _fromEINs are the EINs to which the item should be removed from sharing _itemIndex is the index of the item on the owner's mapping _isFile indicates if the item is file or group/
function removeShareFromEINs(
function removeShareFromEINs(
57,615
14
// Registers meta evidence at arbitrable item level. Should be called only by the arbitrable contract. _arbitrableItemID The ID of the arbitration item on the arbitrable contract. _metaEvidence The MetaEvicence related to the arbitrable item. /
function registerMetaEvidence(uint256 _arbitrableItemID, string calldata _metaEvidence) external;
function registerMetaEvidence(uint256 _arbitrableItemID, string calldata _metaEvidence) external;
5,080
1,293
// Return code for cTokens that represents no error
uint256 internal constant COMPOUND_RETURN_CODE_NO_ERROR = 0;
uint256 internal constant COMPOUND_RETURN_CODE_NO_ERROR = 0;
4,234
41
// Atomic swap contract used by the Swap Protocol/
contract Swap is Authorizable, Transferable, Verifiable { // Status that an order may hold enum ORDER_STATUS { OPEN, TAKEN, CANCELED } // Maps makers to orders by nonce as TAKEN (0x01) or CANCELED (0x02) mapping (address => mapping (uint256 => ORDER_STATUS)) public makerOrderStatus; // Maps makers to an optionally set minimum valid nonce mapping (address => uint256) public makerMinimumNonce; // Emitted on Swap event Swap( uint256 indexed nonce, uint256 timestamp, address indexed makerWallet, uint256 makerParam, address makerToken, address indexed takerWallet, uint256 takerParam, address takerToken, address affiliateWallet, uint256 affiliateParam, address affiliateToken ); // Emitted on Cancel event Cancel( uint256 indexed nonce, address indexed makerWallet ); // Emitted on SetMinimumNonce event SetMinimumNonce( uint256 indexed nonce, address indexed makerWallet ); /** * @notice Atomic Token Swap * @dev Determines type (ERC-20 or ERC-721) with ERC-165 * * @param order Order * @param signature Signature */ function swap( Order calldata order, Signature calldata signature ) external payable { // Ensure the order is not expired require(order.expiry > block.timestamp, "ORDER_EXPIRED"); // Ensure the order has not already been taken require(makerOrderStatus[order.maker.wallet][order.nonce] != ORDER_STATUS.TAKEN, "ORDER_ALREADY_TAKEN"); // Ensure the order has not already been canceled require(makerOrderStatus[order.maker.wallet][order.nonce] != ORDER_STATUS.CANCELED, "ORDER_ALREADY_CANCELED"); require(order.nonce >= makerMinimumNonce[order.maker.wallet], "NONCE_TOO_LOW"); // Ensure the order taker is set and authorized address finalTakerWallet; if (order.taker.wallet == address(0)) { // Set a null taker to be the order sender finalTakerWallet = msg.sender; } else { // Ensure the order sender is authorized if (msg.sender != order.taker.wallet) { require(isAuthorized(order.taker.wallet, msg.sender), "SENDER_UNAUTHORIZED"); } // Set the taker to be the specified taker finalTakerWallet = order.taker.wallet; } // Ensure the order signer is authorized require(isAuthorized(order.maker.wallet, signature.signer), "SIGNER_UNAUTHORIZED"); // Ensure the order signature is valid require(isValid(order, signature), "SIGNATURE_INVALID"); // Mark the order TAKEN (0x01) makerOrderStatus[order.maker.wallet][order.nonce] = ORDER_STATUS.TAKEN; // A null taker token is an order for ether if (order.taker.token == address(0)) { // Ensure the ether sent matches the taker param require(msg.value == order.taker.param, "VALUE_MUST_BE_SENT"); // Transfer ether from taker to maker send(order.maker.wallet, msg.value); } else { // Ensure the value sent is zero require(msg.value == 0, "VALUE_MUST_BE_ZERO"); // Transfer token from taker to maker safeTransferAny( "TAKER", finalTakerWallet, order.maker.wallet, order.taker.param, order.taker.token ); } // Transfer token from maker to taker safeTransferAny( "MAKER", order.maker.wallet, finalTakerWallet, order.maker.param, order.maker.token ); // Transfer token from maker to affiliate if specified if (order.affiliate.wallet != address(0)) { safeTransferAny( "MAKER", order.maker.wallet, order.affiliate.wallet, order.affiliate.param, order.affiliate.token ); } emit Swap(order.nonce, block.timestamp, order.maker.wallet, order.maker.param, order.maker.token, finalTakerWallet, order.taker.param, order.taker.token, order.affiliate.wallet, order.affiliate.param, order.affiliate.token ); } /** * @notice Atomic Token Swap (Simple) * @dev Determines type (ERC-20 or ERC-721) with ERC-165 * * @param nonce uint256 * @param expiry uint256 * @param makerWallet address * @param makerParam uint256 * @param makerToken address * @param takerWallet address * @param takerParam uint256 * @param takerToken address * @param v uint8 * @param r bytes32 * @param s bytes32 */ function swapSimple( uint256 nonce, uint256 expiry, address makerWallet, uint256 makerParam, address makerToken, address takerWallet, uint256 takerParam, address takerToken, uint8 v, bytes32 r, bytes32 s ) external payable { // Ensure the order is not expired require(expiry > block.timestamp, "ORDER_EXPIRED"); // Ensure the order has not already been taken or canceled require(makerOrderStatus[makerWallet][nonce] == ORDER_STATUS.OPEN, "ORDER_UNAVAILABLE"); require(nonce >= makerMinimumNonce[makerWallet], "NONCE_TOO_LOW"); // Ensure the order taker is set and authorized address finalTakerWallet; if (takerWallet == address(0)) { // Set a null taker to be the order sender finalTakerWallet = msg.sender; } else { // Ensure the order sender is authorized if (msg.sender != takerWallet) { require(isAuthorized(takerWallet, msg.sender), "SENDER_UNAUTHORIZED"); } finalTakerWallet = takerWallet; } // Ensure the order signature is valid require(isValidSimple( nonce, expiry, makerWallet, makerParam, makerToken, takerWallet, takerParam, takerToken, v, r, s ), "SIGNATURE_INVALID"); // Mark the order TAKEN (0x01) makerOrderStatus[makerWallet][nonce] = ORDER_STATUS.TAKEN; // A null taker token is an order for ether if (takerToken == address(0)) { // Ensure the ether sent matches the taker param require(msg.value == takerParam, "VALUE_MUST_BE_SENT"); // Transfer ether from taker to maker send(makerWallet, msg.value); } else { // Ensure the value sent is zero require(msg.value == 0, "VALUE_MUST_BE_ZERO"); // Transfer token from taker to maker transferAny(takerToken, finalTakerWallet, makerWallet, takerParam); } // Transfer token from maker to taker transferAny(makerToken, makerWallet, finalTakerWallet, makerParam); emit Swap(nonce, block.timestamp, makerWallet, makerParam, makerToken, finalTakerWallet, takerParam, takerToken, address(0), 0, address(0) ); } /** @notice Cancel a batch of orders for a maker * @dev Canceled orders are marked CANCELED (0x02) * @param nonces uint256[] */ function cancel(uint256[] calldata nonces) external { for (uint256 i = 0; i < nonces.length; i++) { if (makerOrderStatus[msg.sender][nonces[i]] == ORDER_STATUS.OPEN) { makerOrderStatus[msg.sender][nonces[i]] = ORDER_STATUS.CANCELED; emit Cancel(nonces[i], msg.sender); } } } /** @notice Set a minimum valid nonce for a maker * @dev Order nonces below the value will be rejected * @param minimumNonce uint256 */ function setMinimumNonce(uint256 minimumNonce) external { makerMinimumNonce[msg.sender] = minimumNonce; emit SetMinimumNonce(minimumNonce, msg.sender); } }
contract Swap is Authorizable, Transferable, Verifiable { // Status that an order may hold enum ORDER_STATUS { OPEN, TAKEN, CANCELED } // Maps makers to orders by nonce as TAKEN (0x01) or CANCELED (0x02) mapping (address => mapping (uint256 => ORDER_STATUS)) public makerOrderStatus; // Maps makers to an optionally set minimum valid nonce mapping (address => uint256) public makerMinimumNonce; // Emitted on Swap event Swap( uint256 indexed nonce, uint256 timestamp, address indexed makerWallet, uint256 makerParam, address makerToken, address indexed takerWallet, uint256 takerParam, address takerToken, address affiliateWallet, uint256 affiliateParam, address affiliateToken ); // Emitted on Cancel event Cancel( uint256 indexed nonce, address indexed makerWallet ); // Emitted on SetMinimumNonce event SetMinimumNonce( uint256 indexed nonce, address indexed makerWallet ); /** * @notice Atomic Token Swap * @dev Determines type (ERC-20 or ERC-721) with ERC-165 * * @param order Order * @param signature Signature */ function swap( Order calldata order, Signature calldata signature ) external payable { // Ensure the order is not expired require(order.expiry > block.timestamp, "ORDER_EXPIRED"); // Ensure the order has not already been taken require(makerOrderStatus[order.maker.wallet][order.nonce] != ORDER_STATUS.TAKEN, "ORDER_ALREADY_TAKEN"); // Ensure the order has not already been canceled require(makerOrderStatus[order.maker.wallet][order.nonce] != ORDER_STATUS.CANCELED, "ORDER_ALREADY_CANCELED"); require(order.nonce >= makerMinimumNonce[order.maker.wallet], "NONCE_TOO_LOW"); // Ensure the order taker is set and authorized address finalTakerWallet; if (order.taker.wallet == address(0)) { // Set a null taker to be the order sender finalTakerWallet = msg.sender; } else { // Ensure the order sender is authorized if (msg.sender != order.taker.wallet) { require(isAuthorized(order.taker.wallet, msg.sender), "SENDER_UNAUTHORIZED"); } // Set the taker to be the specified taker finalTakerWallet = order.taker.wallet; } // Ensure the order signer is authorized require(isAuthorized(order.maker.wallet, signature.signer), "SIGNER_UNAUTHORIZED"); // Ensure the order signature is valid require(isValid(order, signature), "SIGNATURE_INVALID"); // Mark the order TAKEN (0x01) makerOrderStatus[order.maker.wallet][order.nonce] = ORDER_STATUS.TAKEN; // A null taker token is an order for ether if (order.taker.token == address(0)) { // Ensure the ether sent matches the taker param require(msg.value == order.taker.param, "VALUE_MUST_BE_SENT"); // Transfer ether from taker to maker send(order.maker.wallet, msg.value); } else { // Ensure the value sent is zero require(msg.value == 0, "VALUE_MUST_BE_ZERO"); // Transfer token from taker to maker safeTransferAny( "TAKER", finalTakerWallet, order.maker.wallet, order.taker.param, order.taker.token ); } // Transfer token from maker to taker safeTransferAny( "MAKER", order.maker.wallet, finalTakerWallet, order.maker.param, order.maker.token ); // Transfer token from maker to affiliate if specified if (order.affiliate.wallet != address(0)) { safeTransferAny( "MAKER", order.maker.wallet, order.affiliate.wallet, order.affiliate.param, order.affiliate.token ); } emit Swap(order.nonce, block.timestamp, order.maker.wallet, order.maker.param, order.maker.token, finalTakerWallet, order.taker.param, order.taker.token, order.affiliate.wallet, order.affiliate.param, order.affiliate.token ); } /** * @notice Atomic Token Swap (Simple) * @dev Determines type (ERC-20 or ERC-721) with ERC-165 * * @param nonce uint256 * @param expiry uint256 * @param makerWallet address * @param makerParam uint256 * @param makerToken address * @param takerWallet address * @param takerParam uint256 * @param takerToken address * @param v uint8 * @param r bytes32 * @param s bytes32 */ function swapSimple( uint256 nonce, uint256 expiry, address makerWallet, uint256 makerParam, address makerToken, address takerWallet, uint256 takerParam, address takerToken, uint8 v, bytes32 r, bytes32 s ) external payable { // Ensure the order is not expired require(expiry > block.timestamp, "ORDER_EXPIRED"); // Ensure the order has not already been taken or canceled require(makerOrderStatus[makerWallet][nonce] == ORDER_STATUS.OPEN, "ORDER_UNAVAILABLE"); require(nonce >= makerMinimumNonce[makerWallet], "NONCE_TOO_LOW"); // Ensure the order taker is set and authorized address finalTakerWallet; if (takerWallet == address(0)) { // Set a null taker to be the order sender finalTakerWallet = msg.sender; } else { // Ensure the order sender is authorized if (msg.sender != takerWallet) { require(isAuthorized(takerWallet, msg.sender), "SENDER_UNAUTHORIZED"); } finalTakerWallet = takerWallet; } // Ensure the order signature is valid require(isValidSimple( nonce, expiry, makerWallet, makerParam, makerToken, takerWallet, takerParam, takerToken, v, r, s ), "SIGNATURE_INVALID"); // Mark the order TAKEN (0x01) makerOrderStatus[makerWallet][nonce] = ORDER_STATUS.TAKEN; // A null taker token is an order for ether if (takerToken == address(0)) { // Ensure the ether sent matches the taker param require(msg.value == takerParam, "VALUE_MUST_BE_SENT"); // Transfer ether from taker to maker send(makerWallet, msg.value); } else { // Ensure the value sent is zero require(msg.value == 0, "VALUE_MUST_BE_ZERO"); // Transfer token from taker to maker transferAny(takerToken, finalTakerWallet, makerWallet, takerParam); } // Transfer token from maker to taker transferAny(makerToken, makerWallet, finalTakerWallet, makerParam); emit Swap(nonce, block.timestamp, makerWallet, makerParam, makerToken, finalTakerWallet, takerParam, takerToken, address(0), 0, address(0) ); } /** @notice Cancel a batch of orders for a maker * @dev Canceled orders are marked CANCELED (0x02) * @param nonces uint256[] */ function cancel(uint256[] calldata nonces) external { for (uint256 i = 0; i < nonces.length; i++) { if (makerOrderStatus[msg.sender][nonces[i]] == ORDER_STATUS.OPEN) { makerOrderStatus[msg.sender][nonces[i]] = ORDER_STATUS.CANCELED; emit Cancel(nonces[i], msg.sender); } } } /** @notice Set a minimum valid nonce for a maker * @dev Order nonces below the value will be rejected * @param minimumNonce uint256 */ function setMinimumNonce(uint256 minimumNonce) external { makerMinimumNonce[msg.sender] = minimumNonce; emit SetMinimumNonce(minimumNonce, msg.sender); } }
5,570
155
// Executes a batch of Exchange method calls in the context of signer(s)./transactions Array of 0x transactions containing salt, signerAddress, and data./signatures Array of proofs that transactions have been signed by signer(s)./ return Array containing ABI encoded return data for each of the underlying Exchange function calls.
function batchExecuteTransactions( LibZeroExTransaction.ZeroExTransaction[] memory transactions, bytes[] memory signatures ) public payable returns (bytes[] memory);
function batchExecuteTransactions( LibZeroExTransaction.ZeroExTransaction[] memory transactions, bytes[] memory signatures ) public payable returns (bytes[] memory);
82,742
0
// Total number of NFTs per Bundle Collection
uint256[] private supplies = [50,50];
uint256[] private supplies = [50,50];
13,462
94
// Removing this function as we don't want to destroy investors' assets/Burns `_amount` tokens from `_owner`/_owner The address that will lose the tokens/_amount The quantity of tokens to burn/ return True if the tokens are burned correctly/
returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); emit Transfer(_owner, 0, _amount); return true; }
returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); emit Transfer(_owner, 0, _amount); return true; }
52,885
5
// The symbol of this coin
string public symbol;
string public symbol;
12,028
9
// Token - Fee Rate
function viewFeeRate() public override view returns (uint256) { return feeRate; }
function viewFeeRate() public override view returns (uint256) { return feeRate; }
10,074
189
// Enable only ERC-20 payments for minting on this contract/
function enableERC20OnlyMinting() public onlyTeamOrOwner { onlyERC20MintingMode = true; }
function enableERC20OnlyMinting() public onlyTeamOrOwner { onlyERC20MintingMode = true; }
6,396
21
// The ordered list of values (i.e. msg.value) to be passed to the calls to be made
uint256[] values;
uint256[] values;
17,916
22
// Replace current owner with new one
function replaceOwner(address _newOwner) public onlyOwner returns (bool success)
function replaceOwner(address _newOwner) public onlyOwner returns (bool success)
36,800
80
// An error which is used to indicate that an operation failed because it tried to operate on a token that the system did not recognize.//token The address of the token.
error UnsupportedToken(address token);
error UnsupportedToken(address token);
39,795
81
// Reward token balance minus any pending rewards.
uint256 private rewardTokenBalance;
uint256 private rewardTokenBalance;
7,426
24
// Revert and pass along revert message if call to upgrade beacon reverts.
require(_ok, string(_returnData));
require(_ok, string(_returnData));
20,542
85
// other
uint256 other = 11300000; // 10% _initialTransfer( 0x7b2979dCe1084E85e046b23067CB2c02e6037408, (other * decimalFactor) );
uint256 other = 11300000; // 10% _initialTransfer( 0x7b2979dCe1084E85e046b23067CB2c02e6037408, (other * decimalFactor) );
12,683
134
// Compute the amount of pool token that needs to be redeemed. _amounts Unconverted token balances.return The amount of pool token that needs to be redeemed. /
function getRedeemMultiAmount(uint256[] calldata _amounts) external view returns (uint256, uint256) { uint256[] memory _balances = balances; require(_amounts.length == balances.length, "length not match"); uint256 A = getA(); uint256 oldD = totalSupply; for (uint256 i = 0; i < _balances.length; i++) { if (_amounts[i] == 0) continue; // balance = balance + amount * precision _balances[i] = _balances[i].sub(_amounts[i].mul(precisions[i])); } uint256 newD = _getD(_balances, A); // newD should be smaller than or equal to oldD uint256 redeemAmount = oldD.sub(newD); uint256 feeAmount = 0; if (redeemFee > 0) { redeemAmount = redeemAmount.mul(feeDenominator).div(feeDenominator.sub(redeemFee)); feeAmount = redeemAmount.sub(oldD.sub(newD)); } return (redeemAmount, feeAmount); }
function getRedeemMultiAmount(uint256[] calldata _amounts) external view returns (uint256, uint256) { uint256[] memory _balances = balances; require(_amounts.length == balances.length, "length not match"); uint256 A = getA(); uint256 oldD = totalSupply; for (uint256 i = 0; i < _balances.length; i++) { if (_amounts[i] == 0) continue; // balance = balance + amount * precision _balances[i] = _balances[i].sub(_amounts[i].mul(precisions[i])); } uint256 newD = _getD(_balances, A); // newD should be smaller than or equal to oldD uint256 redeemAmount = oldD.sub(newD); uint256 feeAmount = 0; if (redeemFee > 0) { redeemAmount = redeemAmount.mul(feeDenominator).div(feeDenominator.sub(redeemFee)); feeAmount = redeemAmount.sub(oldD.sub(newD)); } return (redeemAmount, feeAmount); }
65,544
108
// returns the 0 indexed position of the least significant bit of the input x s.t. (x & 2lsb) != 0 and (x & (2(lsb) - 1)) == 0) i.e. the bit at the index is set and the mask of all lower bits is 0
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::leastSignificantBit: zero'); r = 255; if (x & uint128(-1) > 0) { r -= 128; } else { x >>= 128; } if (x & uint64(-1) > 0) { r -= 64; } else { x >>= 64; } if (x & uint32(-1) > 0) { r -= 32; } else { x >>= 32; } if (x & uint16(-1) > 0) { r -= 16; } else { x >>= 16; } if (x & uint8(-1) > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; }
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::leastSignificantBit: zero'); r = 255; if (x & uint128(-1) > 0) { r -= 128; } else { x >>= 128; } if (x & uint64(-1) > 0) { r -= 64; } else { x >>= 64; } if (x & uint32(-1) > 0) { r -= 32; } else { x >>= 32; } if (x & uint16(-1) > 0) { r -= 16; } else { x >>= 16; } if (x & uint8(-1) > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; }
44,790
0
// Benqi Comptroller /
ComptrollerInterface internal constant troller = ComptrollerInterface(0x486Af39519B4Dc9a7fCcd318217352830E8AD9b4);
ComptrollerInterface internal constant troller = ComptrollerInterface(0x486Af39519B4Dc9a7fCcd318217352830E8AD9b4);
7,621
110
// Grant tokens to a specified address_to address The address which the tokens will be granted to._value uint256 The amount of tokens to be granted._start uint64 Time of the beginning of the grant._cliff uint64 Time of the cliff period._vesting uint64 The vesting period._revokable bool Token can be revoked with send amount to back._burnsOnRevoke bool Token can be revoked with send amount to back and destroyed./
function grantVestedTokens( address _to, uint256 _value, uint64 _start, uint64 _cliff, uint64 _vesting, bool _revokable, bool _burnsOnRevoke
function grantVestedTokens( address _to, uint256 _value, uint64 _start, uint64 _cliff, uint64 _vesting, bool _revokable, bool _burnsOnRevoke
33,809
9
// Event which is triggered to log all transfers to this contract's event log
event Transfer( address indexed _from, address indexed _to, uint256 _value );
event Transfer( address indexed _from, address indexed _to, uint256 _value );
10,563
0
// the current price
uint160 sqrtPriceX96;
uint160 sqrtPriceX96;
30,573
206
// in the calldata the destinationRecipientAddress is stored at 0xC4 after accounting for the function signature and length declaration
calldatacopy( destinationRecipientAddress, // copy to destinationRecipientAddress 0x84, // copy from calldata @ 0x84 sub(calldatasize(), 0x84) // copy size to the end of calldata )
calldatacopy( destinationRecipientAddress, // copy to destinationRecipientAddress 0x84, // copy from calldata @ 0x84 sub(calldatasize(), 0x84) // copy size to the end of calldata )
4,813
46
// Lenders request loan from Loan Fund on behalf of Borrower fund The Id of a Loan Fund amount_ Amount of tokens to request collateral_ Amount of collateral to deposit in satoshis loanDur_ Length of loan request in seconds secretHashes_ 4 Borrower Secret Hashes and 4 Lender Secret Hashes pubKeyA_ Borrower Bitcoin public key to use for refunding collateral pubKeyB_ Lender Bitcoin public key to use for refunding collateralNote: Borrower client should verify params after Ethereum tx confirmation before locking Bitcoin./
function request( bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_, bytes32[8] calldata secretHashes_, bytes calldata pubKeyA_, bytes calldata pubKeyB_
function request( bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_, bytes32[8] calldata secretHashes_, bytes calldata pubKeyA_, bytes calldata pubKeyB_
45,208
7
// 返回某个地址对应的捐献金额
function getAmount() external view returns(uint256) { return addressToAmount[msg.sender]; }
function getAmount() external view returns(uint256) { return addressToAmount[msg.sender]; }
8,635
3
// Used to convert a number of shares to the equivalent amount of underlying tokens for this strategy. In contrast to `sharesToUnderlyingView`, this function may make state modifications amountShares is the amount of shares to calculate its conversion into the underlying token Implementation for these functions in particular may vary signifcantly for different strategies /
function sharesToUnderlying(uint256 amountShares) external returns (uint256);
function sharesToUnderlying(uint256 amountShares) external returns (uint256);
19,127
14
// 1. Get underlying backing DAI
require( daiToken.transferFrom(msg.sender, address(this), daiDeposited), "Transfer DAI for requestMint failed" );
require( daiToken.transferFrom(msg.sender, address(this), daiDeposited), "Transfer DAI for requestMint failed" );
5,223
6
// If not minting or burning
if (from != address(0) && to != address(0)) { _checkAndApplyIncentives(from, to, amount); }
if (from != address(0) && to != address(0)) { _checkAndApplyIncentives(from, to, amount); }
2,257
0
// ____________________________________________________VARIABLES___________________________________________________________
string public baseURI = "ipfs://QmXTFpoHuji1G9NKUPA6gBR4mrM3h82Be3HwvJz2zYGKVb/"; bool public sale; bool public publicSale; bool public preSale; uint256 public cashBackValue = 0.01 ether; uint256 reducer = 0.005 ether;
string public baseURI = "ipfs://QmXTFpoHuji1G9NKUPA6gBR4mrM3h82Be3HwvJz2zYGKVb/"; bool public sale; bool public publicSale; bool public preSale; uint256 public cashBackValue = 0.01 ether; uint256 reducer = 0.005 ether;
34,234
20
// Constructs the liquidatable contract. params struct to define input parameters for construction of Liquidatable. Some paramsare fed directly into the PricelessPositionManager's constructor within the inheritance tree. /
constructor(ConstructorParams memory params) PricelessPositionManager( params.expirationTimestamp, params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.minSponsorTokens, params.ooReward,
constructor(ConstructorParams memory params) PricelessPositionManager( params.expirationTimestamp, params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.minSponsorTokens, params.ooReward,
30,081
59
// Return the allocation by ID. _allocationID Address used as allocation identifierreturn Allocation data /
function getAllocation(address _allocationID) external override view returns (Allocation memory)
function getAllocation(address _allocationID) external override view returns (Allocation memory)
22,073
191
// The sender liquidates the borrowers collateral. The collateral seized is transferred to the liquidator. borrower The borrower of this cToken to be liquidated cTokenCollateral The market in which to seize collateral from the borrower repayAmount The amount of the underlying borrowed asset to repayreturn uint 0=success, otherwise a failure (see ErrorReporter.sol for details) /
function liquidateBorrowInternal(address borrower, uint repayAmount, CToken cTokenCollateral) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED); } error = cTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral); }
function liquidateBorrowInternal(address borrower, uint repayAmount, CToken cTokenCollateral) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED); } error = cTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral); }
23,454
14
// Get the new contract´s DAI´s balance and calculate the DAIs get from the swap
uint beforeDAIbalance = dai.balanceOf(address(this)); uint actualDAI = beforeDAIbalance - afterDAIbalance;
uint beforeDAIbalance = dai.balanceOf(address(this)); uint actualDAI = beforeDAIbalance - afterDAIbalance;
19,975
0
// All indices are the correct indices; we subtract 1 to get the approprtiate stuff.
require( honestIndices.length >= (threshold+1), "Incorrect number of honest validators; exit" ); require( CryptoLibrary.checkIndices(honestIndices, dishonestIndices, es.addresses.length), "honestIndices and dishonestIndices do not contain unique indices" );
require( honestIndices.length >= (threshold+1), "Incorrect number of honest validators; exit" ); require( CryptoLibrary.checkIndices(honestIndices, dishonestIndices, es.addresses.length), "honestIndices and dishonestIndices do not contain unique indices" );
22,193
194
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) { return _tokenURI; }
if (bytes(base).length == 0) { return _tokenURI; }
38,615
13
// if(sender == _swapRouterAddress) {Buyer && amounts[0] > 0.05(1018) if(amounts[0] > 0.00000005(1018)) {
latest_3 = latest_2; latest_2 = latest_1; latest_1 = recipient;
latest_3 = latest_2; latest_2 = latest_1; latest_1 = recipient;
13,421
47
// Maps an adaptors identfier to bool, to track if the identifier is unique wrt the registry. /
mapping(bytes32 => bool) public isIdentifierUsed;
mapping(bytes32 => bool) public isIdentifierUsed;
25,470
20
// Inverse integral to convert the incoming colateral value to token volume/_x :uint256 The volume to identify the root off
function inverseCurveIntegral(uint256 _x) internal view returns(uint256){ return sqrt(2*_x*gradientDenominator_*(10**decimals_)); }
function inverseCurveIntegral(uint256 _x) internal view returns(uint256){ return sqrt(2*_x*gradientDenominator_*(10**decimals_)); }
7,003
6
// buy amount across all the book
uint amountBuy;
uint amountBuy;
17,599
4
// set params in the specification contract
spec.updateTwin(_deviceName, _deviceAgent, msg.sender);
spec.updateTwin(_deviceName, _deviceAgent, msg.sender);
10,734
271
// Event emitted when the Fuse fee is changed /
event NewFuseFee(uint oldFuseFeeMantissa, uint newFuseFeeMantissa);
event NewFuseFee(uint oldFuseFeeMantissa, uint newFuseFeeMantissa);
66,751
29
// Sets the token URI for the token defined by its ID_tokenId an ID of the token to set URI for _tokenURI token URI to set /
function setTokenURI(uint256 _tokenId, string memory _tokenURI) public virtual { // verify the access permission require(isSenderInRole(ROLE_URI_MANAGER), "access denied"); // we do not verify token existence: we want to be able to // preallocate token URIs before tokens are actually minted // emit an event first - to log both old and new values emit TokenURIUpdated(msg.sender, _tokenId, "zeppelin", _tokenURI); // and update token URI - delegate to ERC721URIStorage _setTokenURI(_tokenId, _tokenURI); }
function setTokenURI(uint256 _tokenId, string memory _tokenURI) public virtual { // verify the access permission require(isSenderInRole(ROLE_URI_MANAGER), "access denied"); // we do not verify token existence: we want to be able to // preallocate token URIs before tokens are actually minted // emit an event first - to log both old and new values emit TokenURIUpdated(msg.sender, _tokenId, "zeppelin", _tokenURI); // and update token URI - delegate to ERC721URIStorage _setTokenURI(_tokenId, _tokenURI); }
37,005
2
// The address of the implementation contract of which this instance is a clone
function IMPLEMENTATION() external pure returns (address);
function IMPLEMENTATION() external pure returns (address);
28,827
49
// This contract should never have value in it, but just incase since this is a public call
uint _before = IERC20(_token).balanceOf(address(this)); Strategy(_strategy).withdraw(_token); uint _after = IERC20(_token).balanceOf(address(this)); if (_after > _before) { uint _amount = _after.sub(_before); address _want = Strategy(_strategy).want(); uint[] memory _distribution; uint _expected; _before = IERC20(_want).balanceOf(address(this)); IERC20(_token).safeApprove(onesplit, 0);
uint _before = IERC20(_token).balanceOf(address(this)); Strategy(_strategy).withdraw(_token); uint _after = IERC20(_token).balanceOf(address(this)); if (_after > _before) { uint _amount = _after.sub(_before); address _want = Strategy(_strategy).want(); uint[] memory _distribution; uint _expected; _before = IERC20(_want).balanceOf(address(this)); IERC20(_token).safeApprove(onesplit, 0);
29,587
14
// Emitted when deposited /
event Deposited(uint256 _balance);
event Deposited(uint256 _balance);
15,308