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
// 建構子
function AuctionWithdraw() payable { highestBidder = msg.sender; highestBid = 0; }
function AuctionWithdraw() payable { highestBidder = msg.sender; highestBid = 0; }
24,936
12
// Update the user's amount of claimed PAY first to prevent recursive call.
pay_claimed[msg.sender] = 0;
pay_claimed[msg.sender] = 0;
39,647
18
// Returns the price a pool from its id/poolId Id of the pool/ return poolPrice Price of the pool in wei/ return totalTokens Number of tokens of a pool (totalSupply)
function getPoolPrice(uint256 poolId) internal view returns ( uint256 poolPrice, uint256 totalTokens )
function getPoolPrice(uint256 poolId) internal view returns ( uint256 poolPrice, uint256 totalTokens )
15,750
12
// transferable
require(amount >= c.minAmount, "token amount must be greater than configured minAmount"); require(IERC20(tokenContract).allowance(msg.sender, address(this)) >= amount, "token allowance must be equal or greater than amount");
require(amount >= c.minAmount, "token amount must be greater than configured minAmount"); require(IERC20(tokenContract).allowance(msg.sender, address(this)) >= amount, "token allowance must be equal or greater than amount");
38,432
30
// Royalties formats required for use on the Rarible platform/https:docs.rarible.com/asset/royalties-schema
interface IHasSecondarySaleFees is IERC165 { event SecondarySaleFees(uint256 tokenId, address[] recipients, uint[] bps); function getFeeRecipients(uint256 id) external returns (address payable[] memory); function getFeeBps(uint256 id) external returns (uint[] memory); }
interface IHasSecondarySaleFees is IERC165 { event SecondarySaleFees(uint256 tokenId, address[] recipients, uint[] bps); function getFeeRecipients(uint256 id) external returns (address payable[] memory); function getFeeBps(uint256 id) external returns (uint[] memory); }
3,066
404
// Returns whether the given account is entered in the given asset account The address of the account to check aToken The aToken to checkreturn True if the account is in the asset, otherwise false. /
function checkMembership(address account, AToken aToken) external view returns (bool) { return markets[address(aToken)].accountMembership[account]; }
function checkMembership(address account, AToken aToken) external view returns (bool) { return markets[address(aToken)].accountMembership[account]; }
17,053
60
// calculate duration
uint256 duration = end.sub(start);
uint256 duration = end.sub(start);
71,974
66
// get Xend Token contract and mint token for member
_xendTokenContract.mint(payable(member), reward);
_xendTokenContract.mint(payable(member), reward);
5,660
82
// check if taker has enough balance if (safeAdd(safeAdd(safeMul(safeSub(t.capPrice, t.makerPrice), tv.qty)/ t.capPrice, safeMul(tv.qty, takerFee) / (1 ether)), t.takerGasFee / 1e10)1e10 > safeSub(balances[1],tv.takerReserve))
if (!checkEnoughBalance(t.floorPrice, t.makerPrice, tv.qty, true, takerFee, t.takerGasFee, futuresContractHash, safeSub(balances[1],tv.takerReserve))) {
if (!checkEnoughBalance(t.floorPrice, t.makerPrice, tv.qty, true, takerFee, t.takerGasFee, futuresContractHash, safeSub(balances[1],tv.takerReserve))) {
1,179
27
// Contract that creates the Token
contract Token is SafeMath { // Contract balance mapping (address => uint256) public balanceOf; // Token name string public name = "MoralityAI"; // Token symbol string public symbol = "Mo"; // Decimals to use uint8 public decimal = 18; // Total initial suppy uint256 public totalSupply = 1000000000000000000000000; // Transfer function interface event Transfer(address indexed from, address indexed to, uint256 value); // Token creation function function Token(){ // set the balance of the creator to the initial supply balanceOf[msg.sender] = totalSupply; } // Transfer function used to send tokens to an address function transfer(address _to, uint256 _value){ // Check if the creator actually has the required balance require(balanceOf[msg.sender] >= _value); // Check if the amount sent will not overflow require(safeAdd(balanceOf[_to], _value) >= balanceOf[_to]); // Substract tokens from the creator balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value); // Add tokens to the transfer address balanceOf[_to] = safeAdd(balanceOf[_to], _value); // Execute the transfer Transfer(msg.sender, _to, _value); } }
contract Token is SafeMath { // Contract balance mapping (address => uint256) public balanceOf; // Token name string public name = "MoralityAI"; // Token symbol string public symbol = "Mo"; // Decimals to use uint8 public decimal = 18; // Total initial suppy uint256 public totalSupply = 1000000000000000000000000; // Transfer function interface event Transfer(address indexed from, address indexed to, uint256 value); // Token creation function function Token(){ // set the balance of the creator to the initial supply balanceOf[msg.sender] = totalSupply; } // Transfer function used to send tokens to an address function transfer(address _to, uint256 _value){ // Check if the creator actually has the required balance require(balanceOf[msg.sender] >= _value); // Check if the amount sent will not overflow require(safeAdd(balanceOf[_to], _value) >= balanceOf[_to]); // Substract tokens from the creator balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value); // Add tokens to the transfer address balanceOf[_to] = safeAdd(balanceOf[_to], _value); // Execute the transfer Transfer(msg.sender, _to, _value); } }
20,388
8
// Security: function should only be called by owner or tokenFactory
function addERC20(address _address) external override OnlyBy(_ProjectERC20FactoryAddress, owner()) { console.log("DEBUG sol: addERC20", _address); pERC20Registry[_address] = true; }
function addERC20(address _address) external override OnlyBy(_ProjectERC20FactoryAddress, owner()) { console.log("DEBUG sol: addERC20", _address); pERC20Registry[_address] = true; }
16,182
95
// Cradle A smart-contract based mechanism to distribute tokens over time, inspired loosely by Compound and Uniswap. More background and motivation available at: /
contract Cradle is IStaking, Ownable { using SafeMath for uint256; event Staked(address indexed user, uint256 amount, uint256 total, bytes data); event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data); event TokensClaimed(address indexed user, uint256 amount); event TokensLocked(uint256 amount, uint256 durationSec, uint256 total); // amount: Unlocked tokens, total: Total locked tokens event TokensUnlocked(uint256 amount, uint256 total); TokenPool private _stakingPool; TokenPool private _unlockedPool; TokenPool private _lockedPool; // // Time-bonus params // uint256 public constant BONUS_DECIMALS = 2; uint256 public startBonus = 0; uint256 public bonusPeriodSec = 0; // // Global accounting state // uint256 public totalLockedShares = 0; uint256 public totalStakingShares = 0; uint256 private _totalStakingShareSeconds = 0; uint256 private _lastAccountingTimestampSec = now; uint256 private _maxUnlockSchedules = 0; uint256 private _initialSharesPerToken = 0; // // User accounting state // // Represents a single stake for a user. A user may have multiple. struct Stake { uint256 stakingShares; uint256 timestampSec; } // Caches aggregated values from the User->Stake[] map to save computation. // If lastAccountingTimestampSec is 0, there's no entry for that user. struct UserTotals { uint256 stakingShares; uint256 stakingShareSeconds; uint256 lastAccountingTimestampSec; } // Aggregated staking values per user mapping(address => UserTotals) private _userTotals; // The collection of stakes for each user. Ordered by timestamp, earliest to latest. mapping(address => Stake[]) private _userStakes; // // Locked/Unlocked Accounting state // struct UnlockSchedule { uint256 initialLockedShares; uint256 unlockedShares; uint256 lastUnlockTimestampSec; uint256 endAtSec; uint256 durationSec; } UnlockSchedule[] public unlockSchedules; /** * @param stakingToken The token users deposit as stake. * @param distributionToken The token users receive as they unstake. * @param maxUnlockSchedules Max number of unlock stages, to guard against hitting gas limit. * @param startBonus_ Starting time bonus, BONUS_DECIMALS fixed point. * e.g. 25% means user gets 25% of max distribution tokens. * @param bonusPeriodSec_ Length of time for bonus to increase linearly to max. * @param initialSharesPerToken Number of shares to mint per staking token on first stake. */ constructor(IERC20 stakingToken, IERC20 distributionToken, uint256 maxUnlockSchedules, uint256 startBonus_, uint256 bonusPeriodSec_, uint256 initialSharesPerToken) public { // The start bonus must be some fraction of the max. (i.e. <= 100%) require(startBonus_ <= 10**BONUS_DECIMALS, 'Cradle: start bonus too high'); // If no period is desired, instead set startBonus = 100% // and bonusPeriod to a small value like 1sec. require(bonusPeriodSec_ != 0, 'Cradle: bonus period is zero'); require(initialSharesPerToken > 0, 'Cradle: initialSharesPerToken is zero'); _stakingPool = new TokenPool(stakingToken); _unlockedPool = new TokenPool(distributionToken); _lockedPool = new TokenPool(distributionToken); startBonus = startBonus_; bonusPeriodSec = bonusPeriodSec_; _maxUnlockSchedules = maxUnlockSchedules; _initialSharesPerToken = initialSharesPerToken; } /** * @return The token users deposit as stake. */ function getStakingToken() public view returns (IERC20) { return _stakingPool.token(); } /** * @return The token users receive as they unstake. */ function getDistributionToken() public view returns (IERC20) { assert(_unlockedPool.token() == _lockedPool.token()); return _unlockedPool.token(); } /** * @dev Transfers amount of deposit tokens from the user. * @param amount Number of deposit tokens to stake. * @param data Not used. */ function stake(uint256 amount, bytes calldata data) external { _stakeFor(msg.sender, msg.sender, amount); } /** * @dev Transfers amount of deposit tokens from the caller on behalf of user. * @param user User address who gains credit for this stake operation. * @param amount Number of deposit tokens to stake. * @param data Not used. */ function stakeFor(address user, uint256 amount, bytes calldata data) external { _stakeFor(msg.sender, user, amount); } /** * @dev Private implementation of staking methods. * @param staker User address who deposits tokens to stake. * @param beneficiary User address who gains credit for this stake operation. * @param amount Number of deposit tokens to stake. */ function _stakeFor(address staker, address beneficiary, uint256 amount) private { require(amount > 0, 'Cradle: stake amount is zero'); require(beneficiary != address(0), 'Cradle: beneficiary is zero address'); require(totalStakingShares == 0 || totalStaked() > 0, 'Cradle: Invalid state. Staking shares exist, but no staking tokens do'); uint256 mintedStakingShares = (totalStakingShares > 0) ? totalStakingShares.mul(amount).div(totalStaked()) : amount.mul(_initialSharesPerToken); require(mintedStakingShares > 0, 'Cradle: Stake amount is too small'); updateAccounting(); // 1. User Accounting UserTotals storage totals = _userTotals[beneficiary]; totals.stakingShares = totals.stakingShares.add(mintedStakingShares); totals.lastAccountingTimestampSec = now; Stake memory newStake = Stake(mintedStakingShares, now); _userStakes[beneficiary].push(newStake); // 2. Global Accounting totalStakingShares = totalStakingShares.add(mintedStakingShares); // Already set in updateAccounting() // _lastAccountingTimestampSec = now; // interactions require(_stakingPool.token().transferFrom(staker, address(_stakingPool), amount), 'Cradle: transfer into staking pool failed'); emit Staked(beneficiary, amount, totalStakedFor(beneficiary), ""); } /** * @dev Unstakes a certain amount of previously deposited tokens. User also receives their * alotted number of distribution tokens. * @param amount Number of deposit tokens to unstake / withdraw. * @param data Not used. */ function unstake(uint256 amount, bytes calldata data) external { _unstake(amount); } /** * @param amount Number of deposit tokens to unstake / withdraw. * @return The total number of distribution tokens that would be rewarded. */ function unstakeQuery(uint256 amount) public returns (uint256) { return _unstake(amount); } /** * @dev Unstakes a certain amount of previously deposited tokens. User also receives their * alotted number of distribution tokens. * @param amount Number of deposit tokens to unstake / withdraw. * @return The total number of distribution tokens rewarded. */ function _unstake(uint256 amount) private returns (uint256) { updateAccounting(); // checks require(amount > 0, 'Cradle: unstake amount is zero'); require(totalStakedFor(msg.sender) >= amount, 'Cradle: unstake amount is greater than total user stakes'); uint256 stakingSharesToBurn = totalStakingShares.mul(amount).div(totalStaked()); require(stakingSharesToBurn > 0, 'Cradle: Unable to unstake amount this small'); // 1. User Accounting UserTotals storage totals = _userTotals[msg.sender]; Stake[] storage accountStakes = _userStakes[msg.sender]; // Redeem from most recent stake and go backwards in time. uint256 stakingShareSecondsToBurn = 0; uint256 sharesLeftToBurn = stakingSharesToBurn; uint256 rewardAmount = 0; while (sharesLeftToBurn > 0) { Stake storage lastStake = accountStakes[accountStakes.length - 1]; uint256 stakeTimeSec = now.sub(lastStake.timestampSec); uint256 newStakingShareSecondsToBurn = 0; if (lastStake.stakingShares <= sharesLeftToBurn) { // fully redeem a past stake newStakingShareSecondsToBurn = lastStake.stakingShares.mul(stakeTimeSec); rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec); stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn); sharesLeftToBurn = sharesLeftToBurn.sub(lastStake.stakingShares); accountStakes.length--; } else { // partially redeem a past stake newStakingShareSecondsToBurn = sharesLeftToBurn.mul(stakeTimeSec); rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec); stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn); lastStake.stakingShares = lastStake.stakingShares.sub(sharesLeftToBurn); sharesLeftToBurn = 0; } } totals.stakingShareSeconds = totals.stakingShareSeconds.sub(stakingShareSecondsToBurn); totals.stakingShares = totals.stakingShares.sub(stakingSharesToBurn); // Already set in updateAccounting // totals.lastAccountingTimestampSec = now; // 2. Global Accounting _totalStakingShareSeconds = _totalStakingShareSeconds.sub(stakingShareSecondsToBurn); totalStakingShares = totalStakingShares.sub(stakingSharesToBurn); // Already set in updateAccounting // _lastAccountingTimestampSec = now; // interactions require(_stakingPool.transfer(msg.sender, amount), 'Cradle: transfer out of staking pool failed'); require(_unlockedPool.transfer(msg.sender, rewardAmount), 'Cradle: transfer out of unlocked pool failed'); emit Unstaked(msg.sender, amount, totalStakedFor(msg.sender), ""); emit TokensClaimed(msg.sender, rewardAmount); require(totalStakingShares == 0 || totalStaked() > 0, "Cradle: Error unstaking. Staking shares exist, but no staking tokens do"); return rewardAmount; } /** * @dev Applies an additional time-bonus to a distribution amount. This is necessary to * encourage long-term deposits instead of constant unstake/restakes. * The bonus-multiplier is the result of a linear function that starts at startBonus and * ends at 100% over bonusPeriodSec, then stays at 100% thereafter. * @param currentRewardTokens The current number of distribution tokens already alotted for this * unstake op. Any bonuses are already applied. * @param stakingShareSeconds The stakingShare-seconds that are being burned for new * distribution tokens. * @param stakeTimeSec Length of time for which the tokens were staked. Needed to calculate * the time-bonus. * @return Updated amount of distribution tokens to award, with any bonus included on the * newly added tokens. */ function computeNewReward(uint256 currentRewardTokens, uint256 stakingShareSeconds, uint256 stakeTimeSec) private view returns (uint256) { uint256 newRewardTokens = totalUnlocked() .mul(stakingShareSeconds) .div(_totalStakingShareSeconds); if (stakeTimeSec >= bonusPeriodSec) { return currentRewardTokens.add(newRewardTokens); } uint256 oneHundredPct = 10**BONUS_DECIMALS; uint256 bonusedReward = startBonus .add(oneHundredPct.sub(startBonus).mul(stakeTimeSec).div(bonusPeriodSec)) .mul(newRewardTokens) .div(oneHundredPct); return currentRewardTokens.add(bonusedReward); } /** * @param addr The user to look up staking information for. * @return The number of staking tokens deposited for addr. */ function totalStakedFor(address addr) public view returns (uint256) { return totalStakingShares > 0 ? totalStaked().mul(_userTotals[addr].stakingShares).div(totalStakingShares) : 0; } /** * @return The total number of deposit tokens staked globally, by all users. */ function totalStaked() public view returns (uint256) { return _stakingPool.balance(); } /** * @dev Note that this application has a staking token as well as a distribution token, which * may be different. This function is required by EIP-900. * @return The deposit token used for staking. */ function token() external view returns (address) { return address(getStakingToken()); } /** * @dev A globally callable function to update the accounting state of the system. * Global state and state for the caller are updated. * @return [0] balance of the locked pool * @return [1] balance of the unlocked pool * @return [2] caller's staking share seconds * @return [3] global staking share seconds * @return [4] Rewards caller has accumulated, optimistically assumes max time-bonus. * @return [5] block timestamp */ function updateAccounting() public returns ( uint256, uint256, uint256, uint256, uint256, uint256) { unlockTokens(); // Global accounting uint256 newStakingShareSeconds = now .sub(_lastAccountingTimestampSec) .mul(totalStakingShares); _totalStakingShareSeconds = _totalStakingShareSeconds.add(newStakingShareSeconds); _lastAccountingTimestampSec = now; // User Accounting UserTotals storage totals = _userTotals[msg.sender]; uint256 newUserStakingShareSeconds = now .sub(totals.lastAccountingTimestampSec) .mul(totals.stakingShares); totals.stakingShareSeconds = totals.stakingShareSeconds .add(newUserStakingShareSeconds); totals.lastAccountingTimestampSec = now; uint256 totalUserRewards = (_totalStakingShareSeconds > 0) ? totalUnlocked().mul(totals.stakingShareSeconds).div(_totalStakingShareSeconds) : 0; return ( totalLocked(), totalUnlocked(), totals.stakingShareSeconds, _totalStakingShareSeconds, totalUserRewards, now ); } /** * @return Total number of locked distribution tokens. */ function totalLocked() public view returns (uint256) { return _lockedPool.balance(); } /** * @return Total number of unlocked distribution tokens. */ function totalUnlocked() public view returns (uint256) { return _unlockedPool.balance(); } /** * @return Number of unlock schedules. */ function unlockScheduleCount() public view returns (uint256) { return unlockSchedules.length; } /** * @dev This funcion allows the contract owner to add more locked distribution tokens, along * with the associated "unlock schedule". These locked tokens immediately begin unlocking * linearly over the duraction of durationSec timeframe. * @param amount Number of distribution tokens to lock. These are transferred from the caller. * @param durationSec Length of time to linear unlock the tokens. */ function lockTokens(uint256 amount, uint256 durationSec) external onlyOwner { require(unlockSchedules.length < _maxUnlockSchedules, 'Cradle: reached maximum unlock schedules'); // Update lockedTokens amount before using it in computations after. updateAccounting(); uint256 lockedTokens = totalLocked(); uint256 mintedLockedShares = (lockedTokens > 0) ? totalLockedShares.mul(amount).div(lockedTokens) : amount.mul(_initialSharesPerToken); UnlockSchedule memory schedule; schedule.initialLockedShares = mintedLockedShares; schedule.lastUnlockTimestampSec = now; schedule.endAtSec = now.add(durationSec); schedule.durationSec = durationSec; unlockSchedules.push(schedule); totalLockedShares = totalLockedShares.add(mintedLockedShares); require(_lockedPool.token().transferFrom(msg.sender, address(_lockedPool), amount), 'Cradle: transfer into locked pool failed'); emit TokensLocked(amount, durationSec, totalLocked()); } /** * @dev Moves distribution tokens from the locked pool to the unlocked pool, according to the * previously defined unlock schedules. Publicly callable. * @return Number of newly unlocked distribution tokens. */ function unlockTokens() public returns (uint256) { uint256 unlockedTokens = 0; uint256 lockedTokens = totalLocked(); if (totalLockedShares == 0) { unlockedTokens = lockedTokens; } else { uint256 unlockedShares = 0; for (uint256 s = 0; s < unlockSchedules.length; s++) { unlockedShares = unlockedShares.add(unlockScheduleShares(s)); } unlockedTokens = unlockedShares.mul(lockedTokens).div(totalLockedShares); totalLockedShares = totalLockedShares.sub(unlockedShares); } if (unlockedTokens > 0) { require(_lockedPool.transfer(address(_unlockedPool), unlockedTokens), 'Cradle: transfer out of locked pool failed'); emit TokensUnlocked(unlockedTokens, totalLocked()); } return unlockedTokens; } /** * @dev Returns the number of unlockable shares from a given schedule. The returned value * depends on the time since the last unlock. This function updates schedule accounting, * but does not actually transfer any tokens. * @param s Index of the unlock schedule. * @return The number of unlocked shares. */ function unlockScheduleShares(uint256 s) private returns (uint256) { UnlockSchedule storage schedule = unlockSchedules[s]; if(schedule.unlockedShares >= schedule.initialLockedShares) { return 0; } uint256 sharesToUnlock = 0; // Special case to handle any leftover dust from integer division if (now >= schedule.endAtSec) { sharesToUnlock = (schedule.initialLockedShares.sub(schedule.unlockedShares)); schedule.lastUnlockTimestampSec = schedule.endAtSec; } else { sharesToUnlock = now.sub(schedule.lastUnlockTimestampSec) .mul(schedule.initialLockedShares) .div(schedule.durationSec); schedule.lastUnlockTimestampSec = now; } schedule.unlockedShares = schedule.unlockedShares.add(sharesToUnlock); return sharesToUnlock; } }
contract Cradle is IStaking, Ownable { using SafeMath for uint256; event Staked(address indexed user, uint256 amount, uint256 total, bytes data); event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data); event TokensClaimed(address indexed user, uint256 amount); event TokensLocked(uint256 amount, uint256 durationSec, uint256 total); // amount: Unlocked tokens, total: Total locked tokens event TokensUnlocked(uint256 amount, uint256 total); TokenPool private _stakingPool; TokenPool private _unlockedPool; TokenPool private _lockedPool; // // Time-bonus params // uint256 public constant BONUS_DECIMALS = 2; uint256 public startBonus = 0; uint256 public bonusPeriodSec = 0; // // Global accounting state // uint256 public totalLockedShares = 0; uint256 public totalStakingShares = 0; uint256 private _totalStakingShareSeconds = 0; uint256 private _lastAccountingTimestampSec = now; uint256 private _maxUnlockSchedules = 0; uint256 private _initialSharesPerToken = 0; // // User accounting state // // Represents a single stake for a user. A user may have multiple. struct Stake { uint256 stakingShares; uint256 timestampSec; } // Caches aggregated values from the User->Stake[] map to save computation. // If lastAccountingTimestampSec is 0, there's no entry for that user. struct UserTotals { uint256 stakingShares; uint256 stakingShareSeconds; uint256 lastAccountingTimestampSec; } // Aggregated staking values per user mapping(address => UserTotals) private _userTotals; // The collection of stakes for each user. Ordered by timestamp, earliest to latest. mapping(address => Stake[]) private _userStakes; // // Locked/Unlocked Accounting state // struct UnlockSchedule { uint256 initialLockedShares; uint256 unlockedShares; uint256 lastUnlockTimestampSec; uint256 endAtSec; uint256 durationSec; } UnlockSchedule[] public unlockSchedules; /** * @param stakingToken The token users deposit as stake. * @param distributionToken The token users receive as they unstake. * @param maxUnlockSchedules Max number of unlock stages, to guard against hitting gas limit. * @param startBonus_ Starting time bonus, BONUS_DECIMALS fixed point. * e.g. 25% means user gets 25% of max distribution tokens. * @param bonusPeriodSec_ Length of time for bonus to increase linearly to max. * @param initialSharesPerToken Number of shares to mint per staking token on first stake. */ constructor(IERC20 stakingToken, IERC20 distributionToken, uint256 maxUnlockSchedules, uint256 startBonus_, uint256 bonusPeriodSec_, uint256 initialSharesPerToken) public { // The start bonus must be some fraction of the max. (i.e. <= 100%) require(startBonus_ <= 10**BONUS_DECIMALS, 'Cradle: start bonus too high'); // If no period is desired, instead set startBonus = 100% // and bonusPeriod to a small value like 1sec. require(bonusPeriodSec_ != 0, 'Cradle: bonus period is zero'); require(initialSharesPerToken > 0, 'Cradle: initialSharesPerToken is zero'); _stakingPool = new TokenPool(stakingToken); _unlockedPool = new TokenPool(distributionToken); _lockedPool = new TokenPool(distributionToken); startBonus = startBonus_; bonusPeriodSec = bonusPeriodSec_; _maxUnlockSchedules = maxUnlockSchedules; _initialSharesPerToken = initialSharesPerToken; } /** * @return The token users deposit as stake. */ function getStakingToken() public view returns (IERC20) { return _stakingPool.token(); } /** * @return The token users receive as they unstake. */ function getDistributionToken() public view returns (IERC20) { assert(_unlockedPool.token() == _lockedPool.token()); return _unlockedPool.token(); } /** * @dev Transfers amount of deposit tokens from the user. * @param amount Number of deposit tokens to stake. * @param data Not used. */ function stake(uint256 amount, bytes calldata data) external { _stakeFor(msg.sender, msg.sender, amount); } /** * @dev Transfers amount of deposit tokens from the caller on behalf of user. * @param user User address who gains credit for this stake operation. * @param amount Number of deposit tokens to stake. * @param data Not used. */ function stakeFor(address user, uint256 amount, bytes calldata data) external { _stakeFor(msg.sender, user, amount); } /** * @dev Private implementation of staking methods. * @param staker User address who deposits tokens to stake. * @param beneficiary User address who gains credit for this stake operation. * @param amount Number of deposit tokens to stake. */ function _stakeFor(address staker, address beneficiary, uint256 amount) private { require(amount > 0, 'Cradle: stake amount is zero'); require(beneficiary != address(0), 'Cradle: beneficiary is zero address'); require(totalStakingShares == 0 || totalStaked() > 0, 'Cradle: Invalid state. Staking shares exist, but no staking tokens do'); uint256 mintedStakingShares = (totalStakingShares > 0) ? totalStakingShares.mul(amount).div(totalStaked()) : amount.mul(_initialSharesPerToken); require(mintedStakingShares > 0, 'Cradle: Stake amount is too small'); updateAccounting(); // 1. User Accounting UserTotals storage totals = _userTotals[beneficiary]; totals.stakingShares = totals.stakingShares.add(mintedStakingShares); totals.lastAccountingTimestampSec = now; Stake memory newStake = Stake(mintedStakingShares, now); _userStakes[beneficiary].push(newStake); // 2. Global Accounting totalStakingShares = totalStakingShares.add(mintedStakingShares); // Already set in updateAccounting() // _lastAccountingTimestampSec = now; // interactions require(_stakingPool.token().transferFrom(staker, address(_stakingPool), amount), 'Cradle: transfer into staking pool failed'); emit Staked(beneficiary, amount, totalStakedFor(beneficiary), ""); } /** * @dev Unstakes a certain amount of previously deposited tokens. User also receives their * alotted number of distribution tokens. * @param amount Number of deposit tokens to unstake / withdraw. * @param data Not used. */ function unstake(uint256 amount, bytes calldata data) external { _unstake(amount); } /** * @param amount Number of deposit tokens to unstake / withdraw. * @return The total number of distribution tokens that would be rewarded. */ function unstakeQuery(uint256 amount) public returns (uint256) { return _unstake(amount); } /** * @dev Unstakes a certain amount of previously deposited tokens. User also receives their * alotted number of distribution tokens. * @param amount Number of deposit tokens to unstake / withdraw. * @return The total number of distribution tokens rewarded. */ function _unstake(uint256 amount) private returns (uint256) { updateAccounting(); // checks require(amount > 0, 'Cradle: unstake amount is zero'); require(totalStakedFor(msg.sender) >= amount, 'Cradle: unstake amount is greater than total user stakes'); uint256 stakingSharesToBurn = totalStakingShares.mul(amount).div(totalStaked()); require(stakingSharesToBurn > 0, 'Cradle: Unable to unstake amount this small'); // 1. User Accounting UserTotals storage totals = _userTotals[msg.sender]; Stake[] storage accountStakes = _userStakes[msg.sender]; // Redeem from most recent stake and go backwards in time. uint256 stakingShareSecondsToBurn = 0; uint256 sharesLeftToBurn = stakingSharesToBurn; uint256 rewardAmount = 0; while (sharesLeftToBurn > 0) { Stake storage lastStake = accountStakes[accountStakes.length - 1]; uint256 stakeTimeSec = now.sub(lastStake.timestampSec); uint256 newStakingShareSecondsToBurn = 0; if (lastStake.stakingShares <= sharesLeftToBurn) { // fully redeem a past stake newStakingShareSecondsToBurn = lastStake.stakingShares.mul(stakeTimeSec); rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec); stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn); sharesLeftToBurn = sharesLeftToBurn.sub(lastStake.stakingShares); accountStakes.length--; } else { // partially redeem a past stake newStakingShareSecondsToBurn = sharesLeftToBurn.mul(stakeTimeSec); rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec); stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn); lastStake.stakingShares = lastStake.stakingShares.sub(sharesLeftToBurn); sharesLeftToBurn = 0; } } totals.stakingShareSeconds = totals.stakingShareSeconds.sub(stakingShareSecondsToBurn); totals.stakingShares = totals.stakingShares.sub(stakingSharesToBurn); // Already set in updateAccounting // totals.lastAccountingTimestampSec = now; // 2. Global Accounting _totalStakingShareSeconds = _totalStakingShareSeconds.sub(stakingShareSecondsToBurn); totalStakingShares = totalStakingShares.sub(stakingSharesToBurn); // Already set in updateAccounting // _lastAccountingTimestampSec = now; // interactions require(_stakingPool.transfer(msg.sender, amount), 'Cradle: transfer out of staking pool failed'); require(_unlockedPool.transfer(msg.sender, rewardAmount), 'Cradle: transfer out of unlocked pool failed'); emit Unstaked(msg.sender, amount, totalStakedFor(msg.sender), ""); emit TokensClaimed(msg.sender, rewardAmount); require(totalStakingShares == 0 || totalStaked() > 0, "Cradle: Error unstaking. Staking shares exist, but no staking tokens do"); return rewardAmount; } /** * @dev Applies an additional time-bonus to a distribution amount. This is necessary to * encourage long-term deposits instead of constant unstake/restakes. * The bonus-multiplier is the result of a linear function that starts at startBonus and * ends at 100% over bonusPeriodSec, then stays at 100% thereafter. * @param currentRewardTokens The current number of distribution tokens already alotted for this * unstake op. Any bonuses are already applied. * @param stakingShareSeconds The stakingShare-seconds that are being burned for new * distribution tokens. * @param stakeTimeSec Length of time for which the tokens were staked. Needed to calculate * the time-bonus. * @return Updated amount of distribution tokens to award, with any bonus included on the * newly added tokens. */ function computeNewReward(uint256 currentRewardTokens, uint256 stakingShareSeconds, uint256 stakeTimeSec) private view returns (uint256) { uint256 newRewardTokens = totalUnlocked() .mul(stakingShareSeconds) .div(_totalStakingShareSeconds); if (stakeTimeSec >= bonusPeriodSec) { return currentRewardTokens.add(newRewardTokens); } uint256 oneHundredPct = 10**BONUS_DECIMALS; uint256 bonusedReward = startBonus .add(oneHundredPct.sub(startBonus).mul(stakeTimeSec).div(bonusPeriodSec)) .mul(newRewardTokens) .div(oneHundredPct); return currentRewardTokens.add(bonusedReward); } /** * @param addr The user to look up staking information for. * @return The number of staking tokens deposited for addr. */ function totalStakedFor(address addr) public view returns (uint256) { return totalStakingShares > 0 ? totalStaked().mul(_userTotals[addr].stakingShares).div(totalStakingShares) : 0; } /** * @return The total number of deposit tokens staked globally, by all users. */ function totalStaked() public view returns (uint256) { return _stakingPool.balance(); } /** * @dev Note that this application has a staking token as well as a distribution token, which * may be different. This function is required by EIP-900. * @return The deposit token used for staking. */ function token() external view returns (address) { return address(getStakingToken()); } /** * @dev A globally callable function to update the accounting state of the system. * Global state and state for the caller are updated. * @return [0] balance of the locked pool * @return [1] balance of the unlocked pool * @return [2] caller's staking share seconds * @return [3] global staking share seconds * @return [4] Rewards caller has accumulated, optimistically assumes max time-bonus. * @return [5] block timestamp */ function updateAccounting() public returns ( uint256, uint256, uint256, uint256, uint256, uint256) { unlockTokens(); // Global accounting uint256 newStakingShareSeconds = now .sub(_lastAccountingTimestampSec) .mul(totalStakingShares); _totalStakingShareSeconds = _totalStakingShareSeconds.add(newStakingShareSeconds); _lastAccountingTimestampSec = now; // User Accounting UserTotals storage totals = _userTotals[msg.sender]; uint256 newUserStakingShareSeconds = now .sub(totals.lastAccountingTimestampSec) .mul(totals.stakingShares); totals.stakingShareSeconds = totals.stakingShareSeconds .add(newUserStakingShareSeconds); totals.lastAccountingTimestampSec = now; uint256 totalUserRewards = (_totalStakingShareSeconds > 0) ? totalUnlocked().mul(totals.stakingShareSeconds).div(_totalStakingShareSeconds) : 0; return ( totalLocked(), totalUnlocked(), totals.stakingShareSeconds, _totalStakingShareSeconds, totalUserRewards, now ); } /** * @return Total number of locked distribution tokens. */ function totalLocked() public view returns (uint256) { return _lockedPool.balance(); } /** * @return Total number of unlocked distribution tokens. */ function totalUnlocked() public view returns (uint256) { return _unlockedPool.balance(); } /** * @return Number of unlock schedules. */ function unlockScheduleCount() public view returns (uint256) { return unlockSchedules.length; } /** * @dev This funcion allows the contract owner to add more locked distribution tokens, along * with the associated "unlock schedule". These locked tokens immediately begin unlocking * linearly over the duraction of durationSec timeframe. * @param amount Number of distribution tokens to lock. These are transferred from the caller. * @param durationSec Length of time to linear unlock the tokens. */ function lockTokens(uint256 amount, uint256 durationSec) external onlyOwner { require(unlockSchedules.length < _maxUnlockSchedules, 'Cradle: reached maximum unlock schedules'); // Update lockedTokens amount before using it in computations after. updateAccounting(); uint256 lockedTokens = totalLocked(); uint256 mintedLockedShares = (lockedTokens > 0) ? totalLockedShares.mul(amount).div(lockedTokens) : amount.mul(_initialSharesPerToken); UnlockSchedule memory schedule; schedule.initialLockedShares = mintedLockedShares; schedule.lastUnlockTimestampSec = now; schedule.endAtSec = now.add(durationSec); schedule.durationSec = durationSec; unlockSchedules.push(schedule); totalLockedShares = totalLockedShares.add(mintedLockedShares); require(_lockedPool.token().transferFrom(msg.sender, address(_lockedPool), amount), 'Cradle: transfer into locked pool failed'); emit TokensLocked(amount, durationSec, totalLocked()); } /** * @dev Moves distribution tokens from the locked pool to the unlocked pool, according to the * previously defined unlock schedules. Publicly callable. * @return Number of newly unlocked distribution tokens. */ function unlockTokens() public returns (uint256) { uint256 unlockedTokens = 0; uint256 lockedTokens = totalLocked(); if (totalLockedShares == 0) { unlockedTokens = lockedTokens; } else { uint256 unlockedShares = 0; for (uint256 s = 0; s < unlockSchedules.length; s++) { unlockedShares = unlockedShares.add(unlockScheduleShares(s)); } unlockedTokens = unlockedShares.mul(lockedTokens).div(totalLockedShares); totalLockedShares = totalLockedShares.sub(unlockedShares); } if (unlockedTokens > 0) { require(_lockedPool.transfer(address(_unlockedPool), unlockedTokens), 'Cradle: transfer out of locked pool failed'); emit TokensUnlocked(unlockedTokens, totalLocked()); } return unlockedTokens; } /** * @dev Returns the number of unlockable shares from a given schedule. The returned value * depends on the time since the last unlock. This function updates schedule accounting, * but does not actually transfer any tokens. * @param s Index of the unlock schedule. * @return The number of unlocked shares. */ function unlockScheduleShares(uint256 s) private returns (uint256) { UnlockSchedule storage schedule = unlockSchedules[s]; if(schedule.unlockedShares >= schedule.initialLockedShares) { return 0; } uint256 sharesToUnlock = 0; // Special case to handle any leftover dust from integer division if (now >= schedule.endAtSec) { sharesToUnlock = (schedule.initialLockedShares.sub(schedule.unlockedShares)); schedule.lastUnlockTimestampSec = schedule.endAtSec; } else { sharesToUnlock = now.sub(schedule.lastUnlockTimestampSec) .mul(schedule.initialLockedShares) .div(schedule.durationSec); schedule.lastUnlockTimestampSec = now; } schedule.unlockedShares = schedule.unlockedShares.add(sharesToUnlock); return sharesToUnlock; } }
28,012
98
// The preparation time period where a new dungeon is created, before it can be challenged.
uint public dungeonPreparationTime = 60 minutes;
uint public dungeonPreparationTime = 60 minutes;
56,668
17
// This is only called when a new board or a new listing is added, so exposure values will be 0
OptionListingCache storage listingCache = listingCaches[listing.id]; listingCache.id = listing.id; listingCache.strike = listing.strike; listingCache.boardId = listing.boardId; listingCache.skew = listing.skew; boardCache.listings.push(listingId);
OptionListingCache storage listingCache = listingCaches[listing.id]; listingCache.id = listing.id; listingCache.strike = listing.strike; listingCache.boardId = listing.boardId; listingCache.skew = listing.skew; boardCache.listings.push(listingId);
9,713
5
// mapping description of different registries
mapping (string => string) internal registryDescriptions;
mapping (string => string) internal registryDescriptions;
10,788
11
// Using Math.min() since we might free more than needed
_debtPayment = Math.min(_amountFreed, _debtOutstanding);
_debtPayment = Math.min(_amountFreed, _debtOutstanding);
12,258
44
// The scale factor is a crude way to turn everything into integer calcs. Actually do (n10 ^ 4) ^ (1/2)
uint256 _n = n * 10**6; uint256 c = _n; res = _n; uint256 xi; while (true) { xi = (res + c / res) / 2;
uint256 _n = n * 10**6; uint256 c = _n; res = _n; uint256 xi; while (true) { xi = (res + c / res) / 2;
12,028
19
// Agreement account state updated event agreementClass Contract address of the agreement account Account updated slotId slot id of the agreement state /
event AgreementStateUpdated(
event AgreementStateUpdated(
5,039
18
// VNET Token Amount to be transfer
uint256 vnetAmount = weiAmount.mul(ratioNext).div(10 ** 18);
uint256 vnetAmount = weiAmount.mul(ratioNext).div(10 ** 18);
63,000
5
// Choose a member to be the winner
function getWinner() { /** * Block Info Dependency */ uint winnerID = uint(block.blockhash(block.number)) % participants.length; participants[winnerID].send(8 ether); participatorID = 0; }
function getWinner() { /** * Block Info Dependency */ uint winnerID = uint(block.blockhash(block.number)) % participants.length; participants[winnerID].send(8 ether); participatorID = 0; }
17,400
3
// How many decimals does the strike token have? E.g.: 18 /
uint8 public strikeAssetDecimals;
uint8 public strikeAssetDecimals;
8,948
7
// array of all the token tickers
string[] public tokenBridges; bool public isBridgeActive; uint256[100] private __gap;
string[] public tokenBridges; bool public isBridgeActive; uint256[100] private __gap;
10,311
197
// PAYOUT /
function withdraw() public nonReentrant { uint256 balance = address(this).balance; Address.sendValue(payable(owner()), balance); }
function withdraw() public nonReentrant { uint256 balance = address(this).balance; Address.sendValue(payable(owner()), balance); }
51,338
42
// Encode the first byte, followed by the `len` in binary form if `length` is more than 55. len The length of the string or the payload. offset 128 if item is string, 192 if item is list.return RLP encoded bytes. /
function encodeLength(uint len, uint offset) private pure returns (bytes memory) { bytes memory encoded; if (len < 56) { encoded = new bytes(1); encoded[0] = bytes32(len + offset)[31]; } else { uint lenLen; uint i = 1; while (len >= i) { lenLen++; i <<= 8; } encoded = new bytes(lenLen + 1); encoded[0] = bytes32(lenLen + offset + 55)[31]; for(i = 1; i <= lenLen; i++) { encoded[i] = bytes32((len / (256**(lenLen-i))) % 256)[31]; } } return encoded; }
function encodeLength(uint len, uint offset) private pure returns (bytes memory) { bytes memory encoded; if (len < 56) { encoded = new bytes(1); encoded[0] = bytes32(len + offset)[31]; } else { uint lenLen; uint i = 1; while (len >= i) { lenLen++; i <<= 8; } encoded = new bytes(lenLen + 1); encoded[0] = bytes32(lenLen + offset + 55)[31]; for(i = 1; i <= lenLen; i++) { encoded[i] = bytes32((len / (256**(lenLen-i))) % 256)[31]; } } return encoded; }
48,072
6
// events
35,070
263
// If over vesting duration, all tokens vested
if (elapsedTime >= _durationInSeconds) { return token.balanceOf(address(this)); } else {
if (elapsedTime >= _durationInSeconds) { return token.balanceOf(address(this)); } else {
23,413
18
// Disabling fairsale protection
function fairsaleProtectionOFF() onlyOwner { if ( block.number - start_block < 2000) throw; // fairsale window is strictly enforced for the first 2000 blocks fairsaleProtection = false; }
function fairsaleProtectionOFF() onlyOwner { if ( block.number - start_block < 2000) throw; // fairsale window is strictly enforced for the first 2000 blocks fairsaleProtection = false; }
21,935
88
// count of user wallet to check investor should be enlisted /
mapping(address => uint) public userActiveWalletCount;
mapping(address => uint) public userActiveWalletCount;
41,723
39
// Check supply cap
uint supplyCap = supplyCaps[cToken];
uint supplyCap = supplyCaps[cToken];
7,544
6
// Returns the v1 traits associated with a given token ID./Throws if the token ID is not valid./tokenId The ID of the token that represents the Cub/ return traits memory
function traitsV1(uint256 tokenId) external view returns (ICubTraits.TraitsV1 memory traits);
function traitsV1(uint256 tokenId) external view returns (ICubTraits.TraitsV1 memory traits);
57,469
45
// actually retrieve the code, this needs assembly
extcodecopy(who, add(o_code, 0x20), 0, size)
extcodecopy(who, add(o_code, 0x20), 0, size)
28,102
8
// return the total vesting count. /
function vestingCount() public view returns (uint256) { return _vestingCount; }
function vestingCount() public view returns (uint256) { return _vestingCount; }
21,332
96
// Use block UINT256_MAX (which should be never) as the initializable date
uint256 internal constant PETRIFIED_BLOCK = uint256(-1);
uint256 internal constant PETRIFIED_BLOCK = uint256(-1);
16,403
33
// Transfer ERC20 tokens
try this.safeTransferExternal( IERC20Upgradeable(tokenAddress[i]), to[i], amount[i] ) { packPayoutNonce(payoutNonce[i]); emit PayoutSuccessful( tokenAddress[i],
try this.safeTransferExternal( IERC20Upgradeable(tokenAddress[i]), to[i], amount[i] ) { packPayoutNonce(payoutNonce[i]); emit PayoutSuccessful( tokenAddress[i],
20,078
199
// Cache the end of the memory to calculate the length later.
let end := str
let end := str
9,050
44
// Mirror governance contract.
address public override governor;
address public override governor;
46,078
299
// if the earlyBallot was created more than 30 days in the past we should count the new ballot
if (earlyBallotTs < now - 30 days) { return (true, false); }
if (earlyBallotTs < now - 30 days) { return (true, false); }
4,135
15
// The underlying queue data structure stores 2 elements per insertion, so to get the actual desired queue index we need to multiply by 2.
uint40 trueIndex = uint40(_index * 2); bytes32 transactionHash = _queueRef.get(trueIndex); bytes32 timestampAndBlockNumber = _queueRef.get(trueIndex + 1); uint40 elementTimestamp; uint40 elementBlockNumber;
uint40 trueIndex = uint40(_index * 2); bytes32 transactionHash = _queueRef.get(trueIndex); bytes32 timestampAndBlockNumber = _queueRef.get(trueIndex + 1); uint40 elementTimestamp; uint40 elementBlockNumber;
27,900
73
// Minting of new tokens. to The address to mint to. value The amount to be minted. /
function mint(address to, uint256 value) public onlyMinter canMint(value) returns (bool) { _mint(to, value); return true; }
function mint(address to, uint256 value) public onlyMinter canMint(value) returns (bool) { _mint(to, value); return true; }
29,745
214
// returns the day number of the current day, in days since the UNIX epoch. /
function today() public view virtual returns (uint256 dayNumber) { return uint256(block.timestamp / SECONDS_PER_DAY); }
function today() public view virtual returns (uint256 dayNumber) { return uint256(block.timestamp / SECONDS_PER_DAY); }
25,186
6
// Then, compute cost of new memory allocation.
if gt(returnDataWords, msizeWords) { cost := add( cost, add( mul(sub(returnDataWords, msizeWords), CostPerWord), shr( MemoryExpansionCoefficientShift, sub(mul(returnDataWords, returnDataWords), mul(msizeWords, msizeWords)) )
if gt(returnDataWords, msizeWords) { cost := add( cost, add( mul(sub(returnDataWords, msizeWords), CostPerWord), shr( MemoryExpansionCoefficientShift, sub(mul(returnDataWords, returnDataWords), mul(msizeWords, msizeWords)) )
16,444
16
// Получение количества голосваний. /
function getBallotsLengh() public view returns(uint) { return ballots.length; }
function getBallotsLengh() public view returns(uint) { return ballots.length; }
41,150
39
// Allows the current owner to transfer control of the contract to a newOwner.changes the pending owner to newOwner. But doesn't actually transfer newOwner The address to transfer ownership to. /
function transferProxyOwnership(address newOwner) external onlyProxyOwner { require(newOwner != address(0)); _setPendingUpgradeabilityOwner(newOwner); emit NewPendingOwner(proxyOwner(), newOwner); }
function transferProxyOwnership(address newOwner) external onlyProxyOwner { require(newOwner != address(0)); _setPendingUpgradeabilityOwner(newOwner); emit NewPendingOwner(proxyOwner(), newOwner); }
27,426
8
// amount of $HOUSE due for each alpha point staked
uint256 public housePerDagger = 0;
uint256 public housePerDagger = 0;
14,008
125
// 4. GROUP FUNCTIONS/ Function to return group info for an EIN _ein the EIN of the user _groupIndex the index of the groupreturn index is the index of the groupreturn name is the name associated with the group /
function getGroup(uint _ein, uint _groupIndex) external view
function getGroup(uint _ein, uint _groupIndex) external view
36,916
31
// the car registration contract
contract RegisterCar{ // information of car owner string public ownerFirstname; string public ownerLastname; string public ownerBirthdate; string public ownerStreet; string public ownerStreetNumber; string public ownerZipcode; string public ownerCity; //information of car string public licenseTag; // Kennzeichen string public vehicleNumber; // Fahrzeugnummer bytes32 public hashIdentidyCard; // Personalausweis bytes32 public hashCoc; // EG-Uebereinstimmungsbescheinigung string public evbNumber; // elektronische Versicherungsbestaetigung bytes32 public hashCertRegistration; // Fahrzeugschein/Zulassungsbescheinigung Teil 1 bytes32 public hashCertTitle; // Fahrzeugbrief/Zulassungsbescheinigung Teil 2 bytes32 public hashHu; // Hu-Bericht address public insuranceLookup; address public policeLookup; //information of uint public submitTime; uint public updateTime; enum State { submitted, incomplete, accepted, declined, canceled } State public state; // initialize contract with all required information function RegisterCar( // information of car owner string _ownerFirstname, string _ownerLastname, string _ownerBirthdate, string _ownerStreet, string _ownerStreetNumber, string _ownerZipcode, string _ownerCity, // information of car string _vehicleNumber, // Fahrzeugnummer string _evbNumber, // elektronische Versicherungsbestaetigung bytes32 _hashIdentidyCard, // Personalausweis bytes32 _hashCoc, // EG-UebereinstimmungsbescheinigungEg bytes32 _hashCertRegistration, // Fahrzeugschein/Zulassungsbescheinigung Teil 1 bytes32 _hashCertTitle, // Fahrzeugbrief/Zulassungsbescheinigung Teil 2 bytes32 _hashHu, address _insuranceLookup ){ ownerFirstname = _ownerFirstname; ownerLastname = _ownerLastname; ownerBirthdate = _ownerBirthdate; ownerStreet = _ownerStreet; ownerStreetNumber = _ownerStreetNumber; ownerZipcode = _ownerZipcode; ownerCity = _ownerCity; // information of car vehicleNumber =_vehicleNumber; hashIdentidyCard = _hashIdentidyCard; hashCoc =_hashCoc; evbNumber = _evbNumber; hashCertRegistration = _hashCertRegistration; hashCertTitle = _hashCertTitle; hashHu = _hashHu; submitTime = now; updateTime = now; state = State.submitted; // register self to the insuranceLookup contract insuranceLookup = _insuranceLookup; AbstractMapping(insuranceLookup).update(sha3(evbNumber), this); } function setOwnerFirstname( string _ownerFirstname){ ownerFirstname = _ownerFirstname; } function setOwnerLastname( string _ownerLastname){ ownerLastname = _ownerLastname; } function setOwnerBirthdate( string _ownerBirthdate){ ownerBirthdate = _ownerBirthdate; } function setOwnerStreet( string _ownerStreet){ ownerStreet = _ownerStreet; } function setOwnerStreetNumber( string _ownerStreetNumber){ ownerStreetNumber = _ownerStreetNumber; } function setOwnerZipcode( string _ownerZipcode){ ownerZipcode = _ownerZipcode; } function setOwnerCity( string _ownerCity){ ownerCity = _ownerCity; } function setVehicleNumber( string _vehicleNumber){ vehicleNumber = _vehicleNumber; } function setHashIdentidyCard( bytes32 _hashIdentidyCard){ hashIdentidyCard = _hashIdentidyCard; } function setHashCoc( bytes32 _hashCoc){ hashCoc = _hashCoc; } function setEvbNumber( string _evbNumber){ evbNumber = _evbNumber; AbstractMapping(insuranceLookup).update(sha3(evbNumber), this); } function setHashCertRegistration() returns( bytes32 _hashCertRegistration){ hashCertRegistration = _hashCertRegistration; } function setHashCertTitle() returns( bytes32 _hashCertTitle){ hashCertTitle = _hashCertTitle; } function setHashHu( bytes32 _hashHu){ hashHu = _hashHu; } function setSubmitTime( uint _submitTime){ submitTime = _submitTime; } function accept( string _licenseTag, address _policeLookup) { updateTime = now; licenseTag = _licenseTag; state = State.accepted; // register self to the policeLookup contract policeLookup = _policeLookup; AbstractMapping(policeLookup).update(sha3(licenseTag), this); } function incomplete() { updateTime = now; state = State.incomplete; } function decline() { updateTime = now; state = State.declined; } function cancel() { updateTime = now; state = State.canceled; } }
contract RegisterCar{ // information of car owner string public ownerFirstname; string public ownerLastname; string public ownerBirthdate; string public ownerStreet; string public ownerStreetNumber; string public ownerZipcode; string public ownerCity; //information of car string public licenseTag; // Kennzeichen string public vehicleNumber; // Fahrzeugnummer bytes32 public hashIdentidyCard; // Personalausweis bytes32 public hashCoc; // EG-Uebereinstimmungsbescheinigung string public evbNumber; // elektronische Versicherungsbestaetigung bytes32 public hashCertRegistration; // Fahrzeugschein/Zulassungsbescheinigung Teil 1 bytes32 public hashCertTitle; // Fahrzeugbrief/Zulassungsbescheinigung Teil 2 bytes32 public hashHu; // Hu-Bericht address public insuranceLookup; address public policeLookup; //information of uint public submitTime; uint public updateTime; enum State { submitted, incomplete, accepted, declined, canceled } State public state; // initialize contract with all required information function RegisterCar( // information of car owner string _ownerFirstname, string _ownerLastname, string _ownerBirthdate, string _ownerStreet, string _ownerStreetNumber, string _ownerZipcode, string _ownerCity, // information of car string _vehicleNumber, // Fahrzeugnummer string _evbNumber, // elektronische Versicherungsbestaetigung bytes32 _hashIdentidyCard, // Personalausweis bytes32 _hashCoc, // EG-UebereinstimmungsbescheinigungEg bytes32 _hashCertRegistration, // Fahrzeugschein/Zulassungsbescheinigung Teil 1 bytes32 _hashCertTitle, // Fahrzeugbrief/Zulassungsbescheinigung Teil 2 bytes32 _hashHu, address _insuranceLookup ){ ownerFirstname = _ownerFirstname; ownerLastname = _ownerLastname; ownerBirthdate = _ownerBirthdate; ownerStreet = _ownerStreet; ownerStreetNumber = _ownerStreetNumber; ownerZipcode = _ownerZipcode; ownerCity = _ownerCity; // information of car vehicleNumber =_vehicleNumber; hashIdentidyCard = _hashIdentidyCard; hashCoc =_hashCoc; evbNumber = _evbNumber; hashCertRegistration = _hashCertRegistration; hashCertTitle = _hashCertTitle; hashHu = _hashHu; submitTime = now; updateTime = now; state = State.submitted; // register self to the insuranceLookup contract insuranceLookup = _insuranceLookup; AbstractMapping(insuranceLookup).update(sha3(evbNumber), this); } function setOwnerFirstname( string _ownerFirstname){ ownerFirstname = _ownerFirstname; } function setOwnerLastname( string _ownerLastname){ ownerLastname = _ownerLastname; } function setOwnerBirthdate( string _ownerBirthdate){ ownerBirthdate = _ownerBirthdate; } function setOwnerStreet( string _ownerStreet){ ownerStreet = _ownerStreet; } function setOwnerStreetNumber( string _ownerStreetNumber){ ownerStreetNumber = _ownerStreetNumber; } function setOwnerZipcode( string _ownerZipcode){ ownerZipcode = _ownerZipcode; } function setOwnerCity( string _ownerCity){ ownerCity = _ownerCity; } function setVehicleNumber( string _vehicleNumber){ vehicleNumber = _vehicleNumber; } function setHashIdentidyCard( bytes32 _hashIdentidyCard){ hashIdentidyCard = _hashIdentidyCard; } function setHashCoc( bytes32 _hashCoc){ hashCoc = _hashCoc; } function setEvbNumber( string _evbNumber){ evbNumber = _evbNumber; AbstractMapping(insuranceLookup).update(sha3(evbNumber), this); } function setHashCertRegistration() returns( bytes32 _hashCertRegistration){ hashCertRegistration = _hashCertRegistration; } function setHashCertTitle() returns( bytes32 _hashCertTitle){ hashCertTitle = _hashCertTitle; } function setHashHu( bytes32 _hashHu){ hashHu = _hashHu; } function setSubmitTime( uint _submitTime){ submitTime = _submitTime; } function accept( string _licenseTag, address _policeLookup) { updateTime = now; licenseTag = _licenseTag; state = State.accepted; // register self to the policeLookup contract policeLookup = _policeLookup; AbstractMapping(policeLookup).update(sha3(licenseTag), this); } function incomplete() { updateTime = now; state = State.incomplete; } function decline() { updateTime = now; state = State.declined; } function cancel() { updateTime = now; state = State.canceled; } }
5,295
2
// Emits a {Transfer} event. /
function transfer(address recipient, uint256 amount) external returns (bool);
function transfer(address recipient, uint256 amount) external returns (bool);
2,035
46
// Send the ETH to where admins agree upon.
_safe.transfer(this.balance);
_safe.transfer(this.balance);
20,083
19
// Returns the integer division of two unsigned integers. Reverts with custom message ondivision by zero. The result is rounded towards zero. Counterpart to Solidity's `/` operator. Note: this function uses a`revert` opcode (which leaves remaining gas untouched) while Solidityuses an invalid opcode to revert (consuming all remaining gas). Requirements:- The divisor cannot be zero. /
function div( uint256 a, uint256 b, string memory errorMessage
function div( uint256 a, uint256 b, string memory errorMessage
13,863
10
// Info of each user that stakes Staking tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
31,829
15
// claim from main curve LP pools
for(uint256 i = 0; i < rewardContracts.length; i++){ IBasicRewards(rewardContracts[i]).getReward(msg.sender,true); }
for(uint256 i = 0; i < rewardContracts.length; i++){ IBasicRewards(rewardContracts[i]).getReward(msg.sender,true); }
1,901
98
// the Metadata extension. Built to optimize for lower gas during batch mints and non serialized minting such as for migration/non sequence minting. Assumes that an owner cannot have more than 264 - 1 (max value of uint64) of supply. Assumes that the maximum token id cannot exceed 2256 - 1 (max value of uint256). /
contract ERC721SW is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; //used to figure out gaps with non sequened minting... uint64 quantity; //uint64 should suffice as projects using this will not have a single user have a supply greater than 2**64-1 } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 1; } function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } function tokenByIndex(uint256 index) public view returns (uint256) { if (index > totalSupply()) revert ExceedsCurrentSupply(); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { if (index > balanceOf(owner)) revert IndexExceedsOwnerBounds(); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); uint256 currentOwnershipSize = 0; uint256 currTokensPassed = 0; for (uint256 tokenId = 0; tokenId < numMintedSoFar; tokenId++) { TokenOwnership memory ownership = _ownerships[tokenId]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; currentOwnershipSize = ownership.quantity; currTokensPassed = 0; } if (currOwnershipAddr == owner && (currTokensPassed < currentOwnershipSize)) { if ((tokenIdsIdx == index)) { return tokenId; } tokenIdsIdx++; currTokensPassed++; } } revert OwnerQueryForNonexistentToken(); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; uint256 skipped = 0; unchecked { if ((_startTokenId() <= curr) && (curr < _currentIndex)) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; skipped++; ownership = _ownerships[curr]; if ( (ownership.addr != address(0)) && (ownership.quantity > (tokenId - curr)) ) { return ownership; } else if (_startTokenId() > curr) { //incase it cant find to avoid infinite loop.. break; } else if (skipped > 16) { break; } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721SW.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if ( to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data) ) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { uint256 curr = tokenId; unchecked { if ((_startTokenId() <= curr) && (curr < _currentIndex)) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return true; } uint256 TotalChecked = 0; while (true) { curr--; ownership = _ownerships[curr]; TotalChecked += 1; if ( (ownership.addr != address(0)) && (ownership.quantity > (tokenId - curr)) ) { return true; } else if (_startTokenId() > curr) { //incase it cant find to avoid infinite loop.. break; } else if (TotalChecked > 15) { break; } } } } return false; } function _safeMint( address to, uint256 quantity, uint256 startingAddress ) internal { _safeMint(to, quantity, "", startingAddress); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data, uint256 startingAddress ) internal { _mint(to, quantity, _data, true, startingAddress); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe, uint256 startingAddress ) internal { uint256 startTokenId = startingAddress; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); if (quantity > 15) revert ExceedsAllowedBatch(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].quantity = uint64(quantity); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (_exists(updatedIndex)) revert(); if ( !_checkContractOnERC721Received( address(0), to, updatedIndex++, _data ) ) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } if (_currentIndex == startingAddress) { _currentIndex = updatedIndex; } } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; uint64 qtyLeft = 0; if (currSlot.addr != address(0)) { qtyLeft = currSlot.quantity-1; } currSlot.addr = to; uint256 nextTokenId = tokenId + 1; uint256 curr = tokenId; uint256 amountSeen = 0; if ((_startTokenId() <= curr) && (curr < _currentIndex) && (qtyLeft == 0)) { while (true) { curr--; amountSeen++; TokenOwnership storage ownership = _ownerships[curr]; if ( (ownership.addr != address(0)) && (ownership.quantity > (tokenId - curr)) && (ownership.quantity > 0) ) { uint128 amountLeft = (ownership.quantity-uint128(tokenId - curr))-1; ownership.quantity -= 1; qtyLeft = uint64(amountLeft); break; } else if (_startTokenId() > curr) { //incase it cant find to avoid infinite loop.. break; } else if (amountSeen > 16) { break; } } } TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0) && (qtyLeft > 0)) { // This will suffice for checking _exists(nextTokenId), if (nextTokenId != _currentIndex+1) { nextSlot.addr = from; nextSlot.quantity = qtyLeft; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
contract ERC721SW is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; //used to figure out gaps with non sequened minting... uint64 quantity; //uint64 should suffice as projects using this will not have a single user have a supply greater than 2**64-1 } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 1; } function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } function tokenByIndex(uint256 index) public view returns (uint256) { if (index > totalSupply()) revert ExceedsCurrentSupply(); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { if (index > balanceOf(owner)) revert IndexExceedsOwnerBounds(); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); uint256 currentOwnershipSize = 0; uint256 currTokensPassed = 0; for (uint256 tokenId = 0; tokenId < numMintedSoFar; tokenId++) { TokenOwnership memory ownership = _ownerships[tokenId]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; currentOwnershipSize = ownership.quantity; currTokensPassed = 0; } if (currOwnershipAddr == owner && (currTokensPassed < currentOwnershipSize)) { if ((tokenIdsIdx == index)) { return tokenId; } tokenIdsIdx++; currTokensPassed++; } } revert OwnerQueryForNonexistentToken(); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; uint256 skipped = 0; unchecked { if ((_startTokenId() <= curr) && (curr < _currentIndex)) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; skipped++; ownership = _ownerships[curr]; if ( (ownership.addr != address(0)) && (ownership.quantity > (tokenId - curr)) ) { return ownership; } else if (_startTokenId() > curr) { //incase it cant find to avoid infinite loop.. break; } else if (skipped > 16) { break; } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721SW.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if ( to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data) ) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { uint256 curr = tokenId; unchecked { if ((_startTokenId() <= curr) && (curr < _currentIndex)) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return true; } uint256 TotalChecked = 0; while (true) { curr--; ownership = _ownerships[curr]; TotalChecked += 1; if ( (ownership.addr != address(0)) && (ownership.quantity > (tokenId - curr)) ) { return true; } else if (_startTokenId() > curr) { //incase it cant find to avoid infinite loop.. break; } else if (TotalChecked > 15) { break; } } } } return false; } function _safeMint( address to, uint256 quantity, uint256 startingAddress ) internal { _safeMint(to, quantity, "", startingAddress); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data, uint256 startingAddress ) internal { _mint(to, quantity, _data, true, startingAddress); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe, uint256 startingAddress ) internal { uint256 startTokenId = startingAddress; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); if (quantity > 15) revert ExceedsAllowedBatch(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].quantity = uint64(quantity); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (_exists(updatedIndex)) revert(); if ( !_checkContractOnERC721Received( address(0), to, updatedIndex++, _data ) ) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } if (_currentIndex == startingAddress) { _currentIndex = updatedIndex; } } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; uint64 qtyLeft = 0; if (currSlot.addr != address(0)) { qtyLeft = currSlot.quantity-1; } currSlot.addr = to; uint256 nextTokenId = tokenId + 1; uint256 curr = tokenId; uint256 amountSeen = 0; if ((_startTokenId() <= curr) && (curr < _currentIndex) && (qtyLeft == 0)) { while (true) { curr--; amountSeen++; TokenOwnership storage ownership = _ownerships[curr]; if ( (ownership.addr != address(0)) && (ownership.quantity > (tokenId - curr)) && (ownership.quantity > 0) ) { uint128 amountLeft = (ownership.quantity-uint128(tokenId - curr))-1; ownership.quantity -= 1; qtyLeft = uint64(amountLeft); break; } else if (_startTokenId() > curr) { //incase it cant find to avoid infinite loop.. break; } else if (amountSeen > 16) { break; } } } TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0) && (qtyLeft > 0)) { // This will suffice for checking _exists(nextTokenId), if (nextTokenId != _currentIndex+1) { nextSlot.addr = from; nextSlot.quantity = qtyLeft; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
39,733
2
// emitted when a representation token contract is deployed domain the domain of the chain where the canonical asset is deployed id the bytes32 address of the canonical token contract representation the address of the newly locally deployed representation contract /
event TokenDeployed(uint32 indexed domain, bytes32 indexed id, address indexed representation);
event TokenDeployed(uint32 indexed domain, bytes32 indexed id, address indexed representation);
19,206
50
// Bulk function for updating pools - loops throughall pools saved inside the poolTokenAddresses array. /
function syncAllPools() external
function syncAllPools() external
1,365
47
// Run mass transfers with pre-ico 2 bonus /
function proceedPreIcoTransactions(address[] toArray, uint[] valueArray) onlyOwner() { uint tokens = 0; address to = 0x0; uint value = 0; for (uint i = 0; i < toArray.length; i++) { to = toArray[i]; value = valueArray[i]; tokens = value / price(); tokens = tokens + tokens; balances[to] = safeAdd(balances[to], safeMul(tokens, multiplier)); balances[owner] = safeSub(balances[owner], safeMul(tokens, multiplier)); preIcoSold = safeAdd(preIcoSold, tokens); sendEvents(to, value, tokens); } }
function proceedPreIcoTransactions(address[] toArray, uint[] valueArray) onlyOwner() { uint tokens = 0; address to = 0x0; uint value = 0; for (uint i = 0; i < toArray.length; i++) { to = toArray[i]; value = valueArray[i]; tokens = value / price(); tokens = tokens + tokens; balances[to] = safeAdd(balances[to], safeMul(tokens, multiplier)); balances[owner] = safeSub(balances[owner], safeMul(tokens, multiplier)); preIcoSold = safeAdd(preIcoSold, tokens); sendEvents(to, value, tokens); } }
37,391
159
// divide the `asset` sellAmount by the target premium per oToken to get the number of oTokens to buy (8 decimals)
buyAmount = sellAmount .mul(10**(bidDetails.assetDecimals.add(Vault.OTOKEN_DECIMALS))) .div(bidDetails.optionPremium) .div(10**bidDetails.assetDecimals); require( sellAmount <= type(uint96).max, "sellAmount > type(uint96) max value!" ); require(
buyAmount = sellAmount .mul(10**(bidDetails.assetDecimals.add(Vault.OTOKEN_DECIMALS))) .div(bidDetails.optionPremium) .div(10**bidDetails.assetDecimals); require( sellAmount <= type(uint96).max, "sellAmount > type(uint96) max value!" ); require(
13,644
46
// unstake function for layer1 stakes
// @param sessionID {uint256} - id of the layer 1 stake function unstakeV1(uint256 sessionId) external pausable { //lastSessionIdv1 is the last stake ID from v1 layer require(sessionId <= lastSessionIdV1, 'Staking: Invalid sessionId'); Session storage session = sessionDataOf[msg.sender][sessionId]; // Unstaked already require( session.shares == 0 && session.withdrawn == false, 'Staking: Stake withdrawn' ); ( uint256 amount, uint256 start, uint256 end, uint256 shares, uint256 firstPayout ) = stakingV1.sessionDataOf(msg.sender, sessionId); // Unstaked in v1 / doesn't exist require(shares != 0, 'Staking: Stake withdrawn or not set'); uint256 stakingDays = (end - start) / stepTimestamp; uint256 lastPayout = stakingDays + firstPayout; uint256 actualEnd = now; //calculate amount to be paid uint256 amountOut = unstakeV1Internal( sessionId, amount, start, end, actualEnd, shares, firstPayout, lastPayout, stakingDays ); // To account _initPayout(msg.sender, amountOut); }
// @param sessionID {uint256} - id of the layer 1 stake function unstakeV1(uint256 sessionId) external pausable { //lastSessionIdv1 is the last stake ID from v1 layer require(sessionId <= lastSessionIdV1, 'Staking: Invalid sessionId'); Session storage session = sessionDataOf[msg.sender][sessionId]; // Unstaked already require( session.shares == 0 && session.withdrawn == false, 'Staking: Stake withdrawn' ); ( uint256 amount, uint256 start, uint256 end, uint256 shares, uint256 firstPayout ) = stakingV1.sessionDataOf(msg.sender, sessionId); // Unstaked in v1 / doesn't exist require(shares != 0, 'Staking: Stake withdrawn or not set'); uint256 stakingDays = (end - start) / stepTimestamp; uint256 lastPayout = stakingDays + firstPayout; uint256 actualEnd = now; //calculate amount to be paid uint256 amountOut = unstakeV1Internal( sessionId, amount, start, end, actualEnd, shares, firstPayout, lastPayout, stakingDays ); // To account _initPayout(msg.sender, amountOut); }
51,020
35
// Burn function used to burn the securityToken _value No. of token that get burned /
function burn(uint256 _value) public; event Minted(address indexed to, uint256 amount); event Burnt(address indexed _burner, uint256 _value);
function burn(uint256 _value) public; event Minted(address indexed to, uint256 amount); event Burnt(address indexed _burner, uint256 _value);
50,093
159
// uint256 royaltyPayment
payments[1] = calcRoyaltyPayment( _isPrimarySale, _amount, _royaltyPercentage );
payments[1] = calcRoyaltyPayment( _isPrimarySale, _amount, _royaltyPercentage );
57,510
24
// require(_value <= balances[msg.sender]);
require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true;
require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true;
15,491
34
// Set reduce token amount on total reward tokens
function setReduceTokenAmount(uint256 _amount) external onlyOwner { require(_amount <= (totalRewardTokens - soldAmount), "Wrong amount"); reduceTokenAmount = _amount; }
function setReduceTokenAmount(uint256 _amount) external onlyOwner { require(_amount <= (totalRewardTokens - soldAmount), "Wrong amount"); reduceTokenAmount = _amount; }
18,335
204
// Swap using a swapper freely chosen by the caller Open (flash) liquidation: get proceeds first and provide the borrow after
vase.transfer(cloneInfo.collateral, address(this), to, allCollateralShare); if (swapper != address(0)) { ISwapper(swapper).swap(IERC20(cloneInfo.collateral), roseUsd, msg.sender, allBorrowShare, allCollateralShare); }
vase.transfer(cloneInfo.collateral, address(this), to, allCollateralShare); if (swapper != address(0)) { ISwapper(swapper).swap(IERC20(cloneInfo.collateral), roseUsd, msg.sender, allBorrowShare, allCollateralShare); }
32,908
29
// Internal function that mints an amount of the token and assigns it toan account. This encapsulates the modification of balances such that theproper events are emitted. account The account that will receive the created tokens. value The amount that will be created. /
function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); }
function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); }
448
20
// Change address that collects payments for listing tokens./Can be called only by zkSync governor
function setTreasury(address _newTreasury) external { governance.requireGovernor(msg.sender); treasury = _newTreasury; emit TreasuryUpdate(_newTreasury); }
function setTreasury(address _newTreasury) external { governance.requireGovernor(msg.sender); treasury = _newTreasury; emit TreasuryUpdate(_newTreasury); }
54,566
181
// send some amount of arbitrary ERC20 Tokens_externalToken the address of the Token Contract_to address of the beneficiary_value the amount of ether (in Wei) to send_avatar the organization avatar. return bool which represents a success/
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar) external onlyRegisteredScheme(address(_avatar)) onlySubjectToConstraint("externalTokenTransfer", address(_avatar)) returns(bool)
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar) external onlyRegisteredScheme(address(_avatar)) onlySubjectToConstraint("externalTokenTransfer", address(_avatar)) returns(bool)
27,853
54
// Return the setting type valuesreturn The setting type value for addressreturn The setting type value for boolreturn The setting type value for bytesreturn The setting type value for stringreturn The setting type value for uint /
function getSettingTypes() external view returns (uint8, uint8, uint8, uint8, uint8) { return ( ADDRESS_SETTING_TYPE, BOOL_SETTING_TYPE, BYTES_SETTING_TYPE, STRING_SETTING_TYPE, UINT_SETTING_TYPE ); }
function getSettingTypes() external view returns (uint8, uint8, uint8, uint8, uint8) { return ( ADDRESS_SETTING_TYPE, BOOL_SETTING_TYPE, BYTES_SETTING_TYPE, STRING_SETTING_TYPE, UINT_SETTING_TYPE ); }
26,022
208
// verification: for each token to be minted
for(uint256 i = 0; i < n; i++) {
for(uint256 i = 0; i < n; i++) {
42,817
13
// Token data
mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowanceOf; uint public totalSupply = 100000;
mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowanceOf; uint public totalSupply = 100000;
9,003
4
// Set Mint Price /
function setMintPrice(uint256 newMintPrice) external onlyOwner { mintPrice = newMintPrice; }
function setMintPrice(uint256 newMintPrice) external onlyOwner { mintPrice = newMintPrice; }
29,244
7
// "SPDX-License-Identifier: UNLICENSED "/ SafeMath Math operations with safety checks that throw on error /
library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function ceil(uint a, uint m) internal pure returns (uint r) { return (a + m - 1) / m * m; } }
library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function ceil(uint a, uint m) internal pure returns (uint r) { return (a + m - 1) / m * m; } }
12,275
10
// handle the payment for tokens in ETH and LINK withLink boolean flag for paying with LINK instead of ETH amount payed from address /
function handlePayment(bool withLink, uint256 amount, address from) internal { // determine the current phase of the token sale if (_tokenIds.current() < ARTIST_PRINTS) { require(hasRole(ARTIST_ROLE, from), "Only the admin can mint the alpha tokens. Wait your turn FFS"); // } else if (_tokenIds.current() < BETA_SALE) { // TODO: setup beta sale auction and pricing } else { uint256 price = withLink ? currentLinkPrice() : currentPrice(); require(amount >= price, "insuficient payment"); // give change if they over pay if (amount > price) { if (withLink) LINK_TOKEN.transfer(from, amount - price); else msg.sender.transfer(amount - price); } } }
function handlePayment(bool withLink, uint256 amount, address from) internal { // determine the current phase of the token sale if (_tokenIds.current() < ARTIST_PRINTS) { require(hasRole(ARTIST_ROLE, from), "Only the admin can mint the alpha tokens. Wait your turn FFS"); // } else if (_tokenIds.current() < BETA_SALE) { // TODO: setup beta sale auction and pricing } else { uint256 price = withLink ? currentLinkPrice() : currentPrice(); require(amount >= price, "insuficient payment"); // give change if they over pay if (amount > price) { if (withLink) LINK_TOKEN.transfer(from, amount - price); else msg.sender.transfer(amount - price); } } }
47,093
90
// transfer the tokens -- this verifies the sender owns the tokens
transfer(s.receiptAddress, _tokenValue);
transfer(s.receiptAddress, _tokenValue);
23,595
119
// binary search of the value in the array
while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].epochId <= epochId) { min = mid; } else {
while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].epochId <= epochId) { min = mid; } else {
16,300
1
// Returns the address of the RelayHub instance this recipient interacts with. /
function getHubAddr() public view returns (address); function acceptRelayedCall( address relay, address from, bytes calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce,
function getHubAddr() public view returns (address); function acceptRelayedCall( address relay, address from, bytes calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce,
23,358
2
// Initializes factory with address of implementation logic/_implementation SingleEditionMintable logic implementation contract to clone
constructor(address _implementation) { implementation = _implementation; }
constructor(address _implementation) { implementation = _implementation; }
14,802
1
// solhint-disable-next-line func-name-mixedcase
function __TokenageERC20GovernanceToken_init( address adminAddress, string memory name, string memory symbol, uint256 totalSupply, uint8 decimals
function __TokenageERC20GovernanceToken_init( address adminAddress, string memory name, string memory symbol, uint256 totalSupply, uint8 decimals
34,324
33
// Emitted when fiefdom token is transferred to a new owner/previousOwner Previous owner of fiefdom token/newOwner New owner of fiefdom token
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
7,894
303
// maxNumber
uint8 public maxNumber;
uint8 public maxNumber;
11,497
45
// IMPLEMENTATION: allowContract
function _allowContract(address targetContract, address adapter) internal {
function _allowContract(address targetContract, address adapter) internal {
28,793
40
// User is always authorized to transfer SGR from one user to another user. _sender The address of the custodian user. _source The address of the source user. _target The address of the target user.return Authorization status. /
function isAuthorizedToTransferFrom(address _sender, address _source, address _target) external view returns (bool) { _sender; _source; _target; return true; }
function isAuthorizedToTransferFrom(address _sender, address _source, address _target) external view returns (bool) { _sender; _source; _target; return true; }
56,260
21
// The time that the auction started
uint256 startTime;
uint256 startTime;
15,747
3
// address[] addrSet;
mapping(address =>PersonalStruct) addressToStruct; mapping(uint =>PersonalStruct) indexToStruct; event StorageF(uint t0); event ShowList(uint[] uintSet, string[] strSet);
mapping(address =>PersonalStruct) addressToStruct; mapping(uint =>PersonalStruct) indexToStruct; event StorageF(uint t0); event ShowList(uint[] uintSet, string[] strSet);
33,716
11
// Funders
function numberOfFunders() public view returns (uint256){ return funders.length; }
function numberOfFunders() public view returns (uint256){ return funders.length; }
28,904
1
// Returns the original creator of the collection. /
function creatorOf(address collectionAddress) external returns (address creator);
function creatorOf(address collectionAddress) external returns (address creator);
48,701
1
// Controller hook to provide notifications & rule validations on token transfers to the controller./ This includes minting and burning./from Address of the account sending the tokens (address(0x0) on minting)/to Address of the account receiving the tokens (address(0x0) on burning)/amount Amount of tokens being transferred
function beforeTokenTransfer(address from, address to, uint256 amount) external;
function beforeTokenTransfer(address from, address to, uint256 amount) external;
9,093
7
// Sets the owner of the account. /
function setOwner(Data storage self, address owner) internal { self.owner = owner; }
function setOwner(Data storage self, address owner) internal { self.owner = owner; }
25,778
212
// Increment dev fund by tax
devFund = devFund.add(taxedAmount);
devFund = devFund.add(taxedAmount);
18,558
0
// Initialize hand map
handMap[0] = bytes32("No traits"); handMap[1] = bytes32("Bug You"); handMap[2] = bytes32("Smoke"); handMap[3] = bytes32("Money Talk"); handMap[4] = bytes32("Bug Spray"); handMap[5] = bytes32("Camcorder"); handMap[6] = bytes32("Golf Club"); handMap[7] = bytes32("Spicey"); handMap[8] = bytes32("Genius"); handMap[9] = bytes32("All In");
handMap[0] = bytes32("No traits"); handMap[1] = bytes32("Bug You"); handMap[2] = bytes32("Smoke"); handMap[3] = bytes32("Money Talk"); handMap[4] = bytes32("Bug Spray"); handMap[5] = bytes32("Camcorder"); handMap[6] = bytes32("Golf Club"); handMap[7] = bytes32("Spicey"); handMap[8] = bytes32("Genius"); handMap[9] = bytes32("All In");
45,635
10
// Indicates if the crowdsale has been ended already
bool public crowdsaleEnded = false;
bool public crowdsaleEnded = false;
33,429
156
// function {createConfigHash} Create the config hashmetaId_ The drop Id being approved salt_ Salt for create2 erc20Config_ ERC20 configuration messageTimeStamp_ When the message for this config hash was signed lockerFee_ The fee for the unicrypt locker deploymentFee_ The fee for deployment, if any deployer_ Address performing the deploymentreturn configHash_ The bytes32 config hash /
function createConfigHash(
function createConfigHash(
11,369
11
// _siloToken silo token address/_recipient wallet address that is vesting token allocation/_vestingAmount amount of token that is being allocated for vesting/_vestingBegin timestamp of vesting start date/_vestingCliff timestamp of vesting cliff, aka. the time before which token cannot be claimed/_vestingEnd timestamp of vesting end date/_revocable can it be revoked by owner
constructor( address _siloToken, address _recipient, uint256 _vestingAmount, uint256 _vestingBegin, uint256 _vestingCliff, uint256 _vestingEnd, bool _revocable
constructor( address _siloToken, address _recipient, uint256 _vestingAmount, uint256 _vestingBegin, uint256 _vestingCliff, uint256 _vestingEnd, bool _revocable
29,455
15
// Mark the message as received if the call was successful. Ensures that a message can be relayed multiple times in the case that the call reverted.
if (success == true) { successfulMessages[xDomainCalldataHash] = true; emit RelayedMessage(xDomainCalldataHash); }
if (success == true) { successfulMessages[xDomainCalldataHash] = true; emit RelayedMessage(xDomainCalldataHash); }
85,400
7
// Burn TCO2 on behalf of a user. msg.sender does not require approval/ by the account for the burn to be successfull. This function is exposed so it/ can be utilized in cross-chain transfers of TCO2 where we want to burn the/ TCO2 in the source chain but not retire it./account The user for whom to burn TCO2/amount The amount to burn.
function bridgeBurn(address account, uint256 amount) external virtual whenNotPaused onlyBridges
function bridgeBurn(address account, uint256 amount) external virtual whenNotPaused onlyBridges
19,844
8
// payable
function freeMint( uint16 quantity, bytes calldata signature ) external payable{ MintConfig memory cfg = CONFIG; require( cfg.isActive, "sale is not active" ); require( claimed[ msg.sender ] + quantity <= cfg.maxClaims, "don't be greedy" ); require( _isAuthorizedSigner( "1", signature ), "not authorized for badge mints" ); PRINCIPAL.mintTo{ value: msg.value }( _asArray( quantity ), _asArray( msg.sender )); }
function freeMint( uint16 quantity, bytes calldata signature ) external payable{ MintConfig memory cfg = CONFIG; require( cfg.isActive, "sale is not active" ); require( claimed[ msg.sender ] + quantity <= cfg.maxClaims, "don't be greedy" ); require( _isAuthorizedSigner( "1", signature ), "not authorized for badge mints" ); PRINCIPAL.mintTo{ value: msg.value }( _asArray( quantity ), _asArray( msg.sender )); }
935
119
// 1 ability point to random ability (attack power or defence power)
(pointsGiven, pointsToAttackPower) = _getPoints(1); _attackCompleted(enemyChamp, myChamp, pointsGiven, pointsToAttackPower); emit Attack(enemyChamp.id, myChamp.id, false);
(pointsGiven, pointsToAttackPower) = _getPoints(1); _attackCompleted(enemyChamp, myChamp, pointsGiven, pointsToAttackPower); emit Attack(enemyChamp.id, myChamp.id, false);
39,096
242
// If there is a Default Position and no external positions, remove the component
if (!hasExternalPosition(_setToken, _component)) { _setToken.removeComponent(_component); }
if (!hasExternalPosition(_setToken, _component)) { _setToken.removeComponent(_component); }
22,207
12
// The router configuration
function updateConfig(Config memory config) public onlyOwner { s_config = config; emit ConfigUpdated(config); }
function updateConfig(Config memory config) public onlyOwner { s_config = config; emit ConfigUpdated(config); }
24,252
45
// Get size of users. return The size of users./
function userSize() external view whenNotPaused _onlyReaderOrHigher _checkUserAddr returns (uint) { return InsuranceUser(userAddr_).size(); }
function userSize() external view whenNotPaused _onlyReaderOrHigher _checkUserAddr returns (uint) { return InsuranceUser(userAddr_).size(); }
19,709
58
// Library /
function _createFlow(address to, int96 flowRate) internal { _host.callAgreement( _cfa, abi.encodeWithSelector( _cfa.createFlow.selector, _acceptedToken, to, flowRate, new bytes(0) // placeholder ), "0x" ); }
function _createFlow(address to, int96 flowRate) internal { _host.callAgreement( _cfa, abi.encodeWithSelector( _cfa.createFlow.selector, _acceptedToken, to, flowRate, new bytes(0) // placeholder ), "0x" ); }
47,277
97
// finalizing contract with returning of ownership to developers address /
function finalization() internal { super.finalization(); MintableToken(token).transferOwnership(0x57F8FFD76e9F90Ed945E3dB07F8f43b8e4B8E45d); }
function finalization() internal { super.finalization(); MintableToken(token).transferOwnership(0x57F8FFD76e9F90Ed945E3dB07F8f43b8e4B8E45d); }
1,469