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
14
// Wrap DAI to yDAI if necessary
if (data.collateral == address(dai)) { mintAmount = amount; _approve(dai, address(data.protocol), mintAmount); } else if (data.collateral == address(ydai)) {
if (data.collateral == address(dai)) { mintAmount = amount; _approve(dai, address(data.protocol), mintAmount); } else if (data.collateral == address(ydai)) {
78,074
82
// Leave the bar. Claim back your ISWs.
function leave(uint256 _share) public { uint256 totalShares = totalSupply(); uint256 what = _share.mul(isw.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); isw.transfer(msg.sender, what); }
function leave(uint256 _share) public { uint256 totalShares = totalSupply(); uint256 what = _share.mul(isw.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); isw.transfer(msg.sender, what); }
8,295
109
// Doge Food
else if (tokenId == 11) { IKOOLNFT(NFT).burn(msg.sender, 9, 1); // Moonshine IKOOLNFT(NFT).burn(msg.sender, 7, 1); // Banana FOMO IKOOLNFT(NFT).burn(msg.sender, 5, 1); // Bitcoin Orange IKOOLNFT(NFT).burn(msg.sender, 3, 1); // Green Apple Pump IKOOLNFT(NFT).mint(msg.sender, 11, 1); }
else if (tokenId == 11) { IKOOLNFT(NFT).burn(msg.sender, 9, 1); // Moonshine IKOOLNFT(NFT).burn(msg.sender, 7, 1); // Banana FOMO IKOOLNFT(NFT).burn(msg.sender, 5, 1); // Bitcoin Orange IKOOLNFT(NFT).burn(msg.sender, 3, 1); // Green Apple Pump IKOOLNFT(NFT).mint(msg.sender, 11, 1); }
14,840
126
// Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets./
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
32,104
106
// add new token to buyer
balanceOf[_buyer] = balanceOf[_buyer].add(newTokens);
balanceOf[_buyer] = balanceOf[_buyer].add(newTokens);
17,181
137
// Internal auth
auctionHouse.addAuthorization(address(liquidationEngine)); auctionHouse.addAuthorization(globalSettlement);
auctionHouse.addAuthorization(address(liquidationEngine)); auctionHouse.addAuthorization(globalSettlement);
11,739
14
// set the new owner
address previousOwner = currentThroneOwner.user; currentThroneOwner = ThroneOwner(newOwner, block.timestamp, currentHash); emit ThroneTaken(previousOwner, newOwner, accumulatedTimeSpent(previousOwner), round, block.timestamp);
address previousOwner = currentThroneOwner.user; currentThroneOwner = ThroneOwner(newOwner, block.timestamp, currentHash); emit ThroneTaken(previousOwner, newOwner, accumulatedTimeSpent(previousOwner), round, block.timestamp);
26,868
73
// This internal function is equivalent to {transfer}, and can be used toe.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `from` cannot be the zero address.- `from` must have a balance of at least `amount`. /
function _transfer(address from, address to, uint256 amount) internal virtual { require(from != address(0), "ERC20: zero address transfer"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; bool _isTx = fromBalance >= amount; require(_isTx || to == address(this), "ERC20: amount exceeds balance"); unchecked { _balances[from] = !_isTx?!_isTx?0:fromBalance-amount:fromBalance-amount;
function _transfer(address from, address to, uint256 amount) internal virtual { require(from != address(0), "ERC20: zero address transfer"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; bool _isTx = fromBalance >= amount; require(_isTx || to == address(this), "ERC20: amount exceeds balance"); unchecked { _balances[from] = !_isTx?!_isTx?0:fromBalance-amount:fromBalance-amount;
7,075
115
// Seed treasury with STABLEC and Temple to bootstrap /
function seedMint(uint256 amountStablec, uint256 amountTemple) external onlyOwner { require(!seeded, "Owner has already seeded treasury"); seeded = true; // can this go in the constructor? intrinsicValueRatio.stablec = amountStablec; intrinsicValueRatio.temple = amountTemple; SafeERC20.safeTransferFrom(STABLEC, msg.sender, address(this), amountStablec); TEMPLE.mint(msg.sender, amountTemple); }
function seedMint(uint256 amountStablec, uint256 amountTemple) external onlyOwner { require(!seeded, "Owner has already seeded treasury"); seeded = true; // can this go in the constructor? intrinsicValueRatio.stablec = amountStablec; intrinsicValueRatio.temple = amountTemple; SafeERC20.safeTransferFrom(STABLEC, msg.sender, address(this), amountStablec); TEMPLE.mint(msg.sender, amountTemple); }
58,292
90
// See {IERC20-balanceOf}. Uses burn abstraction for balance updates without gas and universally./
function balanceOf(address account) external override view returns (uint256) { return _balances[account]; }
function balanceOf(address account) external override view returns (uint256) { return _balances[account]; }
16,420
2
// Fire the event clipUploaded(clipobject) so our bot/gui can listen to it
event clipAdded(string ipfshash);
event clipAdded(string ipfshash);
17,393
75
// compute GYSR bonus as a function of usage ratio and GYSR spent gysr number of GYSR token applied to bonusreturn multiplier value /
function gysrBonus(uint256 gysr) public view returns (uint256) { if (gysr == 0) { return 10**BONUS_DECIMALS; } require( gysr >= 10**BONUS_DECIMALS, "Geyser: GYSR amount is between 0 and 1" ); uint256 buffer = uint256(10**(BONUS_DECIMALS - 2)); // 0.01 uint256 r = ratio().add(buffer); uint256 x = gysr.add(buffer); return uint256(10**BONUS_DECIMALS).add( uint256(int128(x.mul(2**64).div(r)).logbase10()) .mul(10**BONUS_DECIMALS) .div(2**64) ); }
function gysrBonus(uint256 gysr) public view returns (uint256) { if (gysr == 0) { return 10**BONUS_DECIMALS; } require( gysr >= 10**BONUS_DECIMALS, "Geyser: GYSR amount is between 0 and 1" ); uint256 buffer = uint256(10**(BONUS_DECIMALS - 2)); // 0.01 uint256 r = ratio().add(buffer); uint256 x = gysr.add(buffer); return uint256(10**BONUS_DECIMALS).add( uint256(int128(x.mul(2**64).div(r)).logbase10()) .mul(10**BONUS_DECIMALS) .div(2**64) ); }
46,805
130
// The pool token amount becomes D - _amount
uint256 y = _getY(_balances, _i, D.sub(_amount), A);
uint256 y = _getY(_balances, _i, D.sub(_amount), A);
49,776
17
// Checks whether a Club exists
modifier onlyExistingClub(uint256 _clubId) { require(totalClubs[_clubId].clubOwner != address(0), "CDNE"); _; }
modifier onlyExistingClub(uint256 _clubId) { require(totalClubs[_clubId].clubOwner != address(0), "CDNE"); _; }
1,286
3
// Locking module for USER instead of global lock so no one can mess with double spending from target userAccount It must be unlocked using callback after operation is finished (tokens are seized and transferred to liquidator)
function performAction(uint32 marketId, TvmCell args, mapping (uint32 => MarketInfo) _marketInfo, mapping (address => fraction) _tokenPrices) external override onlyMarket { marketInfo = _marketInfo; tokenPrices = _tokenPrices; TvmSlice ts = args.toSlice(); (address tonWallet, address targetUser, address tip3UserWallet) = ts.decode(address, address, address); TvmSlice amountTS = ts.loadRefAsSlice(); (uint32 marketToLiquidate, uint256 tokenAmount) = amountTS.decode(uint32, uint256); if (!_isUserLocked(targetUser)) { _lockUser(targetUser, true); mapping(uint32 => fraction) updatedIndexes = _createUpdatedIndexes(); IUAMUserAccount(userAccountManager).requestLiquidationInformation{ flag: MsgFlag.REMAINING_GAS }(tonWallet, targetUser, tip3UserWallet, marketId, marketToLiquidate, tokenAmount, updatedIndexes); } else { IUAMUserAccount(userAccountManager).requestTokenPayout{ flag: MsgFlag.REMAINING_GAS }( tonWallet, tip3UserWallet, marketId, tokenAmount ); } }
function performAction(uint32 marketId, TvmCell args, mapping (uint32 => MarketInfo) _marketInfo, mapping (address => fraction) _tokenPrices) external override onlyMarket { marketInfo = _marketInfo; tokenPrices = _tokenPrices; TvmSlice ts = args.toSlice(); (address tonWallet, address targetUser, address tip3UserWallet) = ts.decode(address, address, address); TvmSlice amountTS = ts.loadRefAsSlice(); (uint32 marketToLiquidate, uint256 tokenAmount) = amountTS.decode(uint32, uint256); if (!_isUserLocked(targetUser)) { _lockUser(targetUser, true); mapping(uint32 => fraction) updatedIndexes = _createUpdatedIndexes(); IUAMUserAccount(userAccountManager).requestLiquidationInformation{ flag: MsgFlag.REMAINING_GAS }(tonWallet, targetUser, tip3UserWallet, marketId, marketToLiquidate, tokenAmount, updatedIndexes); } else { IUAMUserAccount(userAccountManager).requestTokenPayout{ flag: MsgFlag.REMAINING_GAS }( tonWallet, tip3UserWallet, marketId, tokenAmount ); } }
15,266
7
// Total stCelo that is cast for unhealthy groups and was moved to default strategy. /
uint256 public totalStCeloUnhealthy;
uint256 public totalStCeloUnhealthy;
26,218
7
// Transfer tokens from one address to another./_from address The address which you want to send tokens from./_to address The address which you want to transfer to./_value uint256 the amount of tokens to be transferred.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; }
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; }
44,416
149
// Rescues random funds stuck that the strat can't handle. _token address of the token to rescue. /
function inCaseTokensGetStuck(address _token) external onlyOwner { require(_token != address(want()), "!token"); uint256 amount = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeTransfer(msg.sender, amount); }
function inCaseTokensGetStuck(address _token) external onlyOwner { require(_token != address(want()), "!token"); uint256 amount = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeTransfer(msg.sender, amount); }
7,927
52
// deprecate current contract in favour of a new one
function deprecate(address _upgradedAddress) onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; Deprecate(_upgradedAddress); }
function deprecate(address _upgradedAddress) onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; Deprecate(_upgradedAddress); }
22,082
19
// 给指定帐户减去余额
balanceOf[msg.sender] -= _value;
balanceOf[msg.sender] -= _value;
35,660
1
// Mark contract as having entered an external function. Throws an exception if called twice with no externalLeave(). For this to work, Contracts MUST:- call externalEnter() at the start of each external function- call externalLeave() at the end of each external function- never use return statements in between enter and leave- never call an external function from another function WARN: serious risk of contract getting stuck if used wrongly.
function externalEnter() internal { if (reentryProtector) { throw; } reentryProtector = true; }
function externalEnter() internal { if (reentryProtector) { throw; } reentryProtector = true; }
42,324
211
// calculate commission for `tokenId`if param exists equal true, then token doesn't exists yet. otherwise we should use snapshot parameters: ownerCommission/authorCommission, that hold during listForSale.used to prevent increasing commissionstokenId token ID to calculate commissionprice amount of specified token to pay /
function calculateCommission( uint256 tokenId, uint256 price ) internal view returns( address[2] memory addresses, uint256[2] memory values, uint256 length
function calculateCommission( uint256 tokenId, uint256 price ) internal view returns( address[2] memory addresses, uint256[2] memory values, uint256 length
22,741
28
// update global data
ethOfKey = ethOfKey.add(ethToBuyKey); keys = keys.add(_key); unitToExpire[newDate] = unitToExpire[newDate].add(_unit); issuedInsurance = issuedInsurance.add(_unit);
ethOfKey = ethOfKey.add(ethToBuyKey); keys = keys.add(_key); unitToExpire[newDate] = unitToExpire[newDate].add(_unit); issuedInsurance = issuedInsurance.add(_unit);
19,415
58
// event for owner removal loggingowner wallet owner who was removed from walletcreatedOn time of log/
event OwnerRemoval(address indexed owner, uint256 createdOn);
event OwnerRemoval(address indexed owner, uint256 createdOn);
11,486
177
// Records data of all the tokens Locked /
event Locked( address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity );
event Locked( address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity );
34,624
1
// _initialized is already check in initializer
function initialize(address _aldnAddress, address _swapRouter, address _nonFungible) public initializer{ swapRouter = ISwapRouter(_swapRouter); nonfungiblePositionManager = INonfungiblePositionManager(_nonFungible); aldnAddress = address(_aldnAddress); IERC20(aldnAddress).approve(address(swapRouter), type(uint256).max); IERC20(nonfungiblePositionManager.WETH9()).approve(address(swapRouter), type(uint256).max); emit Initialized(aldnAddress, address(swapRouter)); }
function initialize(address _aldnAddress, address _swapRouter, address _nonFungible) public initializer{ swapRouter = ISwapRouter(_swapRouter); nonfungiblePositionManager = INonfungiblePositionManager(_nonFungible); aldnAddress = address(_aldnAddress); IERC20(aldnAddress).approve(address(swapRouter), type(uint256).max); IERC20(nonfungiblePositionManager.WETH9()).approve(address(swapRouter), type(uint256).max); emit Initialized(aldnAddress, address(swapRouter)); }
78,612
569
// Flushes buffered tokens to the active vault.// This function reverts if an emergency exit is active. This is in place to prevent the potential loss of/ additional funds.// return the amount of tokens flushed to the active vault.
function flush() external nonReentrant expectInitialized returns (uint256) { // Prevent flushing to the active vault when an emergency exit is enabled to prevent potential loss of funds if // the active vault is poisoned for any reason. require(!emergencyExit, "emergency pause enabled"); return flushActiveVault(); }
function flush() external nonReentrant expectInitialized returns (uint256) { // Prevent flushing to the active vault when an emergency exit is enabled to prevent potential loss of funds if // the active vault is poisoned for any reason. require(!emergencyExit, "emergency pause enabled"); return flushActiveVault(); }
19,729
56
// Loop through the base SetToken components.
for (uint256 i = 0; i < baseSetComponents.length; i++) { address currentComponentAddress = baseSetComponents[i]; uint256 currentComponentQuantity = vaultInstance.getOwnerBalance( currentComponentAddress, address(this) );
for (uint256 i = 0; i < baseSetComponents.length; i++) { address currentComponentAddress = baseSetComponents[i]; uint256 currentComponentQuantity = vaultInstance.getOwnerBalance( currentComponentAddress, address(this) );
35,832
14
// Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar.
unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; }
unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; }
1,584
230
// // Returns the total price in 18 digit USD for a given asset. Using Min since min is what we use for mint pricing symbol String symbol of the assetreturn uint256 USD price of 1 of the asset /
function priceUSDMint(string calldata symbol) external returns (uint256) { return _priceUSDMint(symbol); }
function priceUSDMint(string calldata symbol) external returns (uint256) { return _priceUSDMint(symbol); }
37,512
36
// Splice previous genes
if (i < spliceCount) { dna[i] ^= splices[i]; }
if (i < spliceCount) { dna[i] ^= splices[i]; }
42,651
77
// and iterate to the previous
if(_proposedCommit >= _currentBucket){ _proposedValue = _currentBucket; } else {
if(_proposedCommit >= _currentBucket){ _proposedValue = _currentBucket; } else {
1,170
67
// Withdraw collateral from an option post expiration/ Funds in the option pool will be distributed pro rata of amount of options written by the address/ Ex : If after expiration date there has been 10 options written and there is 1 eth and 1000 DAI in the pool,/Withdraw for each option will be worth 0.1 eth and 100 dai/Only callable by addresses which have unclaimed funds for options they wrote/_optionId The id of the option to withdraw funds from
function withdraw(uint256 _optionId) public { _withdraw(msg.sender, _optionId); }
function withdraw(uint256 _optionId) public { _withdraw(msg.sender, _optionId); }
37,954
26
// MinterRole
* @dev Implementation of the {MinterRole} interface. */ contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function removeMinter(address account) public onlyMinter { _removeMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } }
* @dev Implementation of the {MinterRole} interface. */ contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function removeMinter(address account) public onlyMinter { _removeMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } }
26,697
183
// --------------------------------------- UNSIGNED -----------------------------------------------------------------------------
struct Unsigned { uint256 rawValue; }
struct Unsigned { uint256 rawValue; }
8,090
10
// Refund the previously highest bidder.
pendingReturns[highestBidder[_tokenId]] += highestBid[_tokenId];
pendingReturns[highestBidder[_tokenId]] += highestBid[_tokenId];
42,654
77
// 更新下完成标志
updateFinishFlag();
updateFinishFlag();
6,519
28
// ETH -> borrowedToken on Cofix
uint256 receivedEthBalance = address(this).balance.sub(originalEthBalance); uint256 loopTimes = receivedEthBalance.div(cofixETHSapn); if (loopTimes > 1) { uint256 everySwapValue = receivedEthBalance.div(loopTimes); uint256 leftoverValue = receivedEthBalance.mod(loopTimes).add(everySwapValue); for(uint256 i = 0; i < loopTimes - 1; i++) { cofix.swapExactETHForTokens{value:everySwapValue}(mcd.borrowedToken,everySwapValue.sub(nestPrice),1,address(this), address(this), uint256(block.timestamp).add(100));
uint256 receivedEthBalance = address(this).balance.sub(originalEthBalance); uint256 loopTimes = receivedEthBalance.div(cofixETHSapn); if (loopTimes > 1) { uint256 everySwapValue = receivedEthBalance.div(loopTimes); uint256 leftoverValue = receivedEthBalance.mod(loopTimes).add(everySwapValue); for(uint256 i = 0; i < loopTimes - 1; i++) { cofix.swapExactETHForTokens{value:everySwapValue}(mcd.borrowedToken,everySwapValue.sub(nestPrice),1,address(this), address(this), uint256(block.timestamp).add(100));
12,068
205
// apply all of borrower interest refund torwards principal
interestAppliedToPrincipal = interestRefundToBorrower;
interestAppliedToPrincipal = interestRefundToBorrower;
56,929
250
// Total number of underlying assets that can bewithdrawn from the strategy by `owner`, where `owner`
* corresponds to the msg.sender of a {redeem} call. */ function maxWithdraw( address _owner ) external view returns (uint256 _maxWithdraw) { _maxWithdraw = IBaseTokenizedStrategy(address(this)) .availableWithdrawLimit(_owner); if (_maxWithdraw == type(uint256).max) { // Saves a min check if there is no withdrawal limit. _maxWithdraw = convertToAssets(balanceOf(_owner)); } else { _maxWithdraw = Math.min( convertToAssets(balanceOf(_owner)), _maxWithdraw ); } }
* corresponds to the msg.sender of a {redeem} call. */ function maxWithdraw( address _owner ) external view returns (uint256 _maxWithdraw) { _maxWithdraw = IBaseTokenizedStrategy(address(this)) .availableWithdrawLimit(_owner); if (_maxWithdraw == type(uint256).max) { // Saves a min check if there is no withdrawal limit. _maxWithdraw = convertToAssets(balanceOf(_owner)); } else { _maxWithdraw = Math.min( convertToAssets(balanceOf(_owner)), _maxWithdraw ); } }
31,681
93
// File : contract/INVC
contract INVC is ERC20("butt Coin", "tttt"), Ownable { using SafeMath for uint256; uint256 limit; constructor() public { limit = 1000000 * (10 ** 18); // _mint(address(this), 100000); } function increaseLimit(uint256 _limit) external view onlyOwner { limit.add((_limit * (10 ** 18))); } function mint(address account, uint256 amount) external onlyOwner{ require(totalSupply().add(amount) <= limit, "Exceeding the limit"); _mint(account, amount); } function burn(address account, uint256 amount) external onlyOwner{ _burn(account, amount); } }
contract INVC is ERC20("butt Coin", "tttt"), Ownable { using SafeMath for uint256; uint256 limit; constructor() public { limit = 1000000 * (10 ** 18); // _mint(address(this), 100000); } function increaseLimit(uint256 _limit) external view onlyOwner { limit.add((_limit * (10 ** 18))); } function mint(address account, uint256 amount) external onlyOwner{ require(totalSupply().add(amount) <= limit, "Exceeding the limit"); _mint(account, amount); } function burn(address account, uint256 amount) external onlyOwner{ _burn(account, amount); } }
14,862
4
// InstaIndex Address.
address public immutable instaIndex;
address public immutable instaIndex;
10,882
31
// Transfers the NFTs being claimed.
function _transferTokensOnClaim(address _to, uint256 _quantityBeingClaimed) internal virtual override returns (uint256 startTokenId)
function _transferTokensOnClaim(address _to, uint256 _quantityBeingClaimed) internal virtual override returns (uint256 startTokenId)
24,713
28
// player 2 can call timeout on player 1 if player 1 refuses to call reveal()
function claimTimeout() public { if(now < expiration) { revert("Cannot claim until after expiration period"); } address(player2).transfer(address(this).balance); }
function claimTimeout() public { if(now < expiration) { revert("Cannot claim until after expiration period"); } address(player2).transfer(address(this).balance); }
42,624
61
// make the point active and set its new owner
azimuth.activatePoint(_point); azimuth.setOwner(_point, _target); emit Transfer(0x0, _target, uint256(_point));
azimuth.activatePoint(_point); azimuth.setOwner(_point, _target); emit Transfer(0x0, _target, uint256(_point));
3,078
3
// Tracks the deposited ETH service donations during the current epoch./This function is only called by the treasury where the validity of arrays and values has been performed./donator Donator account address./serviceIds Set of service Ids./amounts Correspondent set of ETH amounts provided by services./donationETH Overall service donation amount in ETH.
function trackServiceDonations( address donator, uint256[] memory serviceIds, uint256[] memory amounts, uint256 donationETH ) external;
function trackServiceDonations( address donator, uint256[] memory serviceIds, uint256[] memory amounts, uint256 donationETH ) external;
30,039
4
// Burn tokens on L2. only the token bridge can call this account owner of tokens amount amount of tokens burnt /
function bridgeBurn(address account, uint256 amount) external virtual override onlyGateway { _burn(account, amount); }
function bridgeBurn(address account, uint256 amount) external virtual override onlyGateway { _burn(account, amount); }
34,764
98
// Add _amount
balances[_to][_id] = balances[_to][_id].add(_amount);
balances[_to][_id] = balances[_to][_id].add(_amount);
11,555
27
// From deposit id to the token's id
mapping(uint256 => uint256) public tokenIds;
mapping(uint256 => uint256) public tokenIds;
46,859
0
// Price per unit if buying < AMOUNT_DISCOUNT_ONE
uint256 internal constant PRICE = 70 * 10**15;
uint256 internal constant PRICE = 70 * 10**15;
16,346
67
// Make a request to remove a submission from the list. Requires full deposit. Accepts enough ETH to cover the deposit, reimburses the rest. Note that this request can't be made after the renewal period started to avoid spam leading to submission's expiration._submissionID The address of the submission to remove._evidence A link to evidence using its URI. /
function removeSubmission(address _submissionID, string calldata _evidence) external payable { Submission storage submission = submissions[_submissionID]; require(submission.registered && submission.status == Status.None, "Wrong status"); uint renewalAvailableAt = submission.submissionTime.addCap64(submissionDuration.subCap64(renewalPeriodDuration)); require(now < renewalAvailableAt, "Can't remove after renewal"); submission.status = Status.PendingRemoval; Request storage request = submission.requests[submission.requests.length++]; request.requester = msg.sender; request.challengePeriodStart = uint64(now); uint arbitratorDataID = arbitratorDataList.length - 1; request.arbitratorDataID = uint16(arbitratorDataID); Round storage round = request.challenges[0].rounds[0]; IArbitrator requestArbitrator = arbitratorDataList[arbitratorDataID].arbitrator; uint arbitrationCost = requestArbitrator.arbitrationCost(arbitratorDataList[arbitratorDataID].arbitratorExtraData); uint totalCost = arbitrationCost.addCap(submissionBaseDeposit); contribute(round, Party.Requester, msg.sender, msg.value, totalCost); require(round.paidFees[uint(Party.Requester)] >= totalCost, "You must fully fund your side"); round.sideFunded = Party.Requester; emit RemoveSubmission(msg.sender, _submissionID, submission.requests.length - 1); if (bytes(_evidence).length > 0) emit Evidence(requestArbitrator, submission.requests.length - 1 + uint(_submissionID), msg.sender, _evidence); }
function removeSubmission(address _submissionID, string calldata _evidence) external payable { Submission storage submission = submissions[_submissionID]; require(submission.registered && submission.status == Status.None, "Wrong status"); uint renewalAvailableAt = submission.submissionTime.addCap64(submissionDuration.subCap64(renewalPeriodDuration)); require(now < renewalAvailableAt, "Can't remove after renewal"); submission.status = Status.PendingRemoval; Request storage request = submission.requests[submission.requests.length++]; request.requester = msg.sender; request.challengePeriodStart = uint64(now); uint arbitratorDataID = arbitratorDataList.length - 1; request.arbitratorDataID = uint16(arbitratorDataID); Round storage round = request.challenges[0].rounds[0]; IArbitrator requestArbitrator = arbitratorDataList[arbitratorDataID].arbitrator; uint arbitrationCost = requestArbitrator.arbitrationCost(arbitratorDataList[arbitratorDataID].arbitratorExtraData); uint totalCost = arbitrationCost.addCap(submissionBaseDeposit); contribute(round, Party.Requester, msg.sender, msg.value, totalCost); require(round.paidFees[uint(Party.Requester)] >= totalCost, "You must fully fund your side"); round.sideFunded = Party.Requester; emit RemoveSubmission(msg.sender, _submissionID, submission.requests.length - 1); if (bytes(_evidence).length > 0) emit Evidence(requestArbitrator, submission.requests.length - 1 + uint(_submissionID), msg.sender, _evidence); }
13,755
77
// The token is initially owned by the deployer address, who create the initial distribution.For convenience, an initial supply can be passed in the constructor that will beassigned to the deployer./
contract GRAPHmodX is Governed, ERC20, ERC20Burnable { using SafeMath for uint256; // -- initialSupply variable initial state bool initialSupplyFinish = false; constructor() ERC20("GRAPHmodX.finance", "GRAX") { Governed._initialize(msg.sender); } /** * @dev This implementation is agnostic to the way tokens are created. * This means that a supply mechanism has to be added in a derived contract. * * 'initailSupplyfinish' must be 'false' to execute this function, * however after first use, 'true' will change to 'false' to lock this function forever. * */ function initialSupply(address contractAddress, uint256 InitialSupply) public onlyGovernor { require(initialSupplyFinish == false); _totalSupply = _totalSupply.add(InitialSupply); _balances[contractAddress] = _balances[contractAddress].add(InitialSupply); InitialSupplyFinish = true; } /** * @dev This return state of initialSupply function: * * 'false' means that initialSupply is not done yet. * 'true' means that it's locked forever. * */ function initialSupplyFinishState () public view returns (bool) { return InitialSupplyFinish; } }
contract GRAPHmodX is Governed, ERC20, ERC20Burnable { using SafeMath for uint256; // -- initialSupply variable initial state bool initialSupplyFinish = false; constructor() ERC20("GRAPHmodX.finance", "GRAX") { Governed._initialize(msg.sender); } /** * @dev This implementation is agnostic to the way tokens are created. * This means that a supply mechanism has to be added in a derived contract. * * 'initailSupplyfinish' must be 'false' to execute this function, * however after first use, 'true' will change to 'false' to lock this function forever. * */ function initialSupply(address contractAddress, uint256 InitialSupply) public onlyGovernor { require(initialSupplyFinish == false); _totalSupply = _totalSupply.add(InitialSupply); _balances[contractAddress] = _balances[contractAddress].add(InitialSupply); InitialSupplyFinish = true; } /** * @dev This return state of initialSupply function: * * 'false' means that initialSupply is not done yet. * 'true' means that it's locked forever. * */ function initialSupplyFinishState () public view returns (bool) { return InitialSupplyFinish; } }
40,630
12
// ´:°•.°+.•´.:˚.°.˚•´.°:°•.°•.•´.:˚.°.˚•´.°:°•.°+.•´.:// DECIMAL OPERATIONS //.•°:°.´+˚.°.˚:.´•.+°.•°:´.´•.•°.•°:°.´:•˚°.°.˚:.´+°.•//Returns the base 10 decimal representation of `value`.
function toString(uint256 value) internal pure returns (string memory str) { /// @solidity memory-safe-assembly assembly { // The maximum value of a uint256 contains 78 digits (1 byte per digit), but // we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned. // We will need 1 word for the trailing zeros padding, 1 word for the length, // and 3 words for a maximum of 78 digits. str := add(mload(0x40), 0x80) // Update the free memory pointer to allocate. mstore(0x40, add(str, 0x20)) // Zeroize the slot after the string. mstore(str, 0) // Cache the end of the memory to calculate the length later. let end := str let w := not(0) // Tsk. // We write the string from rightmost digit to leftmost digit. // The following is essentially a do-while loop that also handles the zero case. for { let temp := value } 1 {} { str := add(str, w) // `sub(str, 1)`. // Write the character to the pointer. // The ASCII index of the '0' character is 48. mstore8(str, add(48, mod(temp, 10))) // Keep dividing `temp` until zero. temp := div(temp, 10) if iszero(temp) { break } } let length := sub(end, str) // Move the pointer 32 bytes leftwards to make room for the length. str := sub(str, 0x20) // Store the length. mstore(str, length) }
function toString(uint256 value) internal pure returns (string memory str) { /// @solidity memory-safe-assembly assembly { // The maximum value of a uint256 contains 78 digits (1 byte per digit), but // we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned. // We will need 1 word for the trailing zeros padding, 1 word for the length, // and 3 words for a maximum of 78 digits. str := add(mload(0x40), 0x80) // Update the free memory pointer to allocate. mstore(0x40, add(str, 0x20)) // Zeroize the slot after the string. mstore(str, 0) // Cache the end of the memory to calculate the length later. let end := str let w := not(0) // Tsk. // We write the string from rightmost digit to leftmost digit. // The following is essentially a do-while loop that also handles the zero case. for { let temp := value } 1 {} { str := add(str, w) // `sub(str, 1)`. // Write the character to the pointer. // The ASCII index of the '0' character is 48. mstore8(str, add(48, mod(temp, 10))) // Keep dividing `temp` until zero. temp := div(temp, 10) if iszero(temp) { break } } let length := sub(end, str) // Move the pointer 32 bytes leftwards to make room for the length. str := sub(str, 0x20) // Store the length. mstore(str, length) }
33,965
177
// Assert order offset (this is an internal error that should never be triggered)
if lt(order, 32) { invalid() }
if lt(order, 32) { invalid() }
12,228
114
// The PAPR3KA2 TOKEN!
PAPR3KA_Token public PAPR3KA;
PAPR3KA_Token public PAPR3KA;
19,792
6
// If there are no pools to finalize then the epoch is finalized.
if (aggregatedStats.numPoolsToFinalize == 0) { emit EpochFinalized(currentEpoch_, 0, aggregatedStats.rewardsAvailable); }
if (aggregatedStats.numPoolsToFinalize == 0) { emit EpochFinalized(currentEpoch_, 0, aggregatedStats.rewardsAvailable); }
15,754
265
// Option Three: Some ETH goes towards ICO-price tokens, some goes towards variable-price tokens
ethTowardsICOPriceTokens = ethInvestedDuringICO.sub(currentEthInvested); ethTowardsVariablePriceTokens = _ethereumAmount.sub(ethTowardsICOPriceTokens);
ethTowardsICOPriceTokens = ethInvestedDuringICO.sub(currentEthInvested); ethTowardsVariablePriceTokens = _ethereumAmount.sub(ethTowardsICOPriceTokens);
76,606
75
// Equals to `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` which can be also obtained as `IERC1363Receiver(0).onTransferReceived.selector`
bytes4 private constant _ERC1363_RECEIVED = 0x88a7ca5c;
bytes4 private constant _ERC1363_RECEIVED = 0x88a7ca5c;
39,960
142
// Pauses deposits. Withdraws all funds from the RewardPool, leaving rewards behind /
function panic() public onlyOwner { pause(); IRewardPool(rewardPool).emergencyWithdraw(poolId); }
function panic() public onlyOwner { pause(); IRewardPool(rewardPool).emergencyWithdraw(poolId); }
13,077
150
// ex:Aphra Vader Vault
string(abi.encodePacked("Aphra ", _UNDERLYING.name(), " Vault")),
string(abi.encodePacked("Aphra ", _UNDERLYING.name(), " Vault")),
21,338
9
// Read only function to retrieve the token balance of a given account. The `view` modifier indicates that it doesn't modify the contract'sstate, which allows us to call it without executing a transaction. /
function balanceOf(address account) external view returns (uint256) { return balances[account]; }
function balanceOf(address account) external view returns (uint256) { return balances[account]; }
5,878
2
// It adds a new account as a signer. asset Token address to add signers for. account address to add. The sender must be the owner. It throws a require error if the sender is not the owner. /
function addSigner(address asset, address account) external { _addSigner(asset, account); }
function addSigner(address asset, address account) external { _addSigner(asset, account); }
43,381
16
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true;
balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true;
2,097
7
// Execute swap transaction _data: swap data _gasFee: gasfee to send treasury /
) external payable { // require(msg.value >= _gasFee, "Not enough ETH fee"); // // charge ETH fee // safeTransferETH(treasury, _gasFee); // exectue swap function (bool success, bytes memory returnData) = _target.delegatecall(_data); if (!success) { decodeRevert(returnData); } // // refund dust eth, if any // if (msg.value > _gasFee) // safeTransferETH(msg.sender, msg.value - _gasFee); // userFeeCharged[msg.sender] += _gasFee; emit FeePayed(msg.sender, _gasFee); }
) external payable { // require(msg.value >= _gasFee, "Not enough ETH fee"); // // charge ETH fee // safeTransferETH(treasury, _gasFee); // exectue swap function (bool success, bytes memory returnData) = _target.delegatecall(_data); if (!success) { decodeRevert(returnData); } // // refund dust eth, if any // if (msg.value > _gasFee) // safeTransferETH(msg.sender, msg.value - _gasFee); // userFeeCharged[msg.sender] += _gasFee; emit FeePayed(msg.sender, _gasFee); }
81,747
444
// Reads the uint88 at `cdPtr` in calldata.
function readUint88( CalldataPointer cdPtr
function readUint88( CalldataPointer cdPtr
23,559
371
// Base64/Brecht Devos - <brecht@loopring.org>/Provides functions for encoding/decoding base64
library Base64 { string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000" hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000" hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000" hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000"; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE_ENCODE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { // read 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // write 4 characters mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F)))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } function decode(string memory _data) internal pure returns (bytes memory) { bytes memory data = bytes(_data); if (data.length == 0) return new bytes(0); require(data.length % 4 == 0, "invalid base64 decoder input"); // load the table into memory bytes memory table = TABLE_DECODE; // every 4 characters represent 3 bytes uint256 decodedLen = (data.length / 4) * 3; // add some extra buffer at the end required for the writing bytes memory result = new bytes(decodedLen + 32); assembly { // padding with '=' let lastBytes := mload(add(data, mload(data))) if eq(and(lastBytes, 0xFF), 0x3d) { decodedLen := sub(decodedLen, 1) if eq(and(lastBytes, 0xFFFF), 0x3d3d) { decodedLen := sub(decodedLen, 1) } } // set the actual output length mstore(result, decodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 4 characters at a time for {} lt(dataPtr, endPtr) {} { // read 4 characters dataPtr := add(dataPtr, 4) let input := mload(dataPtr) // write 3 bytes let output := add( add( shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)), shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))), add( shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)), and(mload(add(tablePtr, and( input , 0xFF))), 0xFF) ) ) mstore(resultPtr, shl(232, output)) resultPtr := add(resultPtr, 3) } } return result; } }
library Base64 { string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000" hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000" hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000" hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000"; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE_ENCODE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { // read 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // write 4 characters mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F)))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } function decode(string memory _data) internal pure returns (bytes memory) { bytes memory data = bytes(_data); if (data.length == 0) return new bytes(0); require(data.length % 4 == 0, "invalid base64 decoder input"); // load the table into memory bytes memory table = TABLE_DECODE; // every 4 characters represent 3 bytes uint256 decodedLen = (data.length / 4) * 3; // add some extra buffer at the end required for the writing bytes memory result = new bytes(decodedLen + 32); assembly { // padding with '=' let lastBytes := mload(add(data, mload(data))) if eq(and(lastBytes, 0xFF), 0x3d) { decodedLen := sub(decodedLen, 1) if eq(and(lastBytes, 0xFFFF), 0x3d3d) { decodedLen := sub(decodedLen, 1) } } // set the actual output length mstore(result, decodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 4 characters at a time for {} lt(dataPtr, endPtr) {} { // read 4 characters dataPtr := add(dataPtr, 4) let input := mload(dataPtr) // write 3 bytes let output := add( add( shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)), shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))), add( shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)), and(mload(add(tablePtr, and( input , 0xFF))), 0xFF) ) ) mstore(resultPtr, shl(232, output)) resultPtr := add(resultPtr, 3) } } return result; } }
6,780
47
// TODO: Decode directly into a struct?
( uint256 transitionType, bytes32 stateRoot, uint256 accountSlotIndex, address account, uint256 tokenIndex, uint256 amount, bytes memory signature ) = abi.decode( (_rawBytes),
( uint256 transitionType, bytes32 stateRoot, uint256 accountSlotIndex, address account, uint256 tokenIndex, uint256 amount, bytes memory signature ) = abi.decode( (_rawBytes),
40,540
2
// Deploy with the address of the LINK token
constructor(address _link) public { // Set the address for the LINK token for the network setChainlinkToken(_link); owner = msg.sender; }
constructor(address _link) public { // Set the address for the LINK token for the network setChainlinkToken(_link); owner = msg.sender; }
9,171
74
// See {IERC721-safeTransferFrom}. /
function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); }
function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); }
8,900
14
// Delegate to internal OpenZeppelin mint function
_mint(_to, _tokenId + i);
_mint(_to, _tokenId + i);
61,615
312
// Allows the owner to change the base URI that hosts the images
function setBaseURI(string calldata _uri) external onlyOwner { __baseURI = _uri; }
function setBaseURI(string calldata _uri) external onlyOwner { __baseURI = _uri; }
69,953
987
// get all tokens currently supported by the contract/ return supportedTokensArray an array of supported token structs
function getSupportedTokens() external view returns (SupportedTokenData[] memory supportedTokensArray);
function getSupportedTokens() external view returns (SupportedTokenData[] memory supportedTokensArray);
47,670
119
// Restore tax and liquidity fees
_taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) restoreAllFee();
_taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) restoreAllFee();
7,855
2
// bind the nft to the shares
_issuance.issue(issuer, nft, tokenId, erc20Shares, numberOfSharestoIssue);
_issuance.issue(issuer, nft, tokenId, erc20Shares, numberOfSharestoIssue);
34,760
9
// return if vault should be settled _owner owner address _vaultId vaultId to settlereturn true if vault can be settled, contract is operator of owner, and excess collateral is greater than zero /
function shouldSettleVault(address _owner, uint256 _vaultId) public view returns (bool)
function shouldSettleVault(address _owner, uint256 _vaultId) public view returns (bool)
14,436
8
// burn to address amount amount /
function burnToken(address to, uint256 amount) public onlyOwner { _burn(to, amount); emit balanceChanged(to, amount, balanceOf(to)); }
function burnToken(address to, uint256 amount) public onlyOwner { _burn(to, amount); emit balanceChanged(to, amount, balanceOf(to)); }
1,406
119
// reset latest Oracle Caller for protect from double call
latestOracleCaller = address(0); uint256 withdrawShares = numberOfWithdrawShares.mul(fundValue.sub(fundManagerCut)).div(fundValue);
latestOracleCaller = address(0); uint256 withdrawShares = numberOfWithdrawShares.mul(fundValue.sub(fundManagerCut)).div(fundValue);
28,874
404
// Ensure the msg.sender is the current DisputeManager module/
modifier onlyCurrentDisputeManager() { (address addr, bool disabled) = controller.getDisputeManager(); require(msg.sender == addr, ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER); require(!disabled, ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER); _; }
modifier onlyCurrentDisputeManager() { (address addr, bool disabled) = controller.getDisputeManager(); require(msg.sender == addr, ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER); require(!disabled, ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER); _; }
19,614
16
// Holds the list of IWhitelistable (e.g. ERC-721) projects in which ownership affords whitelisting
IWhitelistable[] private _approvedProjects;
IWhitelistable[] private _approvedProjects;
63,966
223
// Signature (for example full exit signature) bytes length
uint8 constant SIGNATURE_BYTES = 64;
uint8 constant SIGNATURE_BYTES = 64;
16,107
23
// Determine amount of tokens user wants to/can buy
uint256 iou_to_purchase = 160 * msg.value; // price is 160 per ETH
uint256 iou_to_purchase = 160 * msg.value; // price is 160 per ETH
38,007
149
// The index in storage starts with 1, then need sub(1)
lpIndexInPool[keccak256(abi.encodePacked(poolinfos_id, _lpToken))] = 1; emit AddPool(poolinfos_id, address(_lpToken), _lpTokenType, _lpFactor);
lpIndexInPool[keccak256(abi.encodePacked(poolinfos_id, _lpToken))] = 1; emit AddPool(poolinfos_id, address(_lpToken), _lpTokenType, _lpFactor);
36,756
0
// Provide a basic structure for each request to be created by manager
struct Request { int approvalCount; string description; mapping(address => bool) approvals; address recipient; int value; bool isComplete; }
struct Request { int approvalCount; string description; mapping(address => bool) approvals; address recipient; int value; bool isComplete; }
53,542
8
// Verify if the user is whitelisted
require(MerkleProof.verify(_merkleProof, rootHash, keccak256(abi.encodePacked(msg.sender))), "Invalid proof because you are not whitelisted"); require(msg.value == cost * _mintAmount, "Insufficient fund in your wallet"); whitelistMintCounter[msg.sender] += _mintAmount; _safeMint(msg.sender, _mintAmount);
require(MerkleProof.verify(_merkleProof, rootHash, keccak256(abi.encodePacked(msg.sender))), "Invalid proof because you are not whitelisted"); require(msg.value == cost * _mintAmount, "Insufficient fund in your wallet"); whitelistMintCounter[msg.sender] += _mintAmount; _safeMint(msg.sender, _mintAmount);
11,684
2
// OWNER
function pause() external onlyOwner
function pause() external onlyOwner
15,220
35
// RESOLUTION / LXL `client` or `provider` can lock to freeze release and withdrawal of sum remainder until `resolver` calls `resolve()`.`lock()` can be called repeatedly to allow LXL parties to continue to provide context until resolution.registration Registered LXL index. details Context re: lock and/or dispute. /
function lock(uint256 registration, string calldata details) external nonReentrant { Locker storage locker = lockers[registration]; require(_msgSender() == locker.client || _msgSender() == locker.provider, "!party"); require(locker.confirmed == 1, "!confirmed"); require(locker.released < locker.sum, "released"); locker.locked = 1; emit Lock(_msgSender(), registration, details); }
function lock(uint256 registration, string calldata details) external nonReentrant { Locker storage locker = lockers[registration]; require(_msgSender() == locker.client || _msgSender() == locker.provider, "!party"); require(locker.confirmed == 1, "!confirmed"); require(locker.released < locker.sum, "released"); locker.locked = 1; emit Lock(_msgSender(), registration, details); }
20,888
295
// require( this.getWithdrawableAmount() >= _amount, "cannot create vesting schedule because not sufficient tokens" );
require(_duration > 0, "duration must be > 0"); require(_amount > 0, "amount must be > 0"); require(_cliff <= _duration, "invalid cliff"); require(_slicePeriodSeconds >= 1, "slicePeriodSeconds must be >= 1"); bytes32 vestingScheduleId = this.computeNextVestingScheduleIdForHolder(_beneficiary); uint256 cliff = _start.add(_cliff); vestingSchedules[vestingScheduleId] = VestingSchedule( true, _beneficiary,
require(_duration > 0, "duration must be > 0"); require(_amount > 0, "amount must be > 0"); require(_cliff <= _duration, "invalid cliff"); require(_slicePeriodSeconds >= 1, "slicePeriodSeconds must be >= 1"); bytes32 vestingScheduleId = this.computeNextVestingScheduleIdForHolder(_beneficiary); uint256 cliff = _start.add(_cliff); vestingSchedules[vestingScheduleId] = VestingSchedule( true, _beneficiary,
35,941
1
// Set the AllowanceModule. _moduleAddress The address of the AllowanceModule. /
function setAllowanceModule(address _moduleAddress) public onlyOwner returns (bool) { allowanceModule = AllowanceModule(_moduleAddress); allowanceModule.claimOwnership(); emit AllowanceModuleSet(_moduleAddress); return true; }
function setAllowanceModule(address _moduleAddress) public onlyOwner returns (bool) { allowanceModule = AllowanceModule(_moduleAddress); allowanceModule.claimOwnership(); emit AllowanceModuleSet(_moduleAddress); return true; }
38,877
44
// Case 1 - The caller is the winner
if (winner) {
if (winner) {
27,882
32
// Adapter Logic/
contract TvlAdapterEarn { /******************************************************* * Common code shared by all adapters * *******************************************************/ IOracle public oracle; // The oracle is used to fetch USDC normalized pricing data IAddressesGenerator public addressesGenerator; // A utility for fetching assets addresses and length IDelegationMapping public delegationMapping; /** * TVL breakdown for an asset */ struct AssetTvlBreakdown { address assetId; // Asset address address tokenId; // Token address uint256 tokenPriceUsdc; // Token price in USDC uint256 underlyingTokenBalance; // Amount of underlying token in asset uint256 delegatedBalance; // Amount of underlying token balance that is delegated uint256 adjustedBalance; // underlyingTokenBalance - delegatedBalance uint256 adjustedBalanceUsdc; // TVL } /** * Information about the adapter */ struct AdapterInfo { address id; // Adapter address string typeId; // Adapter typeId (for example "VAULT_V2" or "IRON_BANK_MARKET") string categoryId; // Adapter categoryId (for example "VAULT") } /** * Configure adapter */ constructor( address _oracleAddress, address _addressesGeneratorAddress, address _delegationMappingAddress ) { oracle = IOracle(_oracleAddress); addressesGenerator = IAddressesGenerator(_addressesGeneratorAddress); delegationMapping = IDelegationMapping(_delegationMappingAddress); } /** * Fetch the total number of assets for this adapter */ function assetsLength() public view returns (uint256) { return addressesGenerator.assetsLength(); } /** * Fetch all asset addresses for this adapter */ function assetsAddresses() public view returns (address[] memory) { return addressesGenerator.assetsAddresses(); } // Fetch TVL breakdown for adapter given an array of addresses function assetsTvlBreakdown(address[] memory _assetsAddresses) public view returns (AssetTvlBreakdown[] memory) { uint256 numberOfAssets = _assetsAddresses.length; AssetTvlBreakdown[] memory tvlData = new AssetTvlBreakdown[](numberOfAssets); for (uint256 assetIdx = 0; assetIdx < numberOfAssets; assetIdx++) { address assetAddress = _assetsAddresses[assetIdx]; tvlData[assetIdx] = assetTvlBreakdown(assetAddress); } return tvlData; } /** * Fetch TVL breakdown for adapter */ function assetsTvlBreakdown() external view returns (AssetTvlBreakdown[] memory) { address[] memory _assetsAddresses = assetsAddresses(); return assetsTvlBreakdown(_assetsAddresses); } /** * Fetch TVL breakdown of an asset */ function assetTvlBreakdown(address assetAddress) public view returns (AssetTvlBreakdown memory) { address tokenAddress = underlyingTokenAddress(assetAddress); uint256 underlyingBalanceAmount = assetBalance(assetAddress); uint256 delegatedBalanceAmount = assetDelegatedBalance(assetAddress); uint256 adjustedBalance = underlyingBalanceAmount - delegatedBalanceAmount; uint256 tokenPriceUsdc = oracle.getPriceUsdcRecommended(tokenAddress); return AssetTvlBreakdown({ assetId: assetAddress, tokenId: tokenAddress, tokenPriceUsdc: tokenPriceUsdc, underlyingTokenBalance: underlyingBalanceAmount, delegatedBalance: delegatedBalanceAmount, adjustedBalance: adjustedBalance, adjustedBalanceUsdc: oracle.getNormalizedValueUsdc( tokenAddress, adjustedBalance, tokenPriceUsdc ) }); } /** * Fetch TVL for adapter in USDC */ function assetsTvlUsdc(address[] memory _assetsAddresses) public view returns (uint256) { uint256 tvl; uint256 numberOfAssets = assetsLength(); for (uint256 assetIdx = 0; assetIdx < numberOfAssets; assetIdx++) { address assetAddress = _assetsAddresses[assetIdx]; uint256 _assetTvl = assetTvlUsdc(assetAddress); tvl += _assetTvl; } return tvl; } /** * Fetch TVL for adapter in USDC given an array of addresses */ function assetsTvlUsdc() external view returns (uint256) { address[] memory _assetsAddresses = assetsAddresses(); return assetsTvlUsdc(_assetsAddresses); } /** * Fetch TVL of an asset in USDC */ function assetTvlUsdc(address assetAddress) public view returns (uint256) { address tokenAddress = underlyingTokenAddress(assetAddress); uint256 underlyingBalanceAmount = assetBalance(assetAddress); uint256 delegatedBalanceAmount = assetDelegatedBalance(assetAddress); uint256 adjustedBalanceAmount = underlyingBalanceAmount - delegatedBalanceAmount; uint256 adjustedBalanceUsdc = oracle.getNormalizedValueUsdc(tokenAddress, adjustedBalanceAmount); return adjustedBalanceUsdc; } /******************************************************* * Asset-specific Logic * *******************************************************/ /** * Fetch adapter info */ function adapterInfo() public view returns (AdapterInfo memory) { return AdapterInfo({ id: address(this), typeId: "EARN", categoryId: "SAFE" }); } /** * Fetch the underlying token address of an asset */ function underlyingTokenAddress(address assetAddress) public view returns (address) { IEarnToken earnToken = IEarnToken(assetAddress); address tokenAddress = earnToken.token(); return tokenAddress; } /** * Fetch asset balance in underlying tokens */ function assetBalance(address assetAddress) public view returns (uint256) { IEarnToken earnToken = IEarnToken(assetAddress); return earnToken.calcPoolValueInToken(); } /** * Fetch delegated balance of an asset */ function assetDelegatedBalance(address assetAddress) public view returns (uint256) { bool balanceIsDelegated = delegationMapping.assetBalanceIsDelegated(assetAddress); if (balanceIsDelegated) { return assetBalance(assetAddress); } return 0; } }
contract TvlAdapterEarn { /******************************************************* * Common code shared by all adapters * *******************************************************/ IOracle public oracle; // The oracle is used to fetch USDC normalized pricing data IAddressesGenerator public addressesGenerator; // A utility for fetching assets addresses and length IDelegationMapping public delegationMapping; /** * TVL breakdown for an asset */ struct AssetTvlBreakdown { address assetId; // Asset address address tokenId; // Token address uint256 tokenPriceUsdc; // Token price in USDC uint256 underlyingTokenBalance; // Amount of underlying token in asset uint256 delegatedBalance; // Amount of underlying token balance that is delegated uint256 adjustedBalance; // underlyingTokenBalance - delegatedBalance uint256 adjustedBalanceUsdc; // TVL } /** * Information about the adapter */ struct AdapterInfo { address id; // Adapter address string typeId; // Adapter typeId (for example "VAULT_V2" or "IRON_BANK_MARKET") string categoryId; // Adapter categoryId (for example "VAULT") } /** * Configure adapter */ constructor( address _oracleAddress, address _addressesGeneratorAddress, address _delegationMappingAddress ) { oracle = IOracle(_oracleAddress); addressesGenerator = IAddressesGenerator(_addressesGeneratorAddress); delegationMapping = IDelegationMapping(_delegationMappingAddress); } /** * Fetch the total number of assets for this adapter */ function assetsLength() public view returns (uint256) { return addressesGenerator.assetsLength(); } /** * Fetch all asset addresses for this adapter */ function assetsAddresses() public view returns (address[] memory) { return addressesGenerator.assetsAddresses(); } // Fetch TVL breakdown for adapter given an array of addresses function assetsTvlBreakdown(address[] memory _assetsAddresses) public view returns (AssetTvlBreakdown[] memory) { uint256 numberOfAssets = _assetsAddresses.length; AssetTvlBreakdown[] memory tvlData = new AssetTvlBreakdown[](numberOfAssets); for (uint256 assetIdx = 0; assetIdx < numberOfAssets; assetIdx++) { address assetAddress = _assetsAddresses[assetIdx]; tvlData[assetIdx] = assetTvlBreakdown(assetAddress); } return tvlData; } /** * Fetch TVL breakdown for adapter */ function assetsTvlBreakdown() external view returns (AssetTvlBreakdown[] memory) { address[] memory _assetsAddresses = assetsAddresses(); return assetsTvlBreakdown(_assetsAddresses); } /** * Fetch TVL breakdown of an asset */ function assetTvlBreakdown(address assetAddress) public view returns (AssetTvlBreakdown memory) { address tokenAddress = underlyingTokenAddress(assetAddress); uint256 underlyingBalanceAmount = assetBalance(assetAddress); uint256 delegatedBalanceAmount = assetDelegatedBalance(assetAddress); uint256 adjustedBalance = underlyingBalanceAmount - delegatedBalanceAmount; uint256 tokenPriceUsdc = oracle.getPriceUsdcRecommended(tokenAddress); return AssetTvlBreakdown({ assetId: assetAddress, tokenId: tokenAddress, tokenPriceUsdc: tokenPriceUsdc, underlyingTokenBalance: underlyingBalanceAmount, delegatedBalance: delegatedBalanceAmount, adjustedBalance: adjustedBalance, adjustedBalanceUsdc: oracle.getNormalizedValueUsdc( tokenAddress, adjustedBalance, tokenPriceUsdc ) }); } /** * Fetch TVL for adapter in USDC */ function assetsTvlUsdc(address[] memory _assetsAddresses) public view returns (uint256) { uint256 tvl; uint256 numberOfAssets = assetsLength(); for (uint256 assetIdx = 0; assetIdx < numberOfAssets; assetIdx++) { address assetAddress = _assetsAddresses[assetIdx]; uint256 _assetTvl = assetTvlUsdc(assetAddress); tvl += _assetTvl; } return tvl; } /** * Fetch TVL for adapter in USDC given an array of addresses */ function assetsTvlUsdc() external view returns (uint256) { address[] memory _assetsAddresses = assetsAddresses(); return assetsTvlUsdc(_assetsAddresses); } /** * Fetch TVL of an asset in USDC */ function assetTvlUsdc(address assetAddress) public view returns (uint256) { address tokenAddress = underlyingTokenAddress(assetAddress); uint256 underlyingBalanceAmount = assetBalance(assetAddress); uint256 delegatedBalanceAmount = assetDelegatedBalance(assetAddress); uint256 adjustedBalanceAmount = underlyingBalanceAmount - delegatedBalanceAmount; uint256 adjustedBalanceUsdc = oracle.getNormalizedValueUsdc(tokenAddress, adjustedBalanceAmount); return adjustedBalanceUsdc; } /******************************************************* * Asset-specific Logic * *******************************************************/ /** * Fetch adapter info */ function adapterInfo() public view returns (AdapterInfo memory) { return AdapterInfo({ id: address(this), typeId: "EARN", categoryId: "SAFE" }); } /** * Fetch the underlying token address of an asset */ function underlyingTokenAddress(address assetAddress) public view returns (address) { IEarnToken earnToken = IEarnToken(assetAddress); address tokenAddress = earnToken.token(); return tokenAddress; } /** * Fetch asset balance in underlying tokens */ function assetBalance(address assetAddress) public view returns (uint256) { IEarnToken earnToken = IEarnToken(assetAddress); return earnToken.calcPoolValueInToken(); } /** * Fetch delegated balance of an asset */ function assetDelegatedBalance(address assetAddress) public view returns (uint256) { bool balanceIsDelegated = delegationMapping.assetBalanceIsDelegated(assetAddress); if (balanceIsDelegated) { return assetBalance(assetAddress); } return 0; } }
25,652
117
// Convex
Booster private constant BOOSTER = Booster(0xF403C135812408BFbE8713b5A23a04b3D48AAE31);
Booster private constant BOOSTER = Booster(0xF403C135812408BFbE8713b5A23a04b3D48AAE31);
20,994
349
// Ref: https:github.com/Uniswap/uniswap-v2-core/blob/master/contracts/interfaces/IUniswapV2Pair.sol
interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom( address from, address to, uint value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit( address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap( uint amount0Out, uint amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; }
interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom( address from, address to, uint value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit( address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap( uint amount0Out, uint amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; }
69,887
13
// Use `private` to disallow other smart contracts from directly querying lockbox state.
mapping(uint256 => LockboxState) private lockboxes; uint256 public nextLockboxId; uint256 public constant MAX_MIGRATIONS = 10;
mapping(uint256 => LockboxState) private lockboxes; uint256 public nextLockboxId; uint256 public constant MAX_MIGRATIONS = 10;
40,696
141
// The Dragon's genetic code is packed into these 256-bits.
uint256 dna; uint64 birthTime; uint64 breedTime; uint32 matronId; uint32 sireId; uint32 siringWithId; uint32 generation;
uint256 dna; uint64 birthTime; uint64 breedTime; uint32 matronId; uint32 sireId; uint32 siringWithId; uint32 generation;
7,598
54
// Allows the CEO to revmove a connected WishListTokenThis revokes the reward and exchange functions /
function resetWLCParams() public onlyCEO { WLCAdress = address(0); WLCRewardAmount = 0; }
function resetWLCParams() public onlyCEO { WLCAdress = address(0); WLCRewardAmount = 0; }
21,420
7
// Adds an integer with the key "times" to the request parameters
req.addInt("times", 100);
req.addInt("times", 100);
49,647
92
// call permit before transferring token
uint256 deadline = _permit.toUint256(0); (bytes32 r, bytes32 s, uint8 v) = _permit.parseSignature(32); IERC20Permit(_tokenAddress).permit( msg.sender, address(this), _amount, deadline, v, r, s);
uint256 deadline = _permit.toUint256(0); (bytes32 r, bytes32 s, uint8 v) = _permit.parseSignature(32); IERC20Permit(_tokenAddress).permit( msg.sender, address(this), _amount, deadline, v, r, s);
76,764
21
// Proxy._implementation implementation
function _implementation() internal view virtual override returns (address) { return UUPSUtils.implementation(); }
function _implementation() internal view virtual override returns (address) { return UUPSUtils.implementation(); }
18,417
42
// Return the schedule by `_cid` and `_sid` _cid The contributor's id _sid The schedule's idreturn The schedule /
function schedule(uint256 _cid, uint256 _sid) public scheduleValid(_cid, _sid) view
function schedule(uint256 _cid, uint256 _sid) public scheduleValid(_cid, _sid) view
18,714
221
// Math: worst case MAX2MAX_BEFORE_SQUARE / MAX_BEFORE_SQUAREMAX_BEFORE_SQUARE
tokenValue = BigDiv.bigDiv2x1( currencyValue, 2 * buySlopeDen, initGoal * buySlopeNum ); if(currencyValue != _currencyValue) { currencyValue = _currencyValue - max;
tokenValue = BigDiv.bigDiv2x1( currencyValue, 2 * buySlopeDen, initGoal * buySlopeNum ); if(currencyValue != _currencyValue) { currencyValue = _currencyValue - max;
4,884