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
// Data //Constructor /
modifier once { if (initialized) revert(); _; } function initialize(address _buyer, address _seller, uint _principal, bytes8[] tickers, uint[] amounts, address _registrar, address _override, address _logger, uint _rebalanceFrequency, uint _followFee, uint _minFollowerPrincipal) once { prismData.accountLib.owner = msg.sender; prismData.accountLib.buyer = _buyer; prismData.accountLib.seller = _seller; prismData.override = _override; prismData.logger = PrismLogger(_logger); prismData.rebalancerLib.rebalanceFrequency = _rebalanceFrequency; prismData.followerManagerLib.followFee = _followFee; prismData.followerManagerLib.minFollowerPrincipal = _minFollowerPrincipal; prismData.portfolioLib.principal = _principal; prismData.portfolioLib.initPortInternal(tickers, amounts, _registrar); initialized = true; }
modifier once { if (initialized) revert(); _; } function initialize(address _buyer, address _seller, uint _principal, bytes8[] tickers, uint[] amounts, address _registrar, address _override, address _logger, uint _rebalanceFrequency, uint _followFee, uint _minFollowerPrincipal) once { prismData.accountLib.owner = msg.sender; prismData.accountLib.buyer = _buyer; prismData.accountLib.seller = _seller; prismData.override = _override; prismData.logger = PrismLogger(_logger); prismData.rebalancerLib.rebalanceFrequency = _rebalanceFrequency; prismData.followerManagerLib.followFee = _followFee; prismData.followerManagerLib.minFollowerPrincipal = _minFollowerPrincipal; prismData.portfolioLib.principal = _principal; prismData.portfolioLib.initPortInternal(tickers, amounts, _registrar); initialized = true; }
6,441
18
// Validates that the given destination address is validate for a mint. Functionwill return false if validation fails. /
function validateMint(address _to) external view returns (bool);
function validateMint(address _to) external view returns (bool);
55,056
36
// Sets the vault rewards address./_rewards a new rewards address.
function setRewards(address _rewards) public onlyOwner { rewards = _rewards; }
function setRewards(address _rewards) public onlyOwner { rewards = _rewards; }
15,190
179
// External interface of the EaselyPayout contract /
interface IEaselyPayout { /** * @dev Takes in a payable amount and splits it among the given royalties. * Also takes a cut of the payable amount depending on the sender and the primaryPayout address. * Ensures that this method never splits over 100% of the payin amount. */ function splitPayable(address primaryPayout, address[] memory royalties, uint256[] memory bps) external payable; }
interface IEaselyPayout { /** * @dev Takes in a payable amount and splits it among the given royalties. * Also takes a cut of the payable amount depending on the sender and the primaryPayout address. * Ensures that this method never splits over 100% of the payin amount. */ function splitPayable(address primaryPayout, address[] memory royalties, uint256[] memory bps) external payable; }
23,959
607
// collect all combined warriors data
function getCombinedWarriors() internal view returns(uint256[] memory warriorsData) { uint256 length = tournamentQueueSize; warriorsData = new uint256[](length); for(uint256 i = 0; i < length; i ++) { // Grab the combined warrior data in storage. warriorsData[i] = tournamentQueue[i * DATA_SIZE + 1]; } return warriorsData; }
function getCombinedWarriors() internal view returns(uint256[] memory warriorsData) { uint256 length = tournamentQueueSize; warriorsData = new uint256[](length); for(uint256 i = 0; i < length; i ++) { // Grab the combined warrior data in storage. warriorsData[i] = tournamentQueue[i * DATA_SIZE + 1]; } return warriorsData; }
66,509
0
// address public constant oneSplitAddress = 0xC586BeF4a0992C495Cf22e1aeEE4E446CECDee0E; 1split.eth
address public constant CURVE_ADDRESS = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; // 3-pool DAI/USDC/USDT address public constant ONESPLIT_ADDRESS = 0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e; //1proto.eth address public constant UNIROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant USDC_ADDRESS = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public constant USDT_ADDRESS = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
address public constant CURVE_ADDRESS = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; // 3-pool DAI/USDC/USDT address public constant ONESPLIT_ADDRESS = 0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e; //1proto.eth address public constant UNIROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant USDC_ADDRESS = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public constant USDT_ADDRESS = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
15,283
3
// Vesting contract address getter. _id Sequential identifier for vesting contract.return vesting contract address. /
function getVestingAddress(uint256 _id) public view returns(address)
function getVestingAddress(uint256 _id) public view returns(address)
18,105
6
// get the Tier for each MinterestNFT token /
function tokenTier(uint256) external view returns (uint256);
function tokenTier(uint256) external view returns (uint256);
40,952
26
// Throws if called by any account other than the owner. /
modifier onlyFabric() { require(fabrics[msg.sender].isActive); _; }
modifier onlyFabric() { require(fabrics[msg.sender].isActive); _; }
40,942
50
// Internal Boshi pair LP mint.
function _mint(address to, uint256 amount) internal { totalSupply = totalSupply.add(amount); balanceOf[to] = balanceOf[to].add(amount); emit Transfer(address(0), to, amount); }
function _mint(address to, uint256 amount) internal { totalSupply = totalSupply.add(amount); balanceOf[to] = balanceOf[to].add(amount); emit Transfer(address(0), to, amount); }
33,304
35
// Awaits battle results
function _awaitBattleResults(string memory _battleName) internal { Battle memory _battle = getBattle(_battleName); require( msg.sender == _battle.players[0] || msg.sender == _battle.players[1], "Only players in this battle can make a move" ); require( _battle.moves[0] != 0 && _battle.moves[1] != 0, "Players still need to make a move" ); _resolveBattle(_battle); }
function _awaitBattleResults(string memory _battleName) internal { Battle memory _battle = getBattle(_battleName); require( msg.sender == _battle.players[0] || msg.sender == _battle.players[1], "Only players in this battle can make a move" ); require( _battle.moves[0] != 0 && _battle.moves[1] != 0, "Players still need to make a move" ); _resolveBattle(_battle); }
17,568
5
// transfer amount of tokens to an address/_to receiver of token/_value amount value of token to send/ return success as true, for transfer
function transfer(address _to, uint256 _value) external returns (bool success){ require(balanceOf[msg.sender] >= _value); _transfer(msg.sender, _to, _value); return true; }
function transfer(address _to, uint256 _value) external returns (bool success){ require(balanceOf[msg.sender] >= _value); _transfer(msg.sender, _to, _value); return true; }
38,744
3
// Map from IDs of restricted polls to the minimum number of votes needed for a bug to pass
mapping(uint256 => uint256) minimumVotes;
mapping(uint256 => uint256) minimumVotes;
18,697
35
// Calculate the vested and unclaimed months and tokens available for `_grantId` to claim/ Due to rounding errors once grant duration is reached, returns the entire left grant amount/ Returns (0, 0) if lock duration has not been reached
function calculateGrantClaim(address _recipient) public view returns (uint256, uint256) { Grant storage tokenGrant = tokenGrants[_recipient]; require(tokenGrant.totalClaimed < tokenGrant.amount, "Grant fully claimed"); // Check if lock duration was reached by comparing the current time with the startTime. If lock duration hasn't been reached, return 0, 0 if (currentTime() < tokenGrant.startTime) { return (0, 0); } // Elapsed months is the number of months since the startTime (after lock duration is complete) // We add 1 to the calculation as any time after the unlock timestamp counts as the first elapsed month. // For example: lock duration of 0 and current time at day 1, counts as elapsed month of 1 // Lock duration of 1 month and current time at day 31, counts as elapsed month of 2 // This is to accomplish the design that the first batch of vested tokens are claimable immediately after unlock. uint256 elapsedMonths = currentTime().sub(tokenGrant.startTime).div(intervalTime).add(1); // If over vesting duration, all tokens vested if (elapsedMonths > tokenGrant.vestingDuration) { uint256 remainingGrant = tokenGrant.amount.sub(tokenGrant.totalClaimed); uint256 balanceMonth = tokenGrant.vestingDuration.sub(tokenGrant.monthsClaimed); return (balanceMonth, remainingGrant); } else { uint256 monthsVested = uint256(elapsedMonths.sub(tokenGrant.monthsClaimed)); uint256 amountVestedPerMonth = (tokenGrant.amount.sub(tokenGrant.totalClaimed)).div(uint256(tokenGrant.vestingDuration.sub(tokenGrant.monthsClaimed))); uint256 amountVested = uint256(monthsVested.mul(amountVestedPerMonth)); return (monthsVested, amountVested); } }
function calculateGrantClaim(address _recipient) public view returns (uint256, uint256) { Grant storage tokenGrant = tokenGrants[_recipient]; require(tokenGrant.totalClaimed < tokenGrant.amount, "Grant fully claimed"); // Check if lock duration was reached by comparing the current time with the startTime. If lock duration hasn't been reached, return 0, 0 if (currentTime() < tokenGrant.startTime) { return (0, 0); } // Elapsed months is the number of months since the startTime (after lock duration is complete) // We add 1 to the calculation as any time after the unlock timestamp counts as the first elapsed month. // For example: lock duration of 0 and current time at day 1, counts as elapsed month of 1 // Lock duration of 1 month and current time at day 31, counts as elapsed month of 2 // This is to accomplish the design that the first batch of vested tokens are claimable immediately after unlock. uint256 elapsedMonths = currentTime().sub(tokenGrant.startTime).div(intervalTime).add(1); // If over vesting duration, all tokens vested if (elapsedMonths > tokenGrant.vestingDuration) { uint256 remainingGrant = tokenGrant.amount.sub(tokenGrant.totalClaimed); uint256 balanceMonth = tokenGrant.vestingDuration.sub(tokenGrant.monthsClaimed); return (balanceMonth, remainingGrant); } else { uint256 monthsVested = uint256(elapsedMonths.sub(tokenGrant.monthsClaimed)); uint256 amountVestedPerMonth = (tokenGrant.amount.sub(tokenGrant.totalClaimed)).div(uint256(tokenGrant.vestingDuration.sub(tokenGrant.monthsClaimed))); uint256 amountVested = uint256(monthsVested.mul(amountVestedPerMonth)); return (monthsVested, amountVested); } }
4,082
70
// Emits a {Transfer} event with `from` set to the zero address. Requirements - `to` cannot be the zero address. /
function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); }
function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); }
1,616
80
// ```
* Requirements are the same as {_approve}. */ function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual { if (owner == address(0)) { revert ERC20InvalidApprover(address(0)); } if (spender == address(0)) { revert ERC20InvalidSpender(address(0)); } _allowances[owner][spender] = value; if (emitEvent) { emit Approval(owner, spender, value); } }
* Requirements are the same as {_approve}. */ function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual { if (owner == address(0)) { revert ERC20InvalidApprover(address(0)); } if (spender == address(0)) { revert ERC20InvalidSpender(address(0)); } _allowances[owner][spender] = value; if (emitEvent) { emit Approval(owner, spender, value); } }
25,843
9
// swaps for specific ugly
function swapSelectedUgly(uint _poolId, uint _idFromPool, uint _idToPool) public payable whenNotPaused { require(pools[_poolId].random == false,"Pool only allows random swaps."); require(tokenIds[_poolId].length() > 0, "Nothing in pool."); require(msg.value >= pools[_poolId].fee, "Not enough ETH to pay fee"); pools[_poolId].registry.safeTransferFrom(msg.sender, address(this), _idFromPool); pools[_poolId].registry.safeTransferFrom( address(this), msg.sender, _idToPool); uint _contractFee = msg.value * contractFee / 100; // Take % for contractRoyaltyPayee pools[_poolId].fees += msg.value - _contractFee; tokenIds[_poolId].remove(_idToPool); tokenIds[_poolId].add(_idFromPool); // Address.sendValue(payable(contractFeePayee), _contractFee); payable(contractFeePayee).transfer(_contractFee); emit TradeExecuted(_poolId, msg.sender, _idFromPool, _idToPool); }
function swapSelectedUgly(uint _poolId, uint _idFromPool, uint _idToPool) public payable whenNotPaused { require(pools[_poolId].random == false,"Pool only allows random swaps."); require(tokenIds[_poolId].length() > 0, "Nothing in pool."); require(msg.value >= pools[_poolId].fee, "Not enough ETH to pay fee"); pools[_poolId].registry.safeTransferFrom(msg.sender, address(this), _idFromPool); pools[_poolId].registry.safeTransferFrom( address(this), msg.sender, _idToPool); uint _contractFee = msg.value * contractFee / 100; // Take % for contractRoyaltyPayee pools[_poolId].fees += msg.value - _contractFee; tokenIds[_poolId].remove(_idToPool); tokenIds[_poolId].add(_idFromPool); // Address.sendValue(payable(contractFeePayee), _contractFee); payable(contractFeePayee).transfer(_contractFee); emit TradeExecuted(_poolId, msg.sender, _idFromPool, _idToPool); }
36,035
57
// _safeMint's second argument now takes in a quantity, not a tokenId.
_safeMint(creator, amount); actualPrice = amount * _mintPrice; // Charge people for the ACTUAL amount minted; uint256 assetAmount; newTokenId++; for (uint256 i; i < amount; i++) {
_safeMint(creator, amount); actualPrice = amount * _mintPrice; // Charge people for the ACTUAL amount minted; uint256 assetAmount; newTokenId++; for (uint256 i; i < amount; i++) {
9,885
47
// Returns the base and quote asset addresses for the given orderbook. orderbook The address of the orderbook to retrieve the base and quote asset addresses for.return base The address of the base asset.return quote The address of the quote asset. /
function getBaseQuote( address orderbook
function getBaseQuote( address orderbook
31,278
473
// Returns whether the given account is entered in the given asset account The address of the account to check jToken The jToken to checkreturn True if the account is in the asset, otherwise false. /
function checkMembership(address account, JToken jToken) external view returns (bool) { return markets[address(jToken)].accountMembership[account]; }
function checkMembership(address account, JToken jToken) external view returns (bool) { return markets[address(jToken)].accountMembership[account]; }
33,300
3
// require(detHolderBalance > 0, "Insufficient DET balance");
uint currentValue = dai.balanceOf(address(this)).mul(detHolderBalance).div(detDivider);
uint currentValue = dai.balanceOf(address(this)).mul(detHolderBalance).div(detDivider);
41,875
298
// Fills the input order./orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient./orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt./fillTakerTokenAmount Desired amount of takerToken to fill./shouldThrowOnInsufficientBalanceOrAllowance Test if transfer will fail before attempting./v ECDSA signature parameter v./r ECDSA signature parameters r./s ECDSA signature parameters s./ return Total amount of takerToken filled in trade.
function fillOrder( address[5] orderAddresses, uint[6] orderValues, uint fillTakerTokenAmount, bool shouldThrowOnInsufficientBalanceOrAllowance, uint8 v, bytes32 r, bytes32 s) public returns (uint filledTakerTokenAmount)
function fillOrder( address[5] orderAddresses, uint[6] orderValues, uint fillTakerTokenAmount, bool shouldThrowOnInsufficientBalanceOrAllowance, uint8 v, bytes32 r, bytes32 s) public returns (uint filledTakerTokenAmount)
25,063
128
// Explicitly check that this auction is currently live. (Because of how Ethereum mappings work, we can't just count on the lookup above failing. An invalid _tokenId will just return an auction object that is all zeros.)
require(_isOnAuction(auction));
require(_isOnAuction(auction));
24,078
7
// run code only when tge address is locked
modifier isLocked() { assert(locked); _; }
modifier isLocked() { assert(locked); _; }
14,667
3
// OracleFeed /
contract OracleFeed is IAggregatorV3Interface, AccessControl { event AnswerUpdated(int256 indexed current, uint256 roundId, uint256 updatedAt); uint256 public constant version = 0; uint8 public override decimals; int256 public latestAnswer; uint256 public latestTimestamp; string public description; constructor(uint8 _decimals, int256 _initialAnswer, string memory _description) { decimals = _decimals; description = _description; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); updateAnswer(_initialAnswer); } function updateAnswer(int256 _answer) public onlyRole(DEFAULT_ADMIN_ROLE) { latestAnswer = _answer; latestTimestamp = block.timestamp; emit AnswerUpdated(latestAnswer, 0, block.timestamp); } function latestRoundData() external view override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return ( uint80(0), latestAnswer, latestTimestamp, latestTimestamp, uint80(0) ); } }
contract OracleFeed is IAggregatorV3Interface, AccessControl { event AnswerUpdated(int256 indexed current, uint256 roundId, uint256 updatedAt); uint256 public constant version = 0; uint8 public override decimals; int256 public latestAnswer; uint256 public latestTimestamp; string public description; constructor(uint8 _decimals, int256 _initialAnswer, string memory _description) { decimals = _decimals; description = _description; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); updateAnswer(_initialAnswer); } function updateAnswer(int256 _answer) public onlyRole(DEFAULT_ADMIN_ROLE) { latestAnswer = _answer; latestTimestamp = block.timestamp; emit AnswerUpdated(latestAnswer, 0, block.timestamp); } function latestRoundData() external view override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return ( uint80(0), latestAnswer, latestTimestamp, latestTimestamp, uint80(0) ); } }
16,472
667
// Inserts a boolean value shifted by an offset into a 256 bit word, replacing the old value. Returns the newword. /
function insertBoolean( bytes32 word, bool value, uint256 offset
function insertBoolean( bytes32 word, bool value, uint256 offset
7,009
14
// /
constructor( ILendingPoolAddressesProvider _lendingPoolAddressProvider, IWETHGateway _wethGateway, address _dataProvider, address _incentiveController, IERC20 _rewardToken, address _inboundCurrency
constructor( ILendingPoolAddressesProvider _lendingPoolAddressProvider, IWETHGateway _wethGateway, address _dataProvider, address _incentiveController, IERC20 _rewardToken, address _inboundCurrency
26,729
202
// Borrowing spread has been updated./borrowingSpread The new borrowing spread.
event BorrowingSpreadUpdated(uint256 borrowingSpread);
event BorrowingSpreadUpdated(uint256 borrowingSpread);
9,591
0
// IPFS CID V1 base32 raw "bafrei..." => 5 bits => uint32 uint256 id= 256 bits = 1 bit + 51 uint32 = 1 + 515 = 256 00 added right => uint8 + uint256 + 00 = 258 bits = uint8 + 50 uint32 + (3 bits + 00) = uint8 + 51 uint32 = 3 + 515 = 258
bytes memory buffer = new bytes(52); uint8 high3 = uint8(id >> 253); buffer[0] = _BASE32_SYMBOLS[high3 & 0x1f]; id <<= 2; for (uint256 i = 51; i > 0; i--) { buffer[i] = _BASE32_SYMBOLS[id & 0x1f]; id >>= 5; }
bytes memory buffer = new bytes(52); uint8 high3 = uint8(id >> 253); buffer[0] = _BASE32_SYMBOLS[high3 & 0x1f]; id <<= 2; for (uint256 i = 51; i > 0; i--) { buffer[i] = _BASE32_SYMBOLS[id & 0x1f]; id >>= 5; }
33,545
16
// Check is not needed because safeSub(_allowance, _value) will already throw if this condition is not met if (_value > _allowance) throw;
balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true;
balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true;
32,819
6
// More advanced distribution mechanism with a fixed amount of reward per blockfor the whole contractWIP
contract LiquidityPool2 is LpToken { struct Checkpoint { uint blockNumber; uint avgTotalBalance; } mapping(address => Checkpoint) public checkpoints; Checkpoint public globalCheckpoint; uint constant public REWARD_PER_BLOCK = 1000 * 10 ** 18; UnderlyingToken public underlyingToken; GovernanceToken public governanceToken; uint public genesisBlock; constructor(address _underlyingToken, address _governanceToken) { underlyingToken = UnderlyingToken(_underlyingToken); governanceToken = GovernanceToken(_governanceToken); globalCheckpoint.blockNumber = block.number; genesisBlock = block.number; } function deposit(uint amount) external { globalCheckpoint.avgTotalBalance = _getAvgTotalBalance(); globalCheckpoint.blockNumber = block.number; _distributeRewards(msg.sender); underlyingToken.transferFrom(msg.sender, address(this), amount); _mint(msg.sender, amount); globalCheckpoint.avgTotalBalance = _getAvgTotalBalance(); checkpoints[msg.sender].avgTotalBalance = globalCheckpoint.avgTotalBalance; checkpoints[msg.sender].blockNumber = block.number; } function withdraw(uint amount) external { require(balanceOf(msg.sender) >= amount, 'not enough lp token'); globalCheckpoint.avgTotalBalance = _getAvgTotalBalance(); globalCheckpoint.blockNumber = block.number; _distributeRewards(msg.sender); checkpoints[msg.sender].avgTotalBalance = globalCheckpoint.avgTotalBalance; checkpoints[msg.sender].blockNumber = block.number; underlyingToken.transfer(msg.sender, amount); _burn(msg.sender, amount); globalCheckpoint.avgTotalBalance = _getAvgTotalBalance(); checkpoints[msg.sender].avgTotalBalance = globalCheckpoint.avgTotalBalance; checkpoints[msg.sender].blockNumber = block.number; } function _getAvgTotalBalance() public view returns(uint) { if(block.number - genesisBlock == 0) { return totalSupply(); } return (globalCheckpoint.avgTotalBalance * (globalCheckpoint.blockNumber - genesisBlock) + totalSupply() * (block.number - globalCheckpoint.blockNumber)) / (block.number - genesisBlock); } function _distributeRewards(address beneficiary) internal { Checkpoint storage userCheckpoint = checkpoints[beneficiary]; if(block.number - userCheckpoint.blockNumber > 0) { uint avgTotalBalanceRewardPeriod = (globalCheckpoint.avgTotalBalance * globalCheckpoint.blockNumber - userCheckpoint.avgTotalBalance * userCheckpoint.blockNumber) / (block.number - userCheckpoint.blockNumber); if(avgTotalBalanceRewardPeriod > 0) { uint distributionAmount = (balanceOf(beneficiary) * (block.number - userCheckpoint.blockNumber) * REWARD_PER_BLOCK) / avgTotalBalanceRewardPeriod; governanceToken.mint(beneficiary, distributionAmount); } } } }
contract LiquidityPool2 is LpToken { struct Checkpoint { uint blockNumber; uint avgTotalBalance; } mapping(address => Checkpoint) public checkpoints; Checkpoint public globalCheckpoint; uint constant public REWARD_PER_BLOCK = 1000 * 10 ** 18; UnderlyingToken public underlyingToken; GovernanceToken public governanceToken; uint public genesisBlock; constructor(address _underlyingToken, address _governanceToken) { underlyingToken = UnderlyingToken(_underlyingToken); governanceToken = GovernanceToken(_governanceToken); globalCheckpoint.blockNumber = block.number; genesisBlock = block.number; } function deposit(uint amount) external { globalCheckpoint.avgTotalBalance = _getAvgTotalBalance(); globalCheckpoint.blockNumber = block.number; _distributeRewards(msg.sender); underlyingToken.transferFrom(msg.sender, address(this), amount); _mint(msg.sender, amount); globalCheckpoint.avgTotalBalance = _getAvgTotalBalance(); checkpoints[msg.sender].avgTotalBalance = globalCheckpoint.avgTotalBalance; checkpoints[msg.sender].blockNumber = block.number; } function withdraw(uint amount) external { require(balanceOf(msg.sender) >= amount, 'not enough lp token'); globalCheckpoint.avgTotalBalance = _getAvgTotalBalance(); globalCheckpoint.blockNumber = block.number; _distributeRewards(msg.sender); checkpoints[msg.sender].avgTotalBalance = globalCheckpoint.avgTotalBalance; checkpoints[msg.sender].blockNumber = block.number; underlyingToken.transfer(msg.sender, amount); _burn(msg.sender, amount); globalCheckpoint.avgTotalBalance = _getAvgTotalBalance(); checkpoints[msg.sender].avgTotalBalance = globalCheckpoint.avgTotalBalance; checkpoints[msg.sender].blockNumber = block.number; } function _getAvgTotalBalance() public view returns(uint) { if(block.number - genesisBlock == 0) { return totalSupply(); } return (globalCheckpoint.avgTotalBalance * (globalCheckpoint.blockNumber - genesisBlock) + totalSupply() * (block.number - globalCheckpoint.blockNumber)) / (block.number - genesisBlock); } function _distributeRewards(address beneficiary) internal { Checkpoint storage userCheckpoint = checkpoints[beneficiary]; if(block.number - userCheckpoint.blockNumber > 0) { uint avgTotalBalanceRewardPeriod = (globalCheckpoint.avgTotalBalance * globalCheckpoint.blockNumber - userCheckpoint.avgTotalBalance * userCheckpoint.blockNumber) / (block.number - userCheckpoint.blockNumber); if(avgTotalBalanceRewardPeriod > 0) { uint distributionAmount = (balanceOf(beneficiary) * (block.number - userCheckpoint.blockNumber) * REWARD_PER_BLOCK) / avgTotalBalanceRewardPeriod; governanceToken.mint(beneficiary, distributionAmount); } } } }
43,482
313
// Update the total Fei deposited into the Vault proportionately.
getTotalFeiBoostedForVault[vault] += feiAmount; emit VaultBoosted(msg.sender, vault, feiAmount);
getTotalFeiBoostedForVault[vault] += feiAmount; emit VaultBoosted(msg.sender, vault, feiAmount);
19,226
4
// Recover signer address from a message by using his signature hash bytes32 message, the hash is the signed message. What is recovered is the signer address. sig bytes signature, the signature is generated using web3.eth.sign() /
function recover(bytes32 hash, bytes memory sig) public pure returns (address) { bytes32 r; bytes32 s; uint8 v; //Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } }
function recover(bytes32 hash, bytes memory sig) public pure returns (address) { bytes32 r; bytes32 s; uint8 v; //Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } }
8,066
24
// Record the amount of ETH sent as the contract's current value.
contract_eth_value = this.balance;
contract_eth_value = this.balance;
20,256
116
// Returns the minimum input asset amount required to buy the given output asset amount and the prices amountOut Amount of reserveOut reserveIn Address of the asset to be swap from reserveOut Address of the asset to be swap toreturn uint256 Amount in of the reserveInreturn uint256 The price of in amount denominated in the reserveOut currency (18 decimals)return uint256 In amount of reserveIn value denominated in USD (8 decimals)return uint256 Out amount of reserveOut value denominated in USD (8 decimals)return address[] The exchange path /
function getAmountsIn(
function getAmountsIn(
39,428
277
// Unwraps `amount` yield tokens into the underlying token.//amount The amount of yield-tokens to redeem./recipientThe recipient of the resulting underlying-tokens.// return amountUnderlyingTokens The amount of underlying tokens unwrapped to `recipient`.
function unwrap(uint256 amount, address recipient) external returns (uint256 amountUnderlyingTokens);
function unwrap(uint256 amount, address recipient) external returns (uint256 amountUnderlyingTokens);
44,265
18
// get total shares in the stakingreturn total shares amount /
function totalShares() external view returns (uint256);
function totalShares() external view returns (uint256);
42,304
14
// transfer any divs we got
winner.transfer(address(this).balance);
winner.transfer(address(this).balance);
38,647
72
// Check the Rig `tokenId` exists
if (!_exists(tokenId)) revert OwnerQueryForNonexistentToken(); return _pilots.pilotInfo(tokenId);
if (!_exists(tokenId)) revert OwnerQueryForNonexistentToken(); return _pilots.pilotInfo(tokenId);
14,525
68
// if subscription expired
if (!isSubscriptionValid) { return ownerOfOverrideReturn; }
if (!isSubscriptionValid) { return ownerOfOverrideReturn; }
32,595
1
// mapping (address => uint) public addressToPunkIndex;
mapping (uint => address) public punkIndexToAddress;
mapping (uint => address) public punkIndexToAddress;
3,422
24
// Check to see if account is a campaign owner/Determine whether a specified account address is the campaign owner/_campaignID (campaign id) The campaign id/_owner (owner) The owner address/ return is address the campaign owner or not (boolean)
function isOwner(uint _campaignID, address _owner) constant returns (bool) {}
function isOwner(uint _campaignID, address _owner) constant returns (bool) {}
25,450
5
// The length of all presales on the platform /
function presalesLength() external view returns (uint256) { return presales.length(); }
function presalesLength() external view returns (uint256) { return presales.length(); }
27,187
641
// Expires a cover after a set period of time.Changes the status of the Cover and reduces the currentsum assured of all areas in which the quotation liesUnlocks the CN tokens of the cover. Updates the Total Sum Assured value. _cid Cover Id. /
function expireCover(uint _cid) public { require(checkCoverExpired(_cid) && qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.CoverExpired)); tf.unlockCN(_cid); bytes4 curr; address scAddress; uint sumAssured; (,, scAddress, curr, sumAssured,) = qd.getCoverDetailsByCoverID1(_cid); if (qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.ClaimAccepted)) _removeSAFromCSA(_cid, sumAssured); qd.changeCoverStatusNo(_cid, uint8(QuotationData.CoverStatus.CoverExpired)); }
function expireCover(uint _cid) public { require(checkCoverExpired(_cid) && qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.CoverExpired)); tf.unlockCN(_cid); bytes4 curr; address scAddress; uint sumAssured; (,, scAddress, curr, sumAssured,) = qd.getCoverDetailsByCoverID1(_cid); if (qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.ClaimAccepted)) _removeSAFromCSA(_cid, sumAssured); qd.changeCoverStatusNo(_cid, uint8(QuotationData.CoverStatus.CoverExpired)); }
28,784
16
// Transfer tokens to another account
function transfer(address recipient, uint256 amount) public returns (bool) { // Prevent transfer to 0x0 address require(recipient != address(0), "Transfer to the zero address"); // Check if the sender has enough tokens require(amount <= _balances[msg.sender], "Transfer amount exceeds balance"); // Subtract tokens from sender's account _balances[msg.sender] -= amount; // Add tokens to recipient's account uint256 newBalance = _balances[recipient] + amount; require(newBalance >= _balances[recipient], "Addition overflow"); _balances[recipient] = newBalance; // Notify the listeners emit Transfer(msg.sender, recipient, amount); return true; }
function transfer(address recipient, uint256 amount) public returns (bool) { // Prevent transfer to 0x0 address require(recipient != address(0), "Transfer to the zero address"); // Check if the sender has enough tokens require(amount <= _balances[msg.sender], "Transfer amount exceeds balance"); // Subtract tokens from sender's account _balances[msg.sender] -= amount; // Add tokens to recipient's account uint256 newBalance = _balances[recipient] + amount; require(newBalance >= _balances[recipient], "Addition overflow"); _balances[recipient] = newBalance; // Notify the listeners emit Transfer(msg.sender, recipient, amount); return true; }
44,931
4
// boost market to nerf rice hoarding
marketSeeds=SafeMath.add(marketSeeds,SafeMath.div(eggsUsed,10));
marketSeeds=SafeMath.add(marketSeeds,SafeMath.div(eggsUsed,10));
56,962
51
// Make a hole
uint64 oldEnd = modifiedInterval.end; modifiedInterval.end = begin; modifiedInterval.next = _insert( self, index, modifiedInterval.next, end, oldEnd, true );
uint64 oldEnd = modifiedInterval.end; modifiedInterval.end = begin; modifiedInterval.next = _insert( self, index, modifiedInterval.next, end, oldEnd, true );
1,978
21
// Bubble up the revert if the staticcall reverts.
returndatacopy(0x00, 0x00, returndatasize()) revert(0x00, returndatasize())
returndatacopy(0x00, 0x00, returndatasize()) revert(0x00, returndatasize())
23,869
190
// milk.mint(devAddr, milkReward.mul(3).div(100));3% developersmilk.mint(distributor, milkReward.div(100));1% shakeHoldersmilk.mint(address(this), milkReward);
milk.transferFrom(owner(), address(this), milkReward); pool.accMilkPerShare = pool.accMilkPerShare.add(milkReward.mul(1e12).div(NFTSupply)); pool.lastRewardBlock = block.number;
milk.transferFrom(owner(), address(this), milkReward); pool.accMilkPerShare = pool.accMilkPerShare.add(milkReward.mul(1e12).div(NFTSupply)); pool.lastRewardBlock = block.number;
58,059
100
// See {IERC721-approve}./
function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); }
function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); }
34,317
30
// Get contract's token balance
function getTokenBalance(address targetAddress) public isOwner view returns (uint _balance) { ERC20 targetToken = ERC20(targetAddress); uint balance = targetToken.balanceOf(address(this)); return balance; }
function getTokenBalance(address targetAddress) public isOwner view returns (uint _balance) { ERC20 targetToken = ERC20(targetAddress); uint balance = targetToken.balanceOf(address(this)); return balance; }
34,138
364
// `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error./`yieldToken` must be enabled or this call will revert with a {TokenDisabled} error./`yieldToken` underlying token must be enabled or this call will revert with a {TokenDisabled} error./`recipient` must be non-zero or this call will revert with an {IllegalArgument} error./`amount` must be greater than zero or the call will revert with an {IllegalArgument} error.//Emits a {Deposit} event.//_NOTE:_ This function is WHITELISTED.//_NOTE:_ When depositing, the `AlchemistV2` contract must have allowance() to spend funds on behalf of msg.sender for at least amount of the yieldToken being deposited.This can be done via
function deposit( address yieldToken, uint256 amount, address recipient ) external returns (uint256 sharesIssued);
function deposit( address yieldToken, uint256 amount, address recipient ) external returns (uint256 sharesIssued);
44,318
157
// See updateStakeLock()_staker an address to update stake lock _depositId updated deposit ID _lockedUntil updated deposit locked until value /
function _updateStakeLock( address _staker, uint256 _depositId, uint64 _lockedUntil
function _updateStakeLock( address _staker, uint256 _depositId, uint64 _lockedUntil
11,195
173
// Must be a trusted member
require(rocketDAONode.getMemberIsValid(msg.sender), "Not a trusted member");
require(rocketDAONode.getMemberIsValid(msg.sender), "Not a trusted member");
57,462
12
// Returns true if the slice is empty (has a length of 0). self The slice to operate on.return True if the slice is empty, False otherwise. /
function empty(slice self) internal returns (bool) { return self._len == 0; }
function empty(slice self) internal returns (bool) { return self._len == 0; }
2,814
75
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint; uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20; uint256 private constant ACC_SUSHI_PRECISION = 1e12; event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
uint256 public totalAllocPoint; uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20; uint256 private constant ACC_SUSHI_PRECISION = 1e12; event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
4,747
13
// - Token 消耗通知事件
event Burn(address indexed _from, uint256 _value);
event Burn(address indexed _from, uint256 _value);
38,812
592
// updateDocumentPoll(): check whether the _proposal has achieved majorityNote: the polls contract publicly exposes the function this calls,but we offer it in the ecliptic interface as a convenience
function updateDocumentPoll(bytes32 _proposal) external
function updateDocumentPoll(bytes32 _proposal) external
52,110
4
// Store data length on stack for later use
uint256 length = data.length;
uint256 length = data.length;
565
39
// Updates the state to remove a ERC1155 child _tokenId The owning token to transfer from _childContract The ERC1155 contract of the child token _childTokenId The tokenId of the token that is being transferred _amount The amount of the token that is being transferred /
function _remove1155Child( uint256 _tokenId, address _childContract, uint256 _childTokenId, uint256 _amount
function _remove1155Child( uint256 _tokenId, address _childContract, uint256 _childTokenId, uint256 _amount
60,547
24
// consective 6 round winners can claim the big bounty
function claimBounty() external payable nonReentrant override returns (bool) { /* what if there are more than 1 winners: "First come first serve" */ require(isBountyClaimed == false, "only can be claimed once"); require(isTopPlayers[msg.sender] == true, "only top player can get"); require(players[msg.sender].consecutivelWinningAmount == 6, "only consectively won 6 time"); (bool success, ) = payable(msg.sender).call{value: bountyAmount}(" "); if (!success) { revert CallFailed(); } isBountyClaimed = true; return true; }
function claimBounty() external payable nonReentrant override returns (bool) { /* what if there are more than 1 winners: "First come first serve" */ require(isBountyClaimed == false, "only can be claimed once"); require(isTopPlayers[msg.sender] == true, "only top player can get"); require(players[msg.sender].consecutivelWinningAmount == 6, "only consectively won 6 time"); (bool success, ) = payable(msg.sender).call{value: bountyAmount}(" "); if (!success) { revert CallFailed(); } isBountyClaimed = true; return true; }
19,955
86
// Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], butwith `errorMessage` as a fallback revert reason when `abq` reverts. _Available since v3.1._ /
function functionCallWithValue(address abq, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(abq), "Address: call to non-contract");
function functionCallWithValue(address abq, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(abq), "Address: call to non-contract");
20,148
238
// Flip the early access mode to allow/disallow public minting instead of merkle-drop whitelist
function toggleEarlyAccessMode() external onlyOwner { if (earlyAccessMode) { earlyAccessMode = false; } else { earlyAccessMode = true; } }
function toggleEarlyAccessMode() external onlyOwner { if (earlyAccessMode) { earlyAccessMode = false; } else { earlyAccessMode = true; } }
21,403
10
// Validates that each signer address matches for the given oracles _serviceAgreementID Service agreement ID _oracles Array of oracle addresses which agreed to the service agreement _signatures contains the collected parts(v, r, and s) of each oracle's signature. /
function registerOracleSignatures( bytes32 _serviceAgreementID, address[] memory _oracles, OracleSignatures memory _signatures ) private
function registerOracleSignatures( bytes32 _serviceAgreementID, address[] memory _oracles, OracleSignatures memory _signatures ) private
16,021
102
// Store the size
mstore(ptr, returndatasize())
mstore(ptr, returndatasize())
40,719
231
// Calculate option payoff Represents total payoff to option holders This value will decrease as options are redeemed. The change in valuecorresponds to the payoff returned from a redemption. This method is only used after expiry. After expiry, the `baseToken` balanceof this contract is always at least current payoff + pool value. Currentpayoff is the amount owed to option holders and pool value is the amountowed to LPs. /
function getCurrentPayoff() public view returns (uint256) { uint256[] memory longSupplies = getTotalSupplies(longTokens); uint256[] memory shortSupplies = getTotalSupplies(shortTokens); return OptionMath.calcPayoff(strikePrices, expiryPrice, isPut, longSupplies, shortSupplies); }
function getCurrentPayoff() public view returns (uint256) { uint256[] memory longSupplies = getTotalSupplies(longTokens); uint256[] memory shortSupplies = getTotalSupplies(shortTokens); return OptionMath.calcPayoff(strikePrices, expiryPrice, isPut, longSupplies, shortSupplies); }
46,317
2
// Emits a {Transfer} event. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`./
function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; }
function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; }
28,901
39
// Allows someone to send ether and obtain the token
function purchase(uint256 _tokenId) public payable { address oldOwner = personIndexToOwner[_tokenId]; address newOwner = msg.sender; uint256 sellingPrice = personIndexToPrice[_tokenId]; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 94), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); // Update prices if (sellingPrice < firstStepLimit) { // first stage personIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 94); } else if (sellingPrice < secondStepLimit) { // second stage personIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 120), 94); } else { // third stage personIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 94); } _transfer(oldOwner, newOwner, _tokenId); // Pay previous tokenOwner if owner is not contract if (oldOwner != address(this)) { oldOwner.transfer(payment); //(1-0.06) } TokenSold(_tokenId, sellingPrice, personIndexToPrice[_tokenId], oldOwner, newOwner, persons[_tokenId].name); msg.sender.transfer(purchaseExcess); }
function purchase(uint256 _tokenId) public payable { address oldOwner = personIndexToOwner[_tokenId]; address newOwner = msg.sender; uint256 sellingPrice = personIndexToPrice[_tokenId]; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 94), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); // Update prices if (sellingPrice < firstStepLimit) { // first stage personIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 94); } else if (sellingPrice < secondStepLimit) { // second stage personIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 120), 94); } else { // third stage personIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 94); } _transfer(oldOwner, newOwner, _tokenId); // Pay previous tokenOwner if owner is not contract if (oldOwner != address(this)) { oldOwner.transfer(payment); //(1-0.06) } TokenSold(_tokenId, sellingPrice, personIndexToPrice[_tokenId], oldOwner, newOwner, persons[_tokenId].name); msg.sender.transfer(purchaseExcess); }
78,252
16
// Get Dydx Acccount arg /
function _getAccountArgs() internal view returns (SoloMarginContract.Info[] memory) { SoloMarginContract.Info[] memory accounts = new SoloMarginContract.Info[](1); accounts[0] = (SoloMarginContract.Info(address(this), 0)); return accounts; }
function _getAccountArgs() internal view returns (SoloMarginContract.Info[] memory) { SoloMarginContract.Info[] memory accounts = new SoloMarginContract.Info[](1); accounts[0] = (SoloMarginContract.Info(address(this), 0)); return accounts; }
19,699
107
// step 1. Check is it enough unspent native tokens
{ require(nativeSpent >= vars.localNative, "NativeSpent balance higher then remote"); uint256 nativeAvailable = nativeSpent - vars.localNative;
{ require(nativeSpent >= vars.localNative, "NativeSpent balance higher then remote"); uint256 nativeAvailable = nativeSpent - vars.localNative;
15,336
77
// Swap tokens
pancakeRouter.swapExactTokensForTokens( swapAmountIn, _tokenAmountOutMin, path, address(this), block.timestamp, isFeeEnabled );
pancakeRouter.swapExactTokensForTokens( swapAmountIn, _tokenAmountOutMin, path, address(this), block.timestamp, isFeeEnabled );
10,508
12
// push an ownership checkpoint & emit event
uint96 last = next + batchSize - 1; _sequentialOwnership.push(last, uint160(to));
uint96 last = next + batchSize - 1; _sequentialOwnership.push(last, uint160(to));
428
11
// SafeMathUnsigned math operations with safety checks that revert on errorsource : openzeppelin-solidity/contracts/math/SafeMath.sol/
library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "error"); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "cannot divide by 0 or negative"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "result cannot be lower than 0"); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "both numbers have to be positive"); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "cannot divide by 0"); return a % b; } }
library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "error"); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "cannot divide by 0 or negative"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "result cannot be lower than 0"); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "both numbers have to be positive"); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "cannot divide by 0"); return a % b; } }
11,762
2
// Sets owner only on first run
constructor() public
constructor() public
42,372
13
// mint the avaiable interests to callee./once it mint, the amount of interests will transfer to callee's address./ return the amount of interests minted.
function mint(address to) external returns (uint);
function mint(address to) external returns (uint);
82,351
36
// token int2 to readable str token An output parameter to which the first token is written.return `token`. /
function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); }
function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); }
895
42
// Pay the website owner that invoked the web node that found the PRL seed key
balances[_payout] += payAmount;
balances[_payout] += payAmount;
58,376
1,574
// 789
entry "overambitiously" : ENG_ADVERB
entry "overambitiously" : ENG_ADVERB
21,625
17
// Protect user from ETC/ETH trapped
function (){ throw; }
function (){ throw; }
38,936
115
// unregister a scheme _avatar address _scheme the address of the schemereturn bool which represents a success /
function unregisterScheme(address _scheme, address _avatar)
function unregisterScheme(address _scheme, address _avatar)
20,032
55
// Withdrawals // Validates withdrawal data _partition Source partition of the withdrawal _operator Address that is invoking the transfer _value Number of tokens to be transferred _operatorData Contains the withdrawal authorization datareturn true if the withdrawal data is valid, otherwise false /
function _validateWithdrawal( bytes32 _partition, address _operator, uint256 _value, bytes memory _operatorData
function _validateWithdrawal( bytes32 _partition, address _operator, uint256 _value, bytes memory _operatorData
41,841
11
// Buyer's price is below the agreed
if (msg.value < escrow.price) throw;
if (msg.value < escrow.price) throw;
3,205
139
// convert to WETH
IWETH(address(WETH_ADDRESS)).deposit{value: msg.value}();
IWETH(address(WETH_ADDRESS)).deposit{value: msg.value}();
21,872
169
// Verify it's a cfolioItemTokenId
require(cfolioItemTokenId.isCFolioCard(), 'CFHI: Not CFolioCard');
require(cfolioItemTokenId.isCFolioCard(), 'CFHI: Not CFolioCard');
57,946
20
// Transfer 25% to Give Directly
payable(giveDirectlyAddress).transfer(_each);
payable(giveDirectlyAddress).transfer(_each);
29,870
4
// The `Vault` is Balancer V2's core contract. A single instance of it exists for the entire network, and it is theentity used to interact with Pools by Liquidity Providers who join and exit them, Traders who swap, and AssetManagers who withdraw and deposit tokens. The `Vault`'s source code is split among a number of sub-contracts, with the goal of improving readability and makingunderstanding the system easier. Most sub-contracts have been marked as `abstract` to explicitly indicate that onlythe full `Vault` is meant to be deployed. Roughly speaking, these are the contents of each sub-contract:- `AssetManagers`: Pool token Asset Manager registry,
contract Vault is VaultAuthorization, FlashLoans, Swaps { constructor( IAuthorizer authorizer, IWETH weth, uint256 pauseWindowDuration, uint256 bufferPeriodDuration ) VaultAuthorization(authorizer) AssetHelpers(weth) TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration) { // solhint-disable-previous-line no-empty-blocks } function setPaused(bool paused) external override nonReentrant authenticate { _setPaused(paused); } // solhint-disable-next-line func-name-mixedcase function WETH() external view override returns (IWETH) { return _WETH(); } }
contract Vault is VaultAuthorization, FlashLoans, Swaps { constructor( IAuthorizer authorizer, IWETH weth, uint256 pauseWindowDuration, uint256 bufferPeriodDuration ) VaultAuthorization(authorizer) AssetHelpers(weth) TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration) { // solhint-disable-previous-line no-empty-blocks } function setPaused(bool paused) external override nonReentrant authenticate { _setPaused(paused); } // solhint-disable-next-line func-name-mixedcase function WETH() external view override returns (IWETH) { return _WETH(); } }
2
114
// Sets withdraw fee period Only callable by the contract admin. /
function setWithdrawFeePeriod(uint256 _withdrawFeePeriod) external onlyAdmin { require( _withdrawFeePeriod <= MAX_WITHDRAW_FEE_PERIOD, "withdrawFeePeriod cannot be more than MAX_WITHDRAW_FEE_PERIOD" ); uint256 oldPeriod = withdrawFeePeriod; withdrawFeePeriod = _withdrawFeePeriod; UpdateWithdarwPeriod(msg.sender, oldPeriod, _withdrawFeePeriod); }
function setWithdrawFeePeriod(uint256 _withdrawFeePeriod) external onlyAdmin { require( _withdrawFeePeriod <= MAX_WITHDRAW_FEE_PERIOD, "withdrawFeePeriod cannot be more than MAX_WITHDRAW_FEE_PERIOD" ); uint256 oldPeriod = withdrawFeePeriod; withdrawFeePeriod = _withdrawFeePeriod; UpdateWithdarwPeriod(msg.sender, oldPeriod, _withdrawFeePeriod); }
51,951
113
// Accumulate new reward and remove old deposits./_user Address of the user./_count How many deposits to claim.
function executeUnstakes(address _user, uint256 _count) internal virtual { UserInfo storage user = userInfo[_user]; _count = (_count == 0) ? user.depositTail : Math.min(user.depositTail, user.depositHead.add(_count)); uint256 endedDepositAmount = 0; for (uint256 i = user.depositHead; i < _count; i++) { DepositInfo memory deposit = user.deposits[i]; if (deposit.time < now) { endedDepositAmount = endedDepositAmount.add(deposit.amount); delete user.deposits[i]; user.depositHead = user.depositHead.add(1); emit Withdraw(_user, 0, deposit.amount, deposit.time, now); } } if (endedDepositAmount > 0) { user.amount = user.amount.sub(endedDepositAmount); totalStake = totalStake.sub(endedDepositAmount); referralRewards.handleDepositEnd(_user, endedDepositAmount); safeTokenTransfer(_user, endedDepositAmount); } }
function executeUnstakes(address _user, uint256 _count) internal virtual { UserInfo storage user = userInfo[_user]; _count = (_count == 0) ? user.depositTail : Math.min(user.depositTail, user.depositHead.add(_count)); uint256 endedDepositAmount = 0; for (uint256 i = user.depositHead; i < _count; i++) { DepositInfo memory deposit = user.deposits[i]; if (deposit.time < now) { endedDepositAmount = endedDepositAmount.add(deposit.amount); delete user.deposits[i]; user.depositHead = user.depositHead.add(1); emit Withdraw(_user, 0, deposit.amount, deposit.time, now); } } if (endedDepositAmount > 0) { user.amount = user.amount.sub(endedDepositAmount); totalStake = totalStake.sub(endedDepositAmount); referralRewards.handleDepositEnd(_user, endedDepositAmount); safeTokenTransfer(_user, endedDepositAmount); } }
21,276
5
// Boolean flag to enable or disable free selfdrop
bool public enableFREE = true;
bool public enableFREE = true;
21,101
11
// getRewardDistribution returns the address of the reward distribution contract.
function getRewardDistribution() external view returns (IFantomMintRewardManager);
function getRewardDistribution() external view returns (IFantomMintRewardManager);
30,483
68
// It returns the user allocation for pool 100,000,000,000 means 0.1 (10%) / 1 means 0.0000000000001 (0.0000001%) / 1,000,000,000,000 means 1 (100%) _user: user address _pid: pool idreturn it returns the user's share of pool /
function _getUserAllocationPool(address _user, uint8 _pid) internal view returns (uint256) { if (_poolInformation[_pid].totalAmountPool > 0) { return _userInfo[_user][_pid].amountPool.mul(1e18).div(_poolInformation[_pid].totalAmountPool.mul(1e6)); } else { return 0; } }
function _getUserAllocationPool(address _user, uint8 _pid) internal view returns (uint256) { if (_poolInformation[_pid].totalAmountPool > 0) { return _userInfo[_user][_pid].amountPool.mul(1e18).div(_poolInformation[_pid].totalAmountPool.mul(1e6)); } else { return 0; } }
46,451
83
// Stores all the important DFS addresses and can be changed (timelock)
contract DFSRegistry is AdminAuth { DefisaverLogger public constant logger = DefisaverLogger( 0x5c55B921f590a89C1Ebe84dF170E655a82b62126 ); string public constant ERR_ENTRY_ALREADY_EXISTS = "Entry id already exists"; string public constant ERR_ENTRY_NON_EXISTENT = "Entry id doesn't exists"; string public constant ERR_ENTRY_NOT_IN_CHANGE = "Entry not in change process"; string public constant ERR_WAIT_PERIOD_SHORTER = "New wait period must be bigger"; string public constant ERR_CHANGE_NOT_READY = "Change not ready yet"; string public constant ERR_EMPTY_PREV_ADDR = "Previous addr is 0"; string public constant ERR_ALREADY_IN_CONTRACT_CHANGE = "Already in contract change"; string public constant ERR_ALREADY_IN_WAIT_PERIOD_CHANGE = "Already in wait period change"; struct Entry { address contractAddr; uint256 waitPeriod; uint256 changeStartTime; bool inContractChange; bool inWaitPeriodChange; bool exists; } mapping(bytes32 => Entry) public entries; mapping(bytes32 => address) public previousAddresses; mapping(bytes32 => address) public pendingAddresses; mapping(bytes32 => uint256) public pendingWaitTimes; /// @notice Given an contract id returns the registred address /// @dev Id is keccak256 of the contract name /// @param _id Id of contract function getAddr(bytes32 _id) public view returns (address) { return entries[_id].contractAddr; } /// @notice Helper function to easily query if id is registred /// @param _id Id of contract function isRegistered(bytes32 _id) public view returns (bool) { return entries[_id].exists; } /////////////////////////// OWNER ONLY FUNCTIONS /////////////////////////// /// @notice Adds a new contract to the registry /// @param _id Id of contract /// @param _contractAddr Address of the contract /// @param _waitPeriod Amount of time to wait before a contract address can be changed function addNewContract( bytes32 _id, address _contractAddr, uint256 _waitPeriod ) public onlyOwner { require(!entries[_id].exists, ERR_ENTRY_ALREADY_EXISTS); entries[_id] = Entry({ contractAddr: _contractAddr, waitPeriod: _waitPeriod, changeStartTime: 0, inContractChange: false, inWaitPeriodChange: false, exists: true }); // Remember tha address so we can revert back to old addr if needed previousAddresses[_id] = _contractAddr; logger.Log( address(this), msg.sender, "AddNewContract", abi.encode(_id, _contractAddr, _waitPeriod) ); } /// @notice Revertes to the previous address immediately /// @dev In case the new version has a fault, a quick way to fallback to the old contract /// @param _id Id of contract function revertToPreviousAddress(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(previousAddresses[_id] != address(0), ERR_EMPTY_PREV_ADDR); address currentAddr = entries[_id].contractAddr; entries[_id].contractAddr = previousAddresses[_id]; logger.Log( address(this), msg.sender, "RevertToPreviousAddress", abi.encode(_id, currentAddr, previousAddresses[_id]) ); } /// @notice Starts an address change for an existing entry /// @dev Can override a change that is currently in progress /// @param _id Id of contract /// @param _newContractAddr Address of the new contract function startContractChange(bytes32 _id, address _newContractAddr) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(!entries[_id].inWaitPeriodChange, ERR_ALREADY_IN_WAIT_PERIOD_CHANGE); entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inContractChange = true; pendingAddresses[_id] = _newContractAddr; logger.Log( address(this), msg.sender, "StartContractChange", abi.encode(_id, entries[_id].contractAddr, _newContractAddr) ); } /// @notice Changes new contract address, correct time must have passed /// @param _id Id of contract function approveContractChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE); require( block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line ERR_CHANGE_NOT_READY ); address oldContractAddr = entries[_id].contractAddr; entries[_id].contractAddr = pendingAddresses[_id]; entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; pendingAddresses[_id] = address(0); previousAddresses[_id] = oldContractAddr; logger.Log( address(this), msg.sender, "ApproveContractChange", abi.encode(_id, oldContractAddr, entries[_id].contractAddr) ); } /// @notice Cancel pending change /// @param _id Id of contract function cancelContractChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE); address oldContractAddr = pendingAddresses[_id]; pendingAddresses[_id] = address(0); entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; logger.Log( address(this), msg.sender, "CancelContractChange", abi.encode(_id, oldContractAddr, entries[_id].contractAddr) ); } /// @notice Starts the change for waitPeriod /// @param _id Id of contract /// @param _newWaitPeriod New wait time function startWaitPeriodChange(bytes32 _id, uint256 _newWaitPeriod) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(!entries[_id].inContractChange, ERR_ALREADY_IN_CONTRACT_CHANGE); pendingWaitTimes[_id] = _newWaitPeriod; entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inWaitPeriodChange = true; logger.Log( address(this), msg.sender, "StartWaitPeriodChange", abi.encode(_id, _newWaitPeriod) ); } /// @notice Changes new wait period, correct time must have passed /// @param _id Id of contract function approveWaitPeriodChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE); require( block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line ERR_CHANGE_NOT_READY ); uint256 oldWaitTime = entries[_id].waitPeriod; entries[_id].waitPeriod = pendingWaitTimes[_id]; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; pendingWaitTimes[_id] = 0; logger.Log( address(this), msg.sender, "ApproveWaitPeriodChange", abi.encode(_id, oldWaitTime, entries[_id].waitPeriod) ); } /// @notice Cancel wait period change /// @param _id Id of contract function cancelWaitPeriodChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE); uint256 oldWaitPeriod = pendingWaitTimes[_id]; pendingWaitTimes[_id] = 0; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; logger.Log( address(this), msg.sender, "CancelWaitPeriodChange", abi.encode(_id, oldWaitPeriod, entries[_id].waitPeriod) ); } }
contract DFSRegistry is AdminAuth { DefisaverLogger public constant logger = DefisaverLogger( 0x5c55B921f590a89C1Ebe84dF170E655a82b62126 ); string public constant ERR_ENTRY_ALREADY_EXISTS = "Entry id already exists"; string public constant ERR_ENTRY_NON_EXISTENT = "Entry id doesn't exists"; string public constant ERR_ENTRY_NOT_IN_CHANGE = "Entry not in change process"; string public constant ERR_WAIT_PERIOD_SHORTER = "New wait period must be bigger"; string public constant ERR_CHANGE_NOT_READY = "Change not ready yet"; string public constant ERR_EMPTY_PREV_ADDR = "Previous addr is 0"; string public constant ERR_ALREADY_IN_CONTRACT_CHANGE = "Already in contract change"; string public constant ERR_ALREADY_IN_WAIT_PERIOD_CHANGE = "Already in wait period change"; struct Entry { address contractAddr; uint256 waitPeriod; uint256 changeStartTime; bool inContractChange; bool inWaitPeriodChange; bool exists; } mapping(bytes32 => Entry) public entries; mapping(bytes32 => address) public previousAddresses; mapping(bytes32 => address) public pendingAddresses; mapping(bytes32 => uint256) public pendingWaitTimes; /// @notice Given an contract id returns the registred address /// @dev Id is keccak256 of the contract name /// @param _id Id of contract function getAddr(bytes32 _id) public view returns (address) { return entries[_id].contractAddr; } /// @notice Helper function to easily query if id is registred /// @param _id Id of contract function isRegistered(bytes32 _id) public view returns (bool) { return entries[_id].exists; } /////////////////////////// OWNER ONLY FUNCTIONS /////////////////////////// /// @notice Adds a new contract to the registry /// @param _id Id of contract /// @param _contractAddr Address of the contract /// @param _waitPeriod Amount of time to wait before a contract address can be changed function addNewContract( bytes32 _id, address _contractAddr, uint256 _waitPeriod ) public onlyOwner { require(!entries[_id].exists, ERR_ENTRY_ALREADY_EXISTS); entries[_id] = Entry({ contractAddr: _contractAddr, waitPeriod: _waitPeriod, changeStartTime: 0, inContractChange: false, inWaitPeriodChange: false, exists: true }); // Remember tha address so we can revert back to old addr if needed previousAddresses[_id] = _contractAddr; logger.Log( address(this), msg.sender, "AddNewContract", abi.encode(_id, _contractAddr, _waitPeriod) ); } /// @notice Revertes to the previous address immediately /// @dev In case the new version has a fault, a quick way to fallback to the old contract /// @param _id Id of contract function revertToPreviousAddress(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(previousAddresses[_id] != address(0), ERR_EMPTY_PREV_ADDR); address currentAddr = entries[_id].contractAddr; entries[_id].contractAddr = previousAddresses[_id]; logger.Log( address(this), msg.sender, "RevertToPreviousAddress", abi.encode(_id, currentAddr, previousAddresses[_id]) ); } /// @notice Starts an address change for an existing entry /// @dev Can override a change that is currently in progress /// @param _id Id of contract /// @param _newContractAddr Address of the new contract function startContractChange(bytes32 _id, address _newContractAddr) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(!entries[_id].inWaitPeriodChange, ERR_ALREADY_IN_WAIT_PERIOD_CHANGE); entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inContractChange = true; pendingAddresses[_id] = _newContractAddr; logger.Log( address(this), msg.sender, "StartContractChange", abi.encode(_id, entries[_id].contractAddr, _newContractAddr) ); } /// @notice Changes new contract address, correct time must have passed /// @param _id Id of contract function approveContractChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE); require( block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line ERR_CHANGE_NOT_READY ); address oldContractAddr = entries[_id].contractAddr; entries[_id].contractAddr = pendingAddresses[_id]; entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; pendingAddresses[_id] = address(0); previousAddresses[_id] = oldContractAddr; logger.Log( address(this), msg.sender, "ApproveContractChange", abi.encode(_id, oldContractAddr, entries[_id].contractAddr) ); } /// @notice Cancel pending change /// @param _id Id of contract function cancelContractChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE); address oldContractAddr = pendingAddresses[_id]; pendingAddresses[_id] = address(0); entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; logger.Log( address(this), msg.sender, "CancelContractChange", abi.encode(_id, oldContractAddr, entries[_id].contractAddr) ); } /// @notice Starts the change for waitPeriod /// @param _id Id of contract /// @param _newWaitPeriod New wait time function startWaitPeriodChange(bytes32 _id, uint256 _newWaitPeriod) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(!entries[_id].inContractChange, ERR_ALREADY_IN_CONTRACT_CHANGE); pendingWaitTimes[_id] = _newWaitPeriod; entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inWaitPeriodChange = true; logger.Log( address(this), msg.sender, "StartWaitPeriodChange", abi.encode(_id, _newWaitPeriod) ); } /// @notice Changes new wait period, correct time must have passed /// @param _id Id of contract function approveWaitPeriodChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE); require( block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line ERR_CHANGE_NOT_READY ); uint256 oldWaitTime = entries[_id].waitPeriod; entries[_id].waitPeriod = pendingWaitTimes[_id]; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; pendingWaitTimes[_id] = 0; logger.Log( address(this), msg.sender, "ApproveWaitPeriodChange", abi.encode(_id, oldWaitTime, entries[_id].waitPeriod) ); } /// @notice Cancel wait period change /// @param _id Id of contract function cancelWaitPeriodChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE); uint256 oldWaitPeriod = pendingWaitTimes[_id]; pendingWaitTimes[_id] = 0; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; logger.Log( address(this), msg.sender, "CancelWaitPeriodChange", abi.encode(_id, oldWaitPeriod, entries[_id].waitPeriod) ); } }
25,257
71
// STATICCALL updates the CALLER, updates the ADDRESS, and runs in a static, valueless context.
MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _address; nextMessageContext.isStatic = true; nextMessageContext.ovmCALLVALUE = 0; return _callContract( nextMessageContext, _gasLimit,
MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _address; nextMessageContext.isStatic = true; nextMessageContext.ovmCALLVALUE = 0; return _callContract( nextMessageContext, _gasLimit,
45,501
141
// address of nft asset token
address nftAsset;
address nftAsset;
23,420
12
// This contract handles swapping to and from xTGEN, Tradegen's staking token.
contract TradegenStaking is ERC20("Tradegen Staking Token", "xTGEN"){ using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public immutable TGEN; /** * @notice Creates the TradegenStaking contract and defines the Tradegen token. * @param _TGEN address of the Tradegen token contract. */ constructor(address _TGEN) { TGEN = IERC20(_TGEN); } /* ========== VIEWS ========== */ /** * @notice Returns the price of one share, in TGEN. */ function getSharePrice() external view returns (uint256) { if (totalSupply() == 0) { return 1e18; } return TGEN.balanceOf(address(this)).mul(1e18).div(totalSupply()); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Stakes TGEN tokens. * @param _amount Number of TGEN tokens to stake. */ function stake(uint256 _amount) public { require (_amount > 0, "TradegenStaking: Amount must be greater than 0."); // Gets the amount of TGEN locked in the contract. uint256 totalTGEN = TGEN.balanceOf(address(this)); // Gets the amount of xTGEN in existence. uint256 totalShares = totalSupply(); // If no xTGEN exists, mint it 1:1 to the amount put in. if (totalShares == 0 || totalTGEN == 0) { _mint(msg.sender, _amount); emit Stake(msg.sender, _amount, _amount); } // Calculate and mint the amount of xTGEN the Tradegen token is worth. The ratio will change overtime, as xTGEN is burned/minted and TGEN deposited + gained from fees. else { uint256 numberOfShares = _amount.mul(totalShares).div(totalTGEN); _mint(msg.sender, numberOfShares); emit Stake(msg.sender, _amount, numberOfShares); } // Lock the TGEN in the contract. TGEN.safeTransferFrom(msg.sender, address(this), _amount); } /** * @notice Unlocks the staked/gained TGEN and burns xTGEN. * @param _share Number of xTGEN to burn. */ function withdraw(uint256 _share) public { require (_share > 0, "TradegenStaking: Amount must be greater than 0."); // Gets the amount of xTGEN in existence. uint256 totalShares = totalSupply(); // Calculates the amount of TGEN the xTGEN is worth. uint256 numberOfTGEN = _share.mul(TGEN.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); TGEN.safeTransfer(msg.sender, numberOfTGEN); emit Withdraw(msg.sender, _share, numberOfTGEN); } /** * @notice Withdraws the user's entire balance of xTGEN. */ function exit() public { withdraw(balanceOf(msg.sender)); } /* ========== EVENTS ========== */ event Stake(address indexed user, uint256 amountOfTGEN, uint256 amountOfShares); event Withdraw(address indexed user, uint256 amountOfShares, uint256 amountOfTGEN); }
contract TradegenStaking is ERC20("Tradegen Staking Token", "xTGEN"){ using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public immutable TGEN; /** * @notice Creates the TradegenStaking contract and defines the Tradegen token. * @param _TGEN address of the Tradegen token contract. */ constructor(address _TGEN) { TGEN = IERC20(_TGEN); } /* ========== VIEWS ========== */ /** * @notice Returns the price of one share, in TGEN. */ function getSharePrice() external view returns (uint256) { if (totalSupply() == 0) { return 1e18; } return TGEN.balanceOf(address(this)).mul(1e18).div(totalSupply()); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Stakes TGEN tokens. * @param _amount Number of TGEN tokens to stake. */ function stake(uint256 _amount) public { require (_amount > 0, "TradegenStaking: Amount must be greater than 0."); // Gets the amount of TGEN locked in the contract. uint256 totalTGEN = TGEN.balanceOf(address(this)); // Gets the amount of xTGEN in existence. uint256 totalShares = totalSupply(); // If no xTGEN exists, mint it 1:1 to the amount put in. if (totalShares == 0 || totalTGEN == 0) { _mint(msg.sender, _amount); emit Stake(msg.sender, _amount, _amount); } // Calculate and mint the amount of xTGEN the Tradegen token is worth. The ratio will change overtime, as xTGEN is burned/minted and TGEN deposited + gained from fees. else { uint256 numberOfShares = _amount.mul(totalShares).div(totalTGEN); _mint(msg.sender, numberOfShares); emit Stake(msg.sender, _amount, numberOfShares); } // Lock the TGEN in the contract. TGEN.safeTransferFrom(msg.sender, address(this), _amount); } /** * @notice Unlocks the staked/gained TGEN and burns xTGEN. * @param _share Number of xTGEN to burn. */ function withdraw(uint256 _share) public { require (_share > 0, "TradegenStaking: Amount must be greater than 0."); // Gets the amount of xTGEN in existence. uint256 totalShares = totalSupply(); // Calculates the amount of TGEN the xTGEN is worth. uint256 numberOfTGEN = _share.mul(TGEN.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); TGEN.safeTransfer(msg.sender, numberOfTGEN); emit Withdraw(msg.sender, _share, numberOfTGEN); } /** * @notice Withdraws the user's entire balance of xTGEN. */ function exit() public { withdraw(balanceOf(msg.sender)); } /* ========== EVENTS ========== */ event Stake(address indexed user, uint256 amountOfTGEN, uint256 amountOfShares); event Withdraw(address indexed user, uint256 amountOfShares, uint256 amountOfTGEN); }
22,390
113
// switch to migration phase only if crowdsale manager is set
|| ((currentPhase == Phase.Running || currentPhase == Phase.Paused) && _nextPhase == Phase.Migrating && crowdsaleManager != 0x0) || (currentPhase == Phase.Paused && _nextPhase == Phase.Running)
|| ((currentPhase == Phase.Running || currentPhase == Phase.Paused) && _nextPhase == Phase.Migrating && crowdsaleManager != 0x0) || (currentPhase == Phase.Paused && _nextPhase == Phase.Running)
12,463
94
// Update the total number mints the recipient has done for this stage
stageMintsPerWallet += numberOfTokens; stageMints[presentStage][recipient] = stageMintsPerWallet; return (numberOfTokens);
stageMintsPerWallet += numberOfTokens; stageMints[presentStage][recipient] = stageMintsPerWallet; return (numberOfTokens);
26,048
14
// bytes32sidname = bytes32(allbasestations[sid]); bytes32cidname = bytes32(basestations[allbasestations[sid]].ClusterHeadNodes[cid]);
6,660
25
// service charging
require (manager.send(safeDiv(safeMul(msg.value, promotionCommisionPercent), 100))); uint deposit = safeDiv(safeMul(msg.value, 100 - promotionCommisionPercent), 100); Promotion memory _promotion = Promotion({ id: allPromotions.length, host: msg.sender, name: _name, msg: _msg, url: _url, eachRedPocketAmt: safeDiv(deposit, _maxNum),
require (manager.send(safeDiv(safeMul(msg.value, promotionCommisionPercent), 100))); uint deposit = safeDiv(safeMul(msg.value, 100 - promotionCommisionPercent), 100); Promotion memory _promotion = Promotion({ id: allPromotions.length, host: msg.sender, name: _name, msg: _msg, url: _url, eachRedPocketAmt: safeDiv(deposit, _maxNum),
51,266
14
// no need for owner checks as the following will fail if escrow is not owner
IVesting(unicryptVesting).transferLockOwnership(lockId, payable(msg.sender));
IVesting(unicryptVesting).transferLockOwnership(lockId, payable(msg.sender));
58,725