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
0
// initial value of portfolio
uint public principal;
uint public principal;
47,980
82
// Only token owner can UnWrap
burnFor = IERC721Mintable(_wNFTAddress).ownerOf(_wNFTTokenId); require(burnFor == msg.sender, 'Only owner can unwrap it' );
burnFor = IERC721Mintable(_wNFTAddress).ownerOf(_wNFTTokenId); require(burnFor == msg.sender, 'Only owner can unwrap it' );
8,959
7
// reader contract to easily fetch all relevant info for an account
contract View { struct Data { uint256 pendingRewards; Pool[] pools; EscrowPool escrowPool; uint256 totalWeight; } struct Deposit { uint256 amount; uint64 start; uint64 end; uint256 multiplier; } struct Pool { address poolAddress; uint256 totalPoolShares; address depositToken; uint256 accountPendingRewards; uint256 accountClaimedRewards; uint256 accountTotalDeposit; uint256 accountPoolShares; uint256 weight; Deposit[] deposits; } struct EscrowPool { address poolAddress; uint256 totalPoolShares; uint256 accountTotalDeposit; uint256 accountPoolShares; FancyEscrowPool.Deposit[] deposits; } LiquidityMiningManager public immutable liquidityMiningManager; FancyEscrowPool public immutable escrowPool; constructor(address _liquidityMiningManager, address _escrowPool) { liquidityMiningManager = LiquidityMiningManager(_liquidityMiningManager); escrowPool = FancyEscrowPool(_escrowPool); } function fetchData(address _account) external view returns (Data memory result) { // uint256 rewardPerSecond = liquidityMiningManager.rewardPerSecond(); // uint256 lastDistribution = liquidityMiningManager.lastDistribution(); // uint256 pendingRewards = rewardPerSecond * (block.timestamp - lastDistribution); result.totalWeight = liquidityMiningManager.totalWeight(); LiquidityMiningManager.Pool[] memory pools = liquidityMiningManager.getPools(); result.pools = new Pool[](pools.length); for (uint256 i; i < pools.length; i++) { FancyStakingPool poolContract = FancyStakingPool(address(pools[i].poolContract)); result.pools[i] = Pool({ poolAddress: address(pools[i].poolContract), totalPoolShares: poolContract.totalSupply(), depositToken: address(poolContract.depositToken()), accountPendingRewards: poolContract.withdrawableRewardsOf(_account), accountClaimedRewards: poolContract.withdrawnRewardsOf(_account), accountTotalDeposit: poolContract.getTotalDeposit(_account), accountPoolShares: poolContract.balanceOf(_account), weight: pools[i].weight, deposits: new Deposit[](poolContract.getDepositsOfLength(_account)) }); FancyStakingPool.Deposit[] memory deposits = poolContract.getDepositsOf(_account); for (uint256 j; j < result.pools[i].deposits.length; j++) { FancyStakingPool.Deposit memory deposit = deposits[j]; result.pools[i].deposits[j] = Deposit({ amount: deposit.amount, start: deposit.start, end: deposit.end, multiplier: poolContract.getMultiplier(deposit.end - deposit.start) }); } } result.escrowPool = EscrowPool({ poolAddress: address(escrowPool), totalPoolShares: escrowPool.totalSupply(), accountTotalDeposit: escrowPool.getTotalDeposit(_account), accountPoolShares: escrowPool.balanceOf(_account), deposits: new FancyEscrowPool.Deposit[](escrowPool.getDepositsOfLength(_account)) }); FancyEscrowPool.Deposit[] memory deposits = escrowPool.getDepositsOf(_account); for (uint256 j; j < result.escrowPool.deposits.length; j++) { FancyEscrowPool.Deposit memory deposit = deposits[j]; result.escrowPool.deposits[j] = FancyEscrowPool.Deposit({ amount: deposit.amount, start: deposit.start, end: deposit.end }); } } }
contract View { struct Data { uint256 pendingRewards; Pool[] pools; EscrowPool escrowPool; uint256 totalWeight; } struct Deposit { uint256 amount; uint64 start; uint64 end; uint256 multiplier; } struct Pool { address poolAddress; uint256 totalPoolShares; address depositToken; uint256 accountPendingRewards; uint256 accountClaimedRewards; uint256 accountTotalDeposit; uint256 accountPoolShares; uint256 weight; Deposit[] deposits; } struct EscrowPool { address poolAddress; uint256 totalPoolShares; uint256 accountTotalDeposit; uint256 accountPoolShares; FancyEscrowPool.Deposit[] deposits; } LiquidityMiningManager public immutable liquidityMiningManager; FancyEscrowPool public immutable escrowPool; constructor(address _liquidityMiningManager, address _escrowPool) { liquidityMiningManager = LiquidityMiningManager(_liquidityMiningManager); escrowPool = FancyEscrowPool(_escrowPool); } function fetchData(address _account) external view returns (Data memory result) { // uint256 rewardPerSecond = liquidityMiningManager.rewardPerSecond(); // uint256 lastDistribution = liquidityMiningManager.lastDistribution(); // uint256 pendingRewards = rewardPerSecond * (block.timestamp - lastDistribution); result.totalWeight = liquidityMiningManager.totalWeight(); LiquidityMiningManager.Pool[] memory pools = liquidityMiningManager.getPools(); result.pools = new Pool[](pools.length); for (uint256 i; i < pools.length; i++) { FancyStakingPool poolContract = FancyStakingPool(address(pools[i].poolContract)); result.pools[i] = Pool({ poolAddress: address(pools[i].poolContract), totalPoolShares: poolContract.totalSupply(), depositToken: address(poolContract.depositToken()), accountPendingRewards: poolContract.withdrawableRewardsOf(_account), accountClaimedRewards: poolContract.withdrawnRewardsOf(_account), accountTotalDeposit: poolContract.getTotalDeposit(_account), accountPoolShares: poolContract.balanceOf(_account), weight: pools[i].weight, deposits: new Deposit[](poolContract.getDepositsOfLength(_account)) }); FancyStakingPool.Deposit[] memory deposits = poolContract.getDepositsOf(_account); for (uint256 j; j < result.pools[i].deposits.length; j++) { FancyStakingPool.Deposit memory deposit = deposits[j]; result.pools[i].deposits[j] = Deposit({ amount: deposit.amount, start: deposit.start, end: deposit.end, multiplier: poolContract.getMultiplier(deposit.end - deposit.start) }); } } result.escrowPool = EscrowPool({ poolAddress: address(escrowPool), totalPoolShares: escrowPool.totalSupply(), accountTotalDeposit: escrowPool.getTotalDeposit(_account), accountPoolShares: escrowPool.balanceOf(_account), deposits: new FancyEscrowPool.Deposit[](escrowPool.getDepositsOfLength(_account)) }); FancyEscrowPool.Deposit[] memory deposits = escrowPool.getDepositsOf(_account); for (uint256 j; j < result.escrowPool.deposits.length; j++) { FancyEscrowPool.Deposit memory deposit = deposits[j]; result.escrowPool.deposits[j] = FancyEscrowPool.Deposit({ amount: deposit.amount, start: deposit.start, end: deposit.end }); } } }
19,412
62
// Notifies a new guardian was unregistered
function guardianUnregistered(address guardian) external /* onlyGuardiansRegistrationContract */;
function guardianUnregistered(address guardian) external /* onlyGuardiansRegistrationContract */;
2,502
81
// Returns the storage slot that the proxiable contract assumes is being used to store the implementationaddress. IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risksbricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that thisfunction revert if invoked through a proxy. /
function proxiableUUID() external view returns (bytes32);
function proxiableUUID() external view returns (bytes32);
12,389
427
// If the underlying token matches this predefined 'ETH token' then we create weth for the user and go from there
if (address(_underlying) == _ETH_CONSTANT) {
if (address(_underlying) == _ETH_CONSTANT) {
32,976
17
// exit number used for tradeable exits
uint256 currExitNum = exitNum;
uint256 currExitNum = exitNum;
28,010
16
// create a Bug
bugs[bugId] = Bug({ hunter: bugCommitMap[bugId].hunter, bountyId: bugCommitMap[bugId].bountyId, bugDescription: bugDescription, numTokens: bugCommitMap[bugId].numTokens, pollId: pollId });
bugs[bugId] = Bug({ hunter: bugCommitMap[bugId].hunter, bountyId: bugCommitMap[bugId].bountyId, bugDescription: bugDescription, numTokens: bugCommitMap[bugId].numTokens, pollId: pollId });
25,883
32
// Access for minting new tokens.
mapping(address => bool) private mintAccess;
mapping(address => bool) private mintAccess;
18,014
11
// Commits any new funds to the current presale version, subtracting a donationDonation is applied here to disincentivise waiting until the last minute
if (msg.value > 0) { uint256 donation = msg.value.basis(finalDonation); uint256 amt = msg.value.sub(donation); p.balance = p.balance.add(amt); donatedBalance = donatedBalance.add(donation); committedBalance = committedBalance.add(amt); }
if (msg.value > 0) { uint256 donation = msg.value.basis(finalDonation); uint256 amt = msg.value.sub(donation); p.balance = p.balance.add(amt); donatedBalance = donatedBalance.add(donation); committedBalance = committedBalance.add(amt); }
29,961
116
// return total value locked of the token /
function getTvl(address tokenAddress) external view override returns (uint256) { return _totalLending[tokenAddress]; }
function getTvl(address tokenAddress) external view override returns (uint256) { return _totalLending[tokenAddress]; }
27,006
11
// set default values to tokens
_setDefaultTokenValues(token);
_setDefaultTokenValues(token);
21,691
35
// remove user
delete userInfo[pid][msg.sender];
delete userInfo[pid][msg.sender];
39,872
50
// 17 IN DATA / SET DATA / GET DATA / STRING / PUBLIC / ONLY OWNER / CONSTANT
string inCCH_edit_17 = " une première phrase " ;
string inCCH_edit_17 = " une première phrase " ;
55,991
10
// convert address to string
function toAsciiString(address x) internal pure returns (string memory) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2*i] = char(hi); s[2*i+1] = char(lo); } return string(s); }
function toAsciiString(address x) internal pure returns (string memory) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2*i] = char(hi); s[2*i+1] = char(lo); } return string(s); }
2,469
174
// no change in global balances.emit event.
ExcerciseOption( msg.sender, holderTicketAddress, ticketsExcercised, (bytes32(_assetTokenAddress) ^ bytes32(_strikeTokenAddress)) ); return ticketsExcercised;
ExcerciseOption( msg.sender, holderTicketAddress, ticketsExcercised, (bytes32(_assetTokenAddress) ^ bytes32(_strikeTokenAddress)) ); return ticketsExcercised;
3,539
370
// To the extent possible, modify state variables before calling functions
_mintPoolShare(initialSupply); _pushPoolShare(msg.sender, initialSupply);
_mintPoolShare(initialSupply); _pushPoolShare(msg.sender, initialSupply);
23,463
31
// Transfer reward tokens to user
STAKE_TOKEN.approve(address(this), rewardTokens); require(STAKE_TOKEN.transferFrom(address(this), msg.sender, rewardTokens)); emit WithdrawWinnings(msg.sender, _id, rewardTokens);
STAKE_TOKEN.approve(address(this), rewardTokens); require(STAKE_TOKEN.transferFrom(address(this), msg.sender, rewardTokens)); emit WithdrawWinnings(msg.sender, _id, rewardTokens);
25,008
20
// Returns true if the address is FlashBorrower, false otherwise borrower The address to checkreturn True if the given address is FlashBorrower, false otherwise /
function isFlashBorrower(address borrower) external view returns (bool);
function isFlashBorrower(address borrower) external view returns (bool);
19,881
19
// update struct
tranche.currentCoins = tranche.currentCoins.minus(currentWithdrawal); tranche.lastWithdrawalTime = block.timestamp;
tranche.currentCoins = tranche.currentCoins.minus(currentWithdrawal); tranche.lastWithdrawalTime = block.timestamp;
19,606
432
// Constructs the ExpandedERC20. _tokenName The name which describes the new token. _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. _tokenDecimals The number of decimals to define token precision. /
constructor( string memory _tokenName, string memory _tokenSymbol, uint8 _tokenDecimals
constructor( string memory _tokenName, string memory _tokenSymbol, uint8 _tokenDecimals
21,428
31
// set a new owner.
function changeOwner(address _newFundDeposit) isOwner() external { if (_newFundDeposit == address(0x0)) throw; ethFundDeposit = _newFundDeposit; }
function changeOwner(address _newFundDeposit) isOwner() external { if (_newFundDeposit == address(0x0)) throw; ethFundDeposit = _newFundDeposit; }
11,397
372
// Half of gained want (10% of rewards) are auto-compounded, half of gained want is taken as a performance fee
uint256 autoCompoundedPerformanceFee = wantGained.mul(autoCompoundingPerformanceFeeGovernance).div(MAX_FEE); IERC20Upgradeable(want).transfer(IController(controller).rewards(), autoCompoundedPerformanceFee); emit PerformanceFeeGovernance(IController(controller).rewards(), want, autoCompoundedPerformanceFee, block.number, block.timestamp);
uint256 autoCompoundedPerformanceFee = wantGained.mul(autoCompoundingPerformanceFeeGovernance).div(MAX_FEE); IERC20Upgradeable(want).transfer(IController(controller).rewards(), autoCompoundedPerformanceFee); emit PerformanceFeeGovernance(IController(controller).rewards(), want, autoCompoundedPerformanceFee, block.number, block.timestamp);
76,120
114
// in some cases, the reward token is the same as one of the components only swap when this is NOT the case
IUniswapV2Router02(routerV2).swapExactTokensForTokens( remainingRewardBalance/2, amountOutMin, uniswapRoutes[address(uniLPComponentToken0)], address(this), block.timestamp ); token0Amount = IERC20(uniLPComponentToken0).balanceOf(address(this));
IUniswapV2Router02(routerV2).swapExactTokensForTokens( remainingRewardBalance/2, amountOutMin, uniswapRoutes[address(uniLPComponentToken0)], address(this), block.timestamp ); token0Amount = IERC20(uniLPComponentToken0).balanceOf(address(this));
38,892
7
// Modify length
assembly { mstore(_markets, i) }
assembly { mstore(_markets, i) }
38,873
315
// Jackpot holding contract. This accepts token payouts from a game for every player loss, and on a win, pays out half of the jackpot to the winner. Jackpot payout should only be called from the game./
contract JackpotHolding is ERC223Receiving { /**************************** * FIELDS ****************************/ // How many times we've paid out the jackpot uint public payOutNumber = 0; // The amount to divide the token balance by for a pay out (defaults to half the token balance) uint public payOutDivisor = 2; // Holds the bankroll controller info ZethrBankrollControllerInterface controller; // Zethr contract Zethr zethr; /**************************** * CONSTRUCTOR ****************************/ constructor (address _controllerAddress, address _zethrAddress) public { controller = ZethrBankrollControllerInterface(_controllerAddress); zethr = Zethr(_zethrAddress); } function() public payable {} function tokenFallback(address /*_from*/, uint /*_amountOfTokens*/, bytes/*_data*/) public returns (bool) { // Do nothing, we can track the jackpot by this balance } /**************************** * VIEWS ****************************/ function getJackpotBalance() public view returns (uint) { // Half of this balance + half of jackpotBalance in each token bankroll uint tempBalance; for (uint i=0; i<7; i++) { tempBalance += controller.tokenBankrolls(i).jackpotBalance() > 0 ? controller.tokenBankrolls(i).jackpotBalance() / payOutDivisor : 0; } tempBalance += zethr.balanceOf(address(this)) > 0 ? zethr.balanceOf(address(this)) / payOutDivisor : 0; return tempBalance; } /**************************** * OWNER FUNCTIONS ****************************/ /** @dev Sets the pay out divisor * @param _divisor The value to set the new divisor to */ function ownerSetPayOutDivisor(uint _divisor) public ownerOnly { require(_divisor != 0); payOutDivisor = _divisor; } /** @dev Sets the address of the game controller * @param _controllerAddress The new address of the controller */ function ownerSetControllerAddress(address _controllerAddress) public ownerOnly { controller = ZethrBankrollControllerInterface(_controllerAddress); } /** @dev Transfers the jackpot to _to * @param _to Address to send the jackpot tokens to */ function ownerWithdrawZth(address _to) public ownerOnly { uint balance = zethr.balanceOf(address(this)); zethr.transfer(_to, balance); } /** @dev Transfers any ETH received from dividends to _to * @param _to Address to send the ETH to */ function ownerWithdrawEth(address _to) public ownerOnly { _to.transfer(address(this).balance); } /**************************** * GAME FUNCTIONS ****************************/ function gamePayOutWinner(address _winner) public gameOnly { // Call the payout function on all 7 token bankrolls for (uint i=0; i<7; i++) { controller.tokenBankrolls(i).payJackpotToWinner(_winner, payOutDivisor); } uint payOutAmount; // Calculate pay out & pay out if (zethr.balanceOf(address(this)) >= 1e10) { payOutAmount = zethr.balanceOf(address(this)) / payOutDivisor; } if (payOutAmount >= 1e10) { zethr.transfer(_winner, payOutAmount); } // Increment the statistics fields payOutNumber += 1; // Emit jackpot event emit JackpotPayOut(_winner, payOutNumber); } /**************************** * EVENTS ****************************/ event JackpotPayOut( address winner, uint payOutNumber ); /**************************** * MODIFIERS ****************************/ // Only an owner can call this method (controller is always an owner) modifier ownerOnly() { require(msg.sender == address(controller) || controller.multiSigWallet().isOwner(msg.sender)); _; } // Only a game can call this method modifier gameOnly() { require(controller.validGameAddresses(msg.sender)); _; } }
contract JackpotHolding is ERC223Receiving { /**************************** * FIELDS ****************************/ // How many times we've paid out the jackpot uint public payOutNumber = 0; // The amount to divide the token balance by for a pay out (defaults to half the token balance) uint public payOutDivisor = 2; // Holds the bankroll controller info ZethrBankrollControllerInterface controller; // Zethr contract Zethr zethr; /**************************** * CONSTRUCTOR ****************************/ constructor (address _controllerAddress, address _zethrAddress) public { controller = ZethrBankrollControllerInterface(_controllerAddress); zethr = Zethr(_zethrAddress); } function() public payable {} function tokenFallback(address /*_from*/, uint /*_amountOfTokens*/, bytes/*_data*/) public returns (bool) { // Do nothing, we can track the jackpot by this balance } /**************************** * VIEWS ****************************/ function getJackpotBalance() public view returns (uint) { // Half of this balance + half of jackpotBalance in each token bankroll uint tempBalance; for (uint i=0; i<7; i++) { tempBalance += controller.tokenBankrolls(i).jackpotBalance() > 0 ? controller.tokenBankrolls(i).jackpotBalance() / payOutDivisor : 0; } tempBalance += zethr.balanceOf(address(this)) > 0 ? zethr.balanceOf(address(this)) / payOutDivisor : 0; return tempBalance; } /**************************** * OWNER FUNCTIONS ****************************/ /** @dev Sets the pay out divisor * @param _divisor The value to set the new divisor to */ function ownerSetPayOutDivisor(uint _divisor) public ownerOnly { require(_divisor != 0); payOutDivisor = _divisor; } /** @dev Sets the address of the game controller * @param _controllerAddress The new address of the controller */ function ownerSetControllerAddress(address _controllerAddress) public ownerOnly { controller = ZethrBankrollControllerInterface(_controllerAddress); } /** @dev Transfers the jackpot to _to * @param _to Address to send the jackpot tokens to */ function ownerWithdrawZth(address _to) public ownerOnly { uint balance = zethr.balanceOf(address(this)); zethr.transfer(_to, balance); } /** @dev Transfers any ETH received from dividends to _to * @param _to Address to send the ETH to */ function ownerWithdrawEth(address _to) public ownerOnly { _to.transfer(address(this).balance); } /**************************** * GAME FUNCTIONS ****************************/ function gamePayOutWinner(address _winner) public gameOnly { // Call the payout function on all 7 token bankrolls for (uint i=0; i<7; i++) { controller.tokenBankrolls(i).payJackpotToWinner(_winner, payOutDivisor); } uint payOutAmount; // Calculate pay out & pay out if (zethr.balanceOf(address(this)) >= 1e10) { payOutAmount = zethr.balanceOf(address(this)) / payOutDivisor; } if (payOutAmount >= 1e10) { zethr.transfer(_winner, payOutAmount); } // Increment the statistics fields payOutNumber += 1; // Emit jackpot event emit JackpotPayOut(_winner, payOutNumber); } /**************************** * EVENTS ****************************/ event JackpotPayOut( address winner, uint payOutNumber ); /**************************** * MODIFIERS ****************************/ // Only an owner can call this method (controller is always an owner) modifier ownerOnly() { require(msg.sender == address(controller) || controller.multiSigWallet().isOwner(msg.sender)); _; } // Only a game can call this method modifier gameOnly() { require(controller.validGameAddresses(msg.sender)); _; } }
33,270
75
// instantiate new epoch
currentEpoch = EpochRewards({ rewardsAvailable: 0, rewardsClaimed: 0, rewardPerToken: 0 });
currentEpoch = EpochRewards({ rewardsAvailable: 0, rewardsClaimed: 0, rewardPerToken: 0 });
3,742
97
// Emitted when Global Distribution speed for both supply and borrow are updated
event GlobalDistributionSpeedsUpdated( uint256 borrowSpeed, uint256 supplySpeed );
event GlobalDistributionSpeedsUpdated( uint256 borrowSpeed, uint256 supplySpeed );
40,482
2
// Factory Contracts
function getAddress(uint _index) external view returns (address) { return contracts[_index]; }
function getAddress(uint _index) external view returns (address) { return contracts[_index]; }
14,983
270
// update values in snapshot if in the same block
if (currentBlock == latestSnapshot.blockNumber) { latestSnapshot.quoteAssetReserve = quoteAssetReserve; latestSnapshot.baseAssetReserve = baseAssetReserve; } else {
if (currentBlock == latestSnapshot.blockNumber) { latestSnapshot.quoteAssetReserve = quoteAssetReserve; latestSnapshot.baseAssetReserve = baseAssetReserve; } else {
34,296
47
// Return InstaDApp Mapping Addresses /
function getMappingAddr() internal pure returns (address) { return 0xe81F70Cc7C0D46e12d70efc60607F16bbD617E88; // InstaMapping Address }
function getMappingAddr() internal pure returns (address) { return 0xe81F70Cc7C0D46e12d70efc60607F16bbD617E88; // InstaMapping Address }
53,687
7
// Phase 2
phases[2] = Phase({ minPurchase: 2_000 * 10 ** 18, // 2000 token for test
phases[2] = Phase({ minPurchase: 2_000 * 10 ** 18, // 2000 token for test
40,515
13
// Check Liquidator Allowance
require( IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= debtTotal, Errors.VL_MISSING_ERC20_ALLOWANCE );
require( IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= debtTotal, Errors.VL_MISSING_ERC20_ALLOWANCE );
52,502
91
// Update strategy loss. _strategy Strategy which incur loss _loss Loss of strategy /
function reportLoss(address _strategy, uint256 _loss) external onlyPool { require(strategy[_strategy].active, Errors.STRATEGY_IS_NOT_ACTIVE); _reportLoss(_strategy, _loss); }
function reportLoss(address _strategy, uint256 _loss) external onlyPool { require(strategy[_strategy].active, Errors.STRATEGY_IS_NOT_ACTIVE); _reportLoss(_strategy, _loss); }
75,427
32
// Set the fee wallet _protocolFeeWallet address Wallet to transfer fee to /
function setProtocolFeeWallet(address _protocolFeeWallet) external onlyOwner { // Ensure the new fee wallet is not null require(_protocolFeeWallet != address(0), "INVALID_FEE_WALLET"); protocolFeeWallet = _protocolFeeWallet; emit SetProtocolFeeWallet(_protocolFeeWallet); }
function setProtocolFeeWallet(address _protocolFeeWallet) external onlyOwner { // Ensure the new fee wallet is not null require(_protocolFeeWallet != address(0), "INVALID_FEE_WALLET"); protocolFeeWallet = _protocolFeeWallet; emit SetProtocolFeeWallet(_protocolFeeWallet); }
25,455
60
// See {IERC20-approve}. Requirements: - `spender` cannot be the zero address. /
function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; }
function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; }
12,169
350
// mapping token ID to hashed keys id
mapping(uint256 => uint256) _keyIds;
mapping(uint256 => uint256) _keyIds;
31,173
9
// 构造函数 -- 指定调用合约的地址
constructor(address _adminContractAddr) public{ adminContractAddr = _adminContractAddr; adminContract = AdminContract(adminContractAddr); // 通过地址拿到合约实例 -- 将地址强制转换为合约 }
constructor(address _adminContractAddr) public{ adminContractAddr = _adminContractAddr; adminContract = AdminContract(adminContractAddr); // 通过地址拿到合约实例 -- 将地址强制转换为合约 }
23,372
225
// Redeem tokens from a default partitions. operator The address performing the redeem. from Token holder. value Number of tokens to redeem. data Information attached to the redemption. /
function _redeemByDefaultPartitions( address operator, address from, uint256 value, bytes memory data ) internal
function _redeemByDefaultPartitions( address operator, address from, uint256 value, bytes memory data ) internal
28,344
192
// unregister the caller's schemereturn bool which represents a success /
function unregisterSelf(address _avatar) external isAvatarValid(_avatar) returns(bool) { if (_isSchemeRegistered(msg.sender) == false) { return false; } delete schemes[msg.sender]; emit UnregisterScheme(msg.sender, msg.sender); return true; }
function unregisterSelf(address _avatar) external isAvatarValid(_avatar) returns(bool) { if (_isSchemeRegistered(msg.sender) == false) { return false; } delete schemes[msg.sender]; emit UnregisterScheme(msg.sender, msg.sender); return true; }
30,201
38
// booking lpFee
totalLiquidity = totalLiquidity.add(_s.lpFee);
totalLiquidity = totalLiquidity.add(_s.lpFee);
17,733
194
// safe math not needed hereapr is scaled by 1e18 so we downscale here
uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).mul(maxReportDelay).div(SECONDSPERYEAR); uint256 wantCallCost = _callCostToWant(callCost); return (wantCallCost.mul(profitFactor) < profitIncrease);
uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).mul(maxReportDelay).div(SECONDSPERYEAR); uint256 wantCallCost = _callCostToWant(callCost); return (wantCallCost.mul(profitFactor) < profitIncrease);
24,152
24
// Safe xpolar transfer function, just in case if rounding error causes pool to not have enough xpolars.
function safeXpolarTransfer(address _to, uint256 _amount) internal { uint256 _xpolarBal = xpolar.balanceOf(address(this)); if (_xpolarBal > 0) { if (_amount > _xpolarBal) { xpolar.safeTransfer(_to, _xpolarBal); } else { xpolar.safeTransfer(_to, _amount); } } }
function safeXpolarTransfer(address _to, uint256 _amount) internal { uint256 _xpolarBal = xpolar.balanceOf(address(this)); if (_xpolarBal > 0) { if (_amount > _xpolarBal) { xpolar.safeTransfer(_to, _xpolarBal); } else { xpolar.safeTransfer(_to, _amount); } } }
35,017
30
// Standard ERC20 token/
contract StandardToken is ERC20, BasicToken { uint public constant MAX_UINT = 2**256 - 1; mapping (address => mapping (address => uint256)) internal allowed; /** */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { if (_to == address(0)) { totalSupply_ = totalSupply_.sub(_value); } require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); /// an allowance of MAX_UINT represents an unlimited allowance. /// @dev see https://github.com/ethereum/EIPs/issues/717 if (allowed[_from][msg.sender] < MAX_UINT) { allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); } emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
contract StandardToken is ERC20, BasicToken { uint public constant MAX_UINT = 2**256 - 1; mapping (address => mapping (address => uint256)) internal allowed; /** */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { if (_to == address(0)) { totalSupply_ = totalSupply_.sub(_value); } require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); /// an allowance of MAX_UINT represents an unlimited allowance. /// @dev see https://github.com/ethereum/EIPs/issues/717 if (allowed[_from][msg.sender] < MAX_UINT) { allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); } emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
38,042
11
// Validate input.
require(existingAmounts.length == existingHolders.length); require(inflationCapPeriod_ != 0);
require(existingAmounts.length == existingHolders.length); require(inflationCapPeriod_ != 0);
9,947
34
// Returns true if rewards are actively being accumulated /
function rewardsActive() public view returns (bool) { return block.number >= startBlock && block.number <= endBlock && totalAllocPoint > 0 ? true : false; }
function rewardsActive() public view returns (bool) { return block.number >= startBlock && block.number <= endBlock && totalAllocPoint > 0 ? true : false; }
10,174
20
// determine the amountOut based on which token has a lower address
return uint256(-(zeroForOne ? amount1 : amount0));
return uint256(-(zeroForOne ? amount1 : amount0));
32,221
113
// Iterate over each owner and token ID
for (uint256 i = 0; i < _owners.length; i++) { batchBalances[i] = balances[_owners[i]][_ids[i]]; }
for (uint256 i = 0; i < _owners.length; i++) { batchBalances[i] = balances[_owners[i]][_ids[i]]; }
14,791
9
// Putting in for now to replicate the compound-like token function where I can find balance at a certain block.
function balanceOfAt(address account, uint256 blockNo) external view returns (uint256);
function balanceOfAt(address account, uint256 blockNo) external view returns (uint256);
27,424
41
// Transfer tokens from one address to another.Note that while this function emits an Approval event, this is not required as per the specification,and other compliant implementations may not emit the event. 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) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
27,111
61
// `balances` is the map that tracks the balance of each address, in thiscontract when the balance changes the block number that the changeoccurred is also included in the map
mapping (address => Checkpoint[]) balances;
mapping (address => Checkpoint[]) balances;
31,600
52
// addInvestorBonusInTokens is used for sending bonuses for big investors in tokens
function addInvestorBonusInTokens(address _to, uint tokens) public onlyOwner { _freezeTransfer(_to, tokens); investorGiven = investorGiven.add(tokens); require(investorGiven <= investorSupply); }
function addInvestorBonusInTokens(address _to, uint tokens) public onlyOwner { _freezeTransfer(_to, tokens); investorGiven = investorGiven.add(tokens); require(investorGiven <= investorSupply); }
5,134
51
// flase抛异常,并扣除gas消耗
assert(transferEnabled); if(plockFlag){ assert(!locked[_addr]); }
assert(transferEnabled); if(plockFlag){ assert(!locked[_addr]); }
50,203
122
// Token Lock must have a sufficient allowance prior to creating locks
require(_tokens.add(totalTokensLocked) <= token.allowance(allowanceProvider, address(this))); TokenLockVault storage lock = tokenLocks[_beneficiary];
require(_tokens.add(totalTokensLocked) <= token.allowance(allowanceProvider, address(this))); TokenLockVault storage lock = tokenLocks[_beneficiary];
32,896
211
// resume contractThis will mark contract as resumed/
function resume() onlyOwner public { // mark the flag to indicate resume of the contract isPaused = false; }
function resume() onlyOwner public { // mark the flag to indicate resume of the contract isPaused = false; }
21,287
94
// Update storage balance of previous bin
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
13,173
3
// Minimum bid as a fraction of the pot
uint public constant MIN_BID_FRAC_TOP = 1; uint public constant MIN_BID_FRAC_BOT = 1000;
uint public constant MIN_BID_FRAC_TOP = 1; uint public constant MIN_BID_FRAC_BOT = 1000;
6,973
4
// No tenemos suficientes fondos para pagar el premio, así que transferimos todo lo que tenemos
msg.sender.transfer(address(this).balance); emit Status('Congratulations, you win! Sorry, we didn\'t have enought money, we will deposit everything we have!', msg.sender, msg.value, true); newGame = Game({ addr: msg.sender, blocknumber: block.number, blocktimestamp: block.timestamp, bet: msg.value, prize: address(this).balance, winner: true
msg.sender.transfer(address(this).balance); emit Status('Congratulations, you win! Sorry, we didn\'t have enought money, we will deposit everything we have!', msg.sender, msg.value, true); newGame = Game({ addr: msg.sender, blocknumber: block.number, blocktimestamp: block.timestamp, bet: msg.value, prize: address(this).balance, winner: true
15,016
180
// If there are tokens remaining, process investment
if (mintedPerTierTotal[i] < tokensPerTierTotal[i]) spentUSD = spentUSD.add(_calculateTier(_beneficiary, i, investedUSD.sub(spentUSD), _fundRaiseType));
if (mintedPerTierTotal[i] < tokensPerTierTotal[i]) spentUSD = spentUSD.add(_calculateTier(_beneficiary, i, investedUSD.sub(spentUSD), _fundRaiseType));
5,260
114
// Make sure we can actually create a reward with that amount. This balance of the reward token at this proxy address should never decrease except when rewards are claimed by holders.
uint256 reservedRewardBalance = _reservedRewardBalance; uint256 currentBalance = IERC20(_rewardToken).balanceOf(address(this)); require(currentBalance >= reservedRewardBalance, "Current reserve insufficient"); uint256 reserveIncrease = IGoaldToken(_goaldToken).totalSupply() * multiplier; require(reserveIncrease <= (currentBalance - reservedRewardBalance), "Multiplier too large");
uint256 reservedRewardBalance = _reservedRewardBalance; uint256 currentBalance = IERC20(_rewardToken).balanceOf(address(this)); require(currentBalance >= reservedRewardBalance, "Current reserve insufficient"); uint256 reserveIncrease = IGoaldToken(_goaldToken).totalSupply() * multiplier; require(reserveIncrease <= (currentBalance - reservedRewardBalance), "Multiplier too large");
7,445
0
// address of the contract that will burn req token (through Kyber)
address public requestBurnerContract;
address public requestBurnerContract;
6,647
130
// By default, the liquidator is allowed to purchase at least to `defaultAllowedAmount` if `liquidateAmountRequired` is less than `defaultAllowedAmount`.
int256 defaultAllowedAmount = maxTotalBalance.mul(Constants.DEFAULT_LIQUIDATION_PORTION).div( Constants.PERCENTAGE_DECIMALS ); int256 result = liquidateAmountRequired;
int256 defaultAllowedAmount = maxTotalBalance.mul(Constants.DEFAULT_LIQUIDATION_PORTION).div( Constants.PERCENTAGE_DECIMALS ); int256 result = liquidateAmountRequired;
37,606
252
// ValidateSPV/
library ValidateSPV { using BTCUtils for bytes; using BTCUtils for uint256; using BytesLib for bytes; using SafeMath for uint256; enum InputTypes { NONE, LEGACY, COMPATIBILITY, WITNESS } enum OutputTypes { NONE, WPKH, WSH, OP_RETURN, PKH, SH, NONSTANDARD } uint256 constant ERR_BAD_LENGTH = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint256 constant ERR_INVALID_CHAIN = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe; uint256 constant ERR_LOW_WORK = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd; function getErrBadLength() internal pure returns (uint256) { return ERR_BAD_LENGTH; }
library ValidateSPV { using BTCUtils for bytes; using BTCUtils for uint256; using BytesLib for bytes; using SafeMath for uint256; enum InputTypes { NONE, LEGACY, COMPATIBILITY, WITNESS } enum OutputTypes { NONE, WPKH, WSH, OP_RETURN, PKH, SH, NONSTANDARD } uint256 constant ERR_BAD_LENGTH = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint256 constant ERR_INVALID_CHAIN = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe; uint256 constant ERR_LOW_WORK = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd; function getErrBadLength() internal pure returns (uint256) { return ERR_BAD_LENGTH; }
24,636
31
// Returns the current nonce associated with a given address_signer Address to query signature nonce for/
function getNonce(address _signer) external view returns (uint256 nonce)
function getNonce(address _signer) external view returns (uint256 nonce)
13,713
6
// Returns the amount of tokens owned by `account`./
function balanceOf(address account) external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
3,155
72
// Performs a Solidity function call using a low level `call`. Aplain`call` is an unsafe replacement for a function call: use thisfunction instead. If `target` reverts with a revert reason, it is bubbled up by thisfunction (like regular Solidity function calls). Returns the raw returned data. To convert to the expected return value, Requirements: - `target` must be a contract.- calling `target` with `data` must not revert. _Available since v3.1._ / function functionCall(address target, bytes memory data) internal returns (bytes memory)
// { // return functionCall(target, data, "Address: low-level call failed"); // }
// { // return functionCall(target, data, "Address: low-level call failed"); // }
32,484
1
// max duration in secs available for match after approve, if expires - agreement should be closed
uint public matchLimit; uint public injectionThreshold; uint public minDuration; uint public maxDuration; uint public riskyMargin; uint public acapFee; // per second % address payable public acapAddr;
uint public matchLimit; uint public injectionThreshold; uint public minDuration; uint public maxDuration; uint public riskyMargin; uint public acapFee; // per second % address payable public acapAddr;
4,963
23
// Safely substract amount to be burned from callers allowance
_approve(Account, msg.sender, _allowance[Account][msg.sender].sub(_value,"ERC20: burn amount exceeds allowance"));
_approve(Account, msg.sender, _allowance[Account][msg.sender].sub(_value,"ERC20: burn amount exceeds allowance"));
44,978
20
// If the delegate did not vote yet, add to her weight.
delegate_.weight += sender.weight;
delegate_.weight += sender.weight;
22,772
9
// If the protocol fee is invalid, revert:Protocol fee must be greater than the buy referrer fee since referrer fees are deducted from the protocol fee.The protocol fee must leave room for the creator royalties and the max exhibition take rate. /
revert NFTMarketFees_Invalid_Protocol_Fee();
revert NFTMarketFees_Invalid_Protocol_Fee();
18,092
14
// Interface for contracts conforming to ERC-721: Deed Standard/William Entriken (https:phor.net), et. al./Specification at https:github.com/ethereum/eips/841/ can read the comments there
contract ERC721 { // COMPLIANCE WITH ERC-165 (DRAFT) /// @dev ERC-165 (draft) interface signature for itself bytes4 internal constant INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); /// @dev ERC-165 (draft) interface signature for ERC721 bytes4 internal constant INTERFACE_SIGNATURE_ERC721 = bytes4(keccak256("ownerOf(uint256)")) ^ bytes4(keccak256("countOfDeeds()")) ^ bytes4(keccak256("countOfDeedsByOwner(address)")) ^ bytes4(keccak256("deedOfOwnerByIndex(address,uint256)")) ^ bytes4(keccak256("approve(address,uint256)")) ^ bytes4(keccak256("takeOwnership(uint256)")); function supportsInterface(bytes4 _interfaceID) external pure returns (bool); // PUBLIC QUERY FUNCTIONS ////////////////////////////////////////////////// function ownerOf(uint256 _deedId) public view returns (address _owner); function countOfDeeds() external view returns (uint256 _count); function countOfDeedsByOwner(address _owner) external view returns (uint256 _count); function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _deedId); // TRANSFER MECHANISM ////////////////////////////////////////////////////// event Transfer(address indexed from, address indexed to, uint256 indexed deedId); event Approval(address indexed owner, address indexed approved, uint256 indexed deedId); function approve(address _to, uint256 _deedId) external payable; function takeOwnership(uint256 _deedId) external payable; }
contract ERC721 { // COMPLIANCE WITH ERC-165 (DRAFT) /// @dev ERC-165 (draft) interface signature for itself bytes4 internal constant INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); /// @dev ERC-165 (draft) interface signature for ERC721 bytes4 internal constant INTERFACE_SIGNATURE_ERC721 = bytes4(keccak256("ownerOf(uint256)")) ^ bytes4(keccak256("countOfDeeds()")) ^ bytes4(keccak256("countOfDeedsByOwner(address)")) ^ bytes4(keccak256("deedOfOwnerByIndex(address,uint256)")) ^ bytes4(keccak256("approve(address,uint256)")) ^ bytes4(keccak256("takeOwnership(uint256)")); function supportsInterface(bytes4 _interfaceID) external pure returns (bool); // PUBLIC QUERY FUNCTIONS ////////////////////////////////////////////////// function ownerOf(uint256 _deedId) public view returns (address _owner); function countOfDeeds() external view returns (uint256 _count); function countOfDeedsByOwner(address _owner) external view returns (uint256 _count); function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _deedId); // TRANSFER MECHANISM ////////////////////////////////////////////////////// event Transfer(address indexed from, address indexed to, uint256 indexed deedId); event Approval(address indexed owner, address indexed approved, uint256 indexed deedId); function approve(address _to, uint256 _deedId) external payable; function takeOwnership(uint256 _deedId) external payable; }
38,122
323
// Creates a new token for `to`. Its token ID will be automatically
* assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * See {ERC721-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have minter role to mint"); // We cannot just use balanceOf to create the new tokenId because tokens // can be burned (destroyed), so we need a separate counter. _mint(to, _tokenIdTracker.current()); _tokenIdTracker.increment(); }
* assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * See {ERC721-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have minter role to mint"); // We cannot just use balanceOf to create the new tokenId because tokens // can be burned (destroyed), so we need a separate counter. _mint(to, _tokenIdTracker.current()); _tokenIdTracker.increment(); }
4,482
4
// Read the counter's value.return The counter's current value. /
function read() public view returns (uint) { return _value; }
function read() public view returns (uint) { return _value; }
44,920
2
// The sandbox contract address.
ILiquidityProviderSandbox public immutable sandbox; constructor(LiquidityProviderSandbox sandbox_) public FixinCommon()
ILiquidityProviderSandbox public immutable sandbox; constructor(LiquidityProviderSandbox sandbox_) public FixinCommon()
17,109
47
// ========================================================================================= // Miscellaneous // ========================================================================================= // Returns token0 amount in token0Decimals /
function getToken0AmountInNativeDecimals( uint256 amount, uint8 token0Decimals, uint256 token0DecimalMultiplier
function getToken0AmountInNativeDecimals( uint256 amount, uint8 token0Decimals, uint256 token0DecimalMultiplier
32,015
233
// transfer ethers in this contract to fees collector contract _amount ethers amount to be transferred/
function withdrawEthToFeesCollector(uint256 _amount) external onlyAdmins { TransferETHHelper.safeTransferETH(feesCollectorAddress, _amount); }
function withdrawEthToFeesCollector(uint256 _amount) external onlyAdmins { TransferETHHelper.safeTransferETH(feesCollectorAddress, _amount); }
21,832
164
// Emitted when pendingWanttrollerImplementation is changed/
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
1,173
20
// totalProof: total substitute for staked token
uint totalProof;
uint totalProof;
32,546
64
// Reserve tokens amount
uint256 inputAmount,
uint256 inputAmount,
51,513
307
// Returns the current price for each token
function getCurrentPrice() public view returns (uint256) { require( block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started" ); require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); uint256 currentSupply = totalSupply(); if (currentSupply >= 16381) { return 33000000000000000000; // 16381 - 16383 33 ETH } else if (currentSupply >= 16000) { return 3000000000000000000; // 16000 - 16380 3.0 ETH } else if (currentSupply >= 15000) { return 1700000000000000000; // 15000 - 15999 1.7 ETH } else if (currentSupply >= 11000) { return 900000000000000000; // 11000 - 14999 0.9 ETH } else if (currentSupply >= 7000) { return 500000000000000000; // 7000 - 10999 0.5 ETH } else if (currentSupply >= 3000) { return 300000000000000000; // 3000 - 6999 0.3 ETH } else { return 100000000000000000; // 0 - 2999 0.1 ETH } }
function getCurrentPrice() public view returns (uint256) { require( block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started" ); require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); uint256 currentSupply = totalSupply(); if (currentSupply >= 16381) { return 33000000000000000000; // 16381 - 16383 33 ETH } else if (currentSupply >= 16000) { return 3000000000000000000; // 16000 - 16380 3.0 ETH } else if (currentSupply >= 15000) { return 1700000000000000000; // 15000 - 15999 1.7 ETH } else if (currentSupply >= 11000) { return 900000000000000000; // 11000 - 14999 0.9 ETH } else if (currentSupply >= 7000) { return 500000000000000000; // 7000 - 10999 0.5 ETH } else if (currentSupply >= 3000) { return 300000000000000000; // 3000 - 6999 0.3 ETH } else { return 100000000000000000; // 0 - 2999 0.1 ETH } }
17,858
368
// reduce underlying by redemption penalty
amount = amount - burnAmount.mul(amount).div(totalAmount); redeemToAccount(msg.sender, amount, couponAmount); if (burnAmount != 0) { emit CouponBurn(msg.sender, couponEpoch, burnAmount); }
amount = amount - burnAmount.mul(amount).div(totalAmount); redeemToAccount(msg.sender, amount, couponAmount); if (burnAmount != 0) { emit CouponBurn(msg.sender, couponEpoch, burnAmount); }
29,630
34
// Return all the tokens in the stakedToken Array for this user that are not -1
StakedToken[] memory _stakedTokens = new StakedToken[]( stakers[_user].amountStaked ); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; }
StakedToken[] memory _stakedTokens = new StakedToken[]( stakers[_user].amountStaked ); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; }
3,884
48
// The TDT holder gets any leftover balance.
owedToTdtHolder = balance.add(owedToDeposit).sub(signerFee).sub(owedToFrtHolder); return (owedToDeposit, owedToTdtHolder, owedToFrtHolder); return (0,0,0);
owedToTdtHolder = balance.add(owedToDeposit).sub(signerFee).sub(owedToFrtHolder); return (owedToDeposit, owedToTdtHolder, owedToFrtHolder); return (0,0,0);
51,476
16
// Withdraw from Masterchef contract
masterchef.withdraw(univ2SushiEthPoolId, amount);
masterchef.withdraw(univ2SushiEthPoolId, amount);
4,338
753
// First settle anything pending into sUSD as burning or issuing impacts the size of the debt pool
(, uint refunded, uint numEntriesSettled) = exchanger().settle(from, sUSD); if (numEntriesSettled > 0) { amount = exchanger().calculateAmountAfterSettlement(from, sUSD, amount, refunded); }
(, uint refunded, uint numEntriesSettled) = exchanger().settle(from, sUSD); if (numEntriesSettled > 0) { amount = exchanger().calculateAmountAfterSettlement(from, sUSD, amount, refunded); }
29,592
65
// Returns the multiplication of two unsigned integers, with an overflow flag. _Available since v3.4._ /
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } }
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } }
39,911
12
// See {IMarketplace-rentNFT}. /
function rentNFT( address nftContract, bytes32 listId, uint256 startDate, uint256 endDate ) public payable virtual override nonReentrant { Leasing storage leasing = _leasingMap[nftContract][listId]; uint256 price = leasing.price; uint256 tokenId = leasing.tokenId; require(
function rentNFT( address nftContract, bytes32 listId, uint256 startDate, uint256 endDate ) public payable virtual override nonReentrant { Leasing storage leasing = _leasingMap[nftContract][listId]; uint256 price = leasing.price; uint256 tokenId = leasing.tokenId; require(
4,358
28
// Token adapter for Pie pool tokens. Implementation of TokenAdapter abstract contract. Mick de Graaf <[email protected]> /
contract PieDAOExperiPieTokenAdapter is TokenAdapter { /** * @return TokenMetadata struct with ERC20-style token info. * @dev Implementation of TokenAdapter interface function. */ function getMetadata(address token) external view override returns (TokenMetadata memory) { return TokenMetadata({ token: token, name: ERC20(token).name(), symbol: ERC20(token).symbol(), decimals: ERC20(token).decimals() }); } /** * @return Array of Component structs with underlying tokens rates for the given asset. * @dev Implementation of TokenAdapter abstract contract function. */ function getComponents(address token) external view override returns (Component[] memory) { address[] memory tokens = ExperiPie(token).getTokens(); Component[] memory components = new Component[](tokens.length); for (uint256 i = 0; i < tokens.length; i++) { components[i] = Component({ token: tokens[i], tokenType: "ERC20", rate: (ExperiPie(token).balance(tokens[i]) * 1e18) / ERC20(token).totalSupply() }); } return components; } }
contract PieDAOExperiPieTokenAdapter is TokenAdapter { /** * @return TokenMetadata struct with ERC20-style token info. * @dev Implementation of TokenAdapter interface function. */ function getMetadata(address token) external view override returns (TokenMetadata memory) { return TokenMetadata({ token: token, name: ERC20(token).name(), symbol: ERC20(token).symbol(), decimals: ERC20(token).decimals() }); } /** * @return Array of Component structs with underlying tokens rates for the given asset. * @dev Implementation of TokenAdapter abstract contract function. */ function getComponents(address token) external view override returns (Component[] memory) { address[] memory tokens = ExperiPie(token).getTokens(); Component[] memory components = new Component[](tokens.length); for (uint256 i = 0; i < tokens.length; i++) { components[i] = Component({ token: tokens[i], tokenType: "ERC20", rate: (ExperiPie(token).balance(tokens[i]) * 1e18) / ERC20(token).totalSupply() }); } return components; } }
33,039
24
// Sets `amount` as the allowance of `spender` over the caller's tokens. Returns a boolean value indicating whether the operation succeeded. IMPORTANT: Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: Emits an {Approval} event./
function approve(address spender, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
21,008
46
// Cannot make delegatecall as a delegateproxy.delegatedFwd as it returns ending execution context and halts contract deployment
require(appCode.delegatecall(_initializePayload));
require(appCode.delegatecall(_initializePayload));
51,172
84
// requestRandomness initiates a request for VRF output given _seedSee "SECURITY CONSIDERATIONS" above for more information on _seed.The fulfillRandomness method receives the output, once it's provided by the Oracle, and verified by the vrfCoordinator.The _keyHash must already be registered with the VRFCoordinator, and the _fee must exceed the fee specified during registration of the _keyHash._keyHash ID of public key against which randomness is generated _fee The amount of VOR to send with the request _seed seed mixed into the input of the VRF return requestId unique ID for this requestThe returned requestId can be used to distinguish responses toconcurrent requests. It
function requestRandomness(bytes32 _keyHash, uint256 _fee, uint256 _seed) public returns (bytes32 requestId)
function requestRandomness(bytes32 _keyHash, uint256 _fee, uint256 _seed) public returns (bytes32 requestId)
20,740
8
// Library for managing types. Sets have the following properties: - Elements are added, removed, and checked for existence in constant time (O(1)). - Elements are enumerated in O(n). No guarantees are made on the ordering. ```
* contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * }
* contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * }
4,448
406
// liquidationIncentiveMantissa must be no greater than this value
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
16,340
168
// Returns an originating chain id of the currently processed message. return source chain id of the message that originated on the other side./
function messageSourceChainId() external view returns (uint256 id) { assembly { // Even though this is not the same as uintStorage[keccak256(abi.encodePacked("messageSourceChainId"))], // since solidity mapping introduces another level of addressing, such slot change is safe // for temporary variables which are cleared at the end of the call execution. id := sload(0x7f0fcd9e49860f055dd0c1682d635d309ecb5e3011654c716d9eb59a7ddec7d2) // keccak256(abi.encodePacked("messageSourceChainId")) } }
function messageSourceChainId() external view returns (uint256 id) { assembly { // Even though this is not the same as uintStorage[keccak256(abi.encodePacked("messageSourceChainId"))], // since solidity mapping introduces another level of addressing, such slot change is safe // for temporary variables which are cleared at the end of the call execution. id := sload(0x7f0fcd9e49860f055dd0c1682d635d309ecb5e3011654c716d9eb59a7ddec7d2) // keccak256(abi.encodePacked("messageSourceChainId")) } }
18,685
10
// vesting
address public immutable vestingAddress; uint256 private immutable _vestingSupply;
address public immutable vestingAddress; uint256 private immutable _vestingSupply;
1,139
86
// ERC20WithBlacklist /
contract ERC20WithBlacklist is Ownable, ERC20 { address[] private _blacklist; mapping(address => bool) private _blacklistMap; event AddedToBlacklist(address addr); event RemovedFromBlacklist(address addr); /** * @dev Throws if addr is blacklisted. */ modifier notBlacklisted(address addr) { require(!_blacklistMap[addr], "addr is blacklisted"); _; } /** * @param addr The address to check if blacklisted * @return true if addr is blacklisted, false otherwise */ function isBlacklisted(address addr) public view returns (bool) { return _blacklistMap[addr]; } /** * @dev Function to add an address to the blacklist * @param addr The address to add to the blacklist * @return A boolean that indicates if the operation was successful. */ function addToBlacklist(address addr) public onlyOwner returns (bool) { require(!_blacklistMap[addr], "addr is already blacklisted"); _blacklistMap[addr] = true; _blacklist.push(addr); emit AddedToBlacklist(addr); return true; } /** * @dev Function to remove an address from the blacklist * @param addr The address to remove from the blacklist * @return A boolean that indicates if the operation was successful. */ function removeFromBlacklist(address addr) public onlyOwner returns (bool) { require(_blacklistMap[addr], "addr is not blacklisted"); _blacklistMap[addr] = false; for (uint256 i = 0; i < _blacklist.length; i++) { if (_blacklist[i] == addr) { _blacklist[i] = _blacklist[_blacklist.length - 1]; _blacklist.pop(); break; } } emit RemovedFromBlacklist(addr); return true; } /** * @return Length of the blacklist */ function getBlacklistLength() public view returns (uint256) { return _blacklist.length; } /** * @return Blacklisted address at index */ function getBlacklist(uint256 index) public view returns (address) { require(index < _blacklist.length, "index out of range"); return _blacklist[index]; } // reserved storage slots uint256[50] private ______gap; }
contract ERC20WithBlacklist is Ownable, ERC20 { address[] private _blacklist; mapping(address => bool) private _blacklistMap; event AddedToBlacklist(address addr); event RemovedFromBlacklist(address addr); /** * @dev Throws if addr is blacklisted. */ modifier notBlacklisted(address addr) { require(!_blacklistMap[addr], "addr is blacklisted"); _; } /** * @param addr The address to check if blacklisted * @return true if addr is blacklisted, false otherwise */ function isBlacklisted(address addr) public view returns (bool) { return _blacklistMap[addr]; } /** * @dev Function to add an address to the blacklist * @param addr The address to add to the blacklist * @return A boolean that indicates if the operation was successful. */ function addToBlacklist(address addr) public onlyOwner returns (bool) { require(!_blacklistMap[addr], "addr is already blacklisted"); _blacklistMap[addr] = true; _blacklist.push(addr); emit AddedToBlacklist(addr); return true; } /** * @dev Function to remove an address from the blacklist * @param addr The address to remove from the blacklist * @return A boolean that indicates if the operation was successful. */ function removeFromBlacklist(address addr) public onlyOwner returns (bool) { require(_blacklistMap[addr], "addr is not blacklisted"); _blacklistMap[addr] = false; for (uint256 i = 0; i < _blacklist.length; i++) { if (_blacklist[i] == addr) { _blacklist[i] = _blacklist[_blacklist.length - 1]; _blacklist.pop(); break; } } emit RemovedFromBlacklist(addr); return true; } /** * @return Length of the blacklist */ function getBlacklistLength() public view returns (uint256) { return _blacklist.length; } /** * @return Blacklisted address at index */ function getBlacklist(uint256 index) public view returns (address) { require(index < _blacklist.length, "index out of range"); return _blacklist[index]; } // reserved storage slots uint256[50] private ______gap; }
21,951
139
// When the loan was created
uint256 timeCreated;
uint256 timeCreated;
50,041
29
// Helper fuction to get already claimed amount for a wallet. /
function claimedAmount(address wallet, address collection) public view returns (uint16) { RadlistedCollection storage radlistedCollection = collections[collection]; Claimed storage claimed = radlistedCollection.claimed; return claimed.perWallet[wallet]; }
function claimedAmount(address wallet, address collection) public view returns (uint16) { RadlistedCollection storage radlistedCollection = collections[collection]; Claimed storage claimed = radlistedCollection.claimed; return claimed.perWallet[wallet]; }
38,876
5
// Minimum buyback price is 50 BUSD for 1 SAT
uint256 public constant MIN_BUYBACK_PRICE = 50; uint256 public constant MIN_TOKEN_BALANCE_TO_COUNT = 100000000000000; // 0.0001 event Apply(address indexed user, uint256 amount, bool isReapply); event TokenToSellWithdraw(address indexed user, uint256 amount); event BuybackWithdraw(address indexed user, uint256 amount);
uint256 public constant MIN_BUYBACK_PRICE = 50; uint256 public constant MIN_TOKEN_BALANCE_TO_COUNT = 100000000000000; // 0.0001 event Apply(address indexed user, uint256 amount, bool isReapply); event TokenToSellWithdraw(address indexed user, uint256 amount); event BuybackWithdraw(address indexed user, uint256 amount);
34,381
43
// after conversion event happens, time travel before and check options
uint32 ct = esop.currentTime(); esop.offerOptionsToEmployee(emp1, ct, ct + 2 weeks, 10000, false); emp1.employeeSignsToESOP(); uint maxopts = esop.totalPoolOptions() - esop.remainingPoolOptions() + 10000; ct += uint32(esop.optionsCalculator().vestingPeriod() / 2); esop.mockTime(ct); converter = new DummyOptionsConverter(address(esop), ct + 60 days); uint8 rc = uint8(esop.offerOptionsConversion(converter)); assertEq(uint(rc), 0, "offerOptionsConversion");
uint32 ct = esop.currentTime(); esop.offerOptionsToEmployee(emp1, ct, ct + 2 weeks, 10000, false); emp1.employeeSignsToESOP(); uint maxopts = esop.totalPoolOptions() - esop.remainingPoolOptions() + 10000; ct += uint32(esop.optionsCalculator().vestingPeriod() / 2); esop.mockTime(ct); converter = new DummyOptionsConverter(address(esop), ct + 60 days); uint8 rc = uint8(esop.offerOptionsConversion(converter)); assertEq(uint(rc), 0, "offerOptionsConversion");
17,315