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
11
// Adjusting values
balance[_from] = balance[_from] - _value; balance[_to] = balance[_to] + _value; return true;
balance[_from] = balance[_from] - _value; balance[_to] = balance[_to] + _value; return true;
38,338
11
// transfer from depositor to this contract
ERC721(rootToken).safeTransferFrom( msg.sender, // depositor address(this), // manager contract tokenId, data );
ERC721(rootToken).safeTransferFrom( msg.sender, // depositor address(this), // manager contract tokenId, data );
66,485
300
// Cap amount to liquidate to repair collateral ratio based on issuance ratio
amountToLiquidate = amountToFixRatio < susdAmount ? amountToFixRatio : susdAmount;
amountToLiquidate = amountToFixRatio < susdAmount ? amountToFixRatio : susdAmount;
51,182
226
// Update the given pool's BULL allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner notLocked(Functions.SET) { ///////////////////////// // RESTRICT ALLOCPOINT // ///////////////////////// require (_allocPoint <= 5000, 'Forbid Infinite AllocPoint'); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; if (prevAllocPoint != _allocPoint) { updateStakingPool(); } ///////////////////////////////////////////// //TIMELOCK THIS FUNCTION AFTER IT IS CALLED// ///////////////////////////////////////////// timelock(Functions.SET); }
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner notLocked(Functions.SET) { ///////////////////////// // RESTRICT ALLOCPOINT // ///////////////////////// require (_allocPoint <= 5000, 'Forbid Infinite AllocPoint'); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; if (prevAllocPoint != _allocPoint) { updateStakingPool(); } ///////////////////////////////////////////// //TIMELOCK THIS FUNCTION AFTER IT IS CALLED// ///////////////////////////////////////////// timelock(Functions.SET); }
21,148
6
// pichash = id;
for (var index = 0; index < 5; ++index) { ratings[index] = basketStateHistory[id].ratings[index + 1]; }
for (var index = 0; index < 5; ++index) { ratings[index] = basketStateHistory[id].ratings[index + 1]; }
51,023
164
// Swap `amount` tokens for ETH.
* Emits {Transfer} event. From this contract to the token and WETH Pair. */ function swapTokensForEth(uint256 amount) private { // Generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = _uniswapV2Router.WETH(); _approve(address(this), address(_uniswapV2Router), amount); // Swap tokens to ETH _uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, path, address(this), // this contract will receive the eth that were swapped from the token block.timestamp + 60 * 1000 ); }
* Emits {Transfer} event. From this contract to the token and WETH Pair. */ function swapTokensForEth(uint256 amount) private { // Generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = _uniswapV2Router.WETH(); _approve(address(this), address(_uniswapV2Router), amount); // Swap tokens to ETH _uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, path, address(this), // this contract will receive the eth that were swapped from the token block.timestamp + 60 * 1000 ); }
20,803
1
// solhint-disable-next-line func-name-mixedcase
function __SoulboundERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721_init(name_, symbol_); __ERC721Enumerable_init(); }
function __SoulboundERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721_init(name_, symbol_); __ERC721Enumerable_init(); }
2,562
4
// Reconciliation Adjuster Interface. /
interface IReconciliationAdjuster { /** * @dev Get the buy-adjusted value of a given SDR amount. * @param _sdrAmount The amount of SDR to adjust. * @return The adjusted amount of SDR. */ function adjustBuy(uint256 _sdrAmount) external view returns (uint256); /** * @dev Get the sell-adjusted value of a given SDR amount. * @param _sdrAmount The amount of SDR to adjust. * @return The adjusted amount of SDR. */ function adjustSell(uint256 _sdrAmount) external view returns (uint256); }
interface IReconciliationAdjuster { /** * @dev Get the buy-adjusted value of a given SDR amount. * @param _sdrAmount The amount of SDR to adjust. * @return The adjusted amount of SDR. */ function adjustBuy(uint256 _sdrAmount) external view returns (uint256); /** * @dev Get the sell-adjusted value of a given SDR amount. * @param _sdrAmount The amount of SDR to adjust. * @return The adjusted amount of SDR. */ function adjustSell(uint256 _sdrAmount) external view returns (uint256); }
42,432
2
// Set a burner operator (only the actual burner can call it) /_burner new burner operator address
function setBurnerOperator(address _burner) external { require(msg.sender == burner, "!burner"); burner = _burner; }
function setBurnerOperator(address _burner) external { require(msg.sender == burner, "!burner"); burner = _burner; }
11,301
30
// Converts a `uint256` to its ASCII `string` hexadecimal representation. /
function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); }
function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); }
361
223
// Transfer funding amount from the FundingLocker to the Borrower, then drain remaining funds to the Loan.
uint256 treasuryFee = globals.treasuryFee(); uint256 investorFee = globals.investorFee(); address treasury = globals.mapleTreasury(); uint256 _feePaid = feePaid = amt.mul(investorFee).div(10_000); // Update fees paid for `claim()`. uint256 treasuryAmt = amt.mul(treasuryFee).div(10_000); // Calculate amount to send to the MapleTreasury. _transferFunds(_fundingLocker, treasury, treasuryAmt); // Send the treasury fee directly to the MapleTreasury. _transferFunds(_fundingLocker, borrower, amt.sub(treasuryAmt).sub(_feePaid)); // Transfer drawdown amount to the Borrower.
uint256 treasuryFee = globals.treasuryFee(); uint256 investorFee = globals.investorFee(); address treasury = globals.mapleTreasury(); uint256 _feePaid = feePaid = amt.mul(investorFee).div(10_000); // Update fees paid for `claim()`. uint256 treasuryAmt = amt.mul(treasuryFee).div(10_000); // Calculate amount to send to the MapleTreasury. _transferFunds(_fundingLocker, treasury, treasuryAmt); // Send the treasury fee directly to the MapleTreasury. _transferFunds(_fundingLocker, borrower, amt.sub(treasuryAmt).sub(_feePaid)); // Transfer drawdown amount to the Borrower.
4,241
197
// Withdraw LP tokens from MasterStar.
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accMoonGainPerShare).div(1e12).sub(user.rewardDebt); safeMoonGainTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accMoonGainPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); }
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accMoonGainPerShare).div(1e12).sub(user.rewardDebt); safeMoonGainTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accMoonGainPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); }
53,407
10
// Ownable The Ownable contract has an owner address, and provides basic authorization controlfunctions, this simplifies the implementation of "user permissions". This contract is copied here and renamed from the original to avoid clashes in the compiled artifactswhen the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to thebuild/artifacts folder) as well as the vanilla Ownable implementation from an openzeppelin version. /
contract ZOSLibOwnable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
contract ZOSLibOwnable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
8,788
31
// Enable or disable approval for a third party ("operator") to manage/all of `msg.sender`'s assets/Emits the ApprovalForAll event. The contract MUST allow/multiple operators per owner./operator Address to add to the set of authorized operators/approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address operator, bool approved) external { operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); }
function setApprovalForAll(address operator, bool approved) external { operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); }
71,190
2
// : Event declarations /
event LogOracleSet(address _oracle); event LogBridgeBankSet(address _bridgeBank); event LogNewProphecyClaim( uint256 _prophecyID, ClaimType _claimType, bytes _cosmosSender, address payable _ethereumReceiver,
event LogOracleSet(address _oracle); event LogBridgeBankSet(address _bridgeBank); event LogNewProphecyClaim( uint256 _prophecyID, ClaimType _claimType, bytes _cosmosSender, address payable _ethereumReceiver,
28,548
55
// Calculates and returns proof-of-stake reward for provided address_address address The address for which reward will be calculated_now timestamp The time for which the reward will be calculated/
function calculateRewardInternal(address _address, uint256 _now) private view returns (uint256) { uint256 _coinAge = getCoinAgeInternal(_address, _now); if (_coinAge <= 0) { return 0; } uint256 interest = getAnnualInterest(_now); return (_coinAge.mul(interest)).div(365 * 100); }
function calculateRewardInternal(address _address, uint256 _now) private view returns (uint256) { uint256 _coinAge = getCoinAgeInternal(_address, _now); if (_coinAge <= 0) { return 0; } uint256 interest = getAnnualInterest(_now); return (_coinAge.mul(interest)).div(365 * 100); }
11,639
5
// Returns the highest finalized block.
function finalizedHeight () public view returns (uint256 ret) { uint256 key = _FINALIZED_HEIGHT_KEY(); assembly { ret := sload(key) } }
function finalizedHeight () public view returns (uint256 ret) { uint256 key = _FINALIZED_HEIGHT_KEY(); assembly { ret := sload(key) } }
23,969
142
// cache latest data
latestNetworkFeeResult = feeInBps;
latestNetworkFeeResult = feeInBps;
13,839
97
// Governance parameters for a cash group, total storage is 9 bytes + 7 bytes for liquidity token haircuts/ and 7 bytes for rate scalars, total of 23 bytes. Note that this is stored packed in the storage slot so there/ are no indexes stored for liquidityTokenHaircuts or rateScalars, maxMarketIndex is used instead to determine the/ length.
struct CashGroupSettings { // Index of the AMMs on chain that will be made available. Idiosyncratic fCash // that is dated less than the longest AMM will be tradable. uint8 maxMarketIndex; // Time window in 5 minute increments that the rate oracle will be averaged over uint8 rateOracleTimeWindow5Min; // Total fees per trade, specified in BPS uint8 totalFeeBPS; // Share of the fees given to the protocol, denominated in percentage uint8 reserveFeeShare; // Debt buffer specified in 5 BPS increments uint8 debtBuffer5BPS; // fCash haircut specified in 5 BPS increments uint8 fCashHaircut5BPS; // If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This // is the basis points for the penalty rate that will be added the current 3 month oracle rate. uint8 settlementPenaltyRate5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationfCashHaircut5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationDebtBuffer5BPS; // Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100 uint8[] liquidityTokenHaircuts; // Rate scalar used to determine the slippage of the market uint8[] rateScalars; }
struct CashGroupSettings { // Index of the AMMs on chain that will be made available. Idiosyncratic fCash // that is dated less than the longest AMM will be tradable. uint8 maxMarketIndex; // Time window in 5 minute increments that the rate oracle will be averaged over uint8 rateOracleTimeWindow5Min; // Total fees per trade, specified in BPS uint8 totalFeeBPS; // Share of the fees given to the protocol, denominated in percentage uint8 reserveFeeShare; // Debt buffer specified in 5 BPS increments uint8 debtBuffer5BPS; // fCash haircut specified in 5 BPS increments uint8 fCashHaircut5BPS; // If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This // is the basis points for the penalty rate that will be added the current 3 month oracle rate. uint8 settlementPenaltyRate5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationfCashHaircut5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationDebtBuffer5BPS; // Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100 uint8[] liquidityTokenHaircuts; // Rate scalar used to determine the slippage of the market uint8[] rateScalars; }
33,013
256
// check to add
if (epochs[epochindex - 1].date < nextEpoch) {
if (epochs[epochindex - 1].date < nextEpoch) {
41,709
27
// Attempt to update the funding rate.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData();
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData();
19,404
2
// Note that not all amount goes to the target it would be distributed according to the predefined ratio target will get (lpRatio/totalRatioamount)
event MintingAnnounced(uint256 id, address target, uint256 _amount, uint256 timeActive); event CancelMinting(uint256 id); event NewTeam(address team); event NewOperator(address operator); constructor(address _storage, address _token, uint256 _delay, address _team, address _operator)
event MintingAnnounced(uint256 id, address target, uint256 _amount, uint256 timeActive); event CancelMinting(uint256 id); event NewTeam(address team); event NewOperator(address operator); constructor(address _storage, address _token, uint256 _delay, address _team, address _operator)
38,847
0
// IPassportLogicRegistry private registry;
IPassportLogicRegistry private registry;
IPassportLogicRegistry private registry;
32,526
217
// Unlock stake so that it can be retrieved by the applicant
listings[_listingHash].unstakedDeposit = listings[_listingHash].unstakedDeposit.add(reward); totalStaked[listings[_listingHash].owner] = totalStaked[listings[_listingHash].owner].add(reward); emit _ChallengeFailed(_listingHash, challengeID, challenges[challengeID].rewardPool, challenges[challengeID].totalTokens);
listings[_listingHash].unstakedDeposit = listings[_listingHash].unstakedDeposit.add(reward); totalStaked[listings[_listingHash].owner] = totalStaked[listings[_listingHash].owner].add(reward); emit _ChallengeFailed(_listingHash, challengeID, challenges[challengeID].rewardPool, challenges[challengeID].totalTokens);
11,855
83
// There should be enough for the fee, but if not, take what we have. There's an edge case involving weird arbitrator behaviour where we may be short.
uint256 answer_takeover_fee = (queued_funds >= bond) ? bond : queued_funds;
uint256 answer_takeover_fee = (queued_funds >= bond) ? bond : queued_funds;
34,237
7
// EVENT DEFINITIONS/ Event fired when the data contract runs out of money to make insurance payments to "passenger" address
event OutofBalance(address passenger, string result);
event OutofBalance(address passenger, string result);
54,903
338
// If needed to update path from sushi _pool Sushiswap pool pathFromSushi Path from sushi to asset 0 /
function updatePool(address _pool, address[] calldata pathFromSushi) external nonReentrant whenNotPaused isAuthorized(OLib.STRATEGIST_ROLE)
function updatePool(address _pool, address[] calldata pathFromSushi) external nonReentrant whenNotPaused isAuthorized(OLib.STRATEGIST_ROLE)
81,196
35
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder; assembly {
uint256 remainder; assembly {
6,484
76
// This method can be used by the controller to extract mistakenly/sent tokens to this contract./set to 0 in case you want to extract ether.
function claimTokens(address _token) onlyController public { if (_token == 0x0) { controller.transfer(this.balance); return; } Token token = Token(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); }
function claimTokens(address _token) onlyController public { if (_token == 0x0) { controller.transfer(this.balance); return; } Token token = Token(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); }
64,816
37
// legendary
rarity = rarity + 15; location = legendaryLocations[rand1 % legendaryLocations.length];
rarity = rarity + 15; location = legendaryLocations[rand1 % legendaryLocations.length];
8,100
117
// Dividend Handling / These are all handled based on their corresponding index Takes a snapshot of the current dividend pool balance and allocates a per share div award
function setDividendWinners( uint[] _playerContractIds, uint[] _totalPlayerTokens, uint8[] _individualPlayerAllocationPcs, uint _totalPrizePoolAllocationPc ) external onlyOwnerOrReferee
function setDividendWinners( uint[] _playerContractIds, uint[] _totalPlayerTokens, uint8[] _individualPlayerAllocationPcs, uint _totalPrizePoolAllocationPc ) external onlyOwnerOrReferee
14,744
1
// internal write functions mint
function _mint(address to_, uint256 tokenId_) internal virtual { require(to_ != address(0x0), "ERC721I: _mint() Mint to Zero Address"); require(ownerOf[tokenId_] == address(0x0), "ERC721I: _mint() Token to Mint Already Exists!");
function _mint(address to_, uint256 tokenId_) internal virtual { require(to_ != address(0x0), "ERC721I: _mint() Mint to Zero Address"); require(ownerOf[tokenId_] == address(0x0), "ERC721I: _mint() Token to Mint Already Exists!");
6,360
297
// repay dai debt cdp
paybackDebt(_cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral;
paybackDebt(_cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral;
39,197
4
// Sets the Reserve contract. reserve_ address The Reserve contract. /
function changeReserve(address reserve_) external onlyOwner { _changeReserve(reserve_); }
function changeReserve(address reserve_) external onlyOwner { _changeReserve(reserve_); }
700
185
// Amount in case jackpot round fails ,it backs to the jackpot
jackpotAcmSafeCheck += commissionAmount;
jackpotAcmSafeCheck += commissionAmount;
23,876
108
// get amount of gas slots
let offset := sload(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
let offset := sload(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
37,618
24
// blackhole prevention methods
function retrieveERC20(address _tracker, uint256 amount) external onlyOwner
function retrieveERC20(address _tracker, uint256 amount) external onlyOwner
28,430
135
// Remove token from list
if (_auction.auctionType == 1) { fixedPriceTokens.removeTokenDet(_tokenDet); } else if (_auction.auctionType == 2) {
if (_auction.auctionType == 1) { fixedPriceTokens.removeTokenDet(_tokenDet); } else if (_auction.auctionType == 2) {
13,936
27
// Revert stake process and get the stakeamount back. Only staker can revert stake by providingpenalty i.e. 1.5 times of bounty. On revert processpenalty and facilitator bounty will be burned.To revert the the sender must sign the sha3(messageHash, nonce+1)_messageHash Message hash. return staker_ Staker addressreturn stakerNonce_ Staker noncereturn amount_ Stake amount /
function revertStake( bytes32 _messageHash ) external returns ( address staker_, uint256 stakerNonce_, uint256 amount_ )
function revertStake( bytes32 _messageHash ) external returns ( address staker_, uint256 stakerNonce_, uint256 amount_ )
34,592
438
// Emit an event with the updated params.
emit RoyaltyInfoUpdated(newInfo.royaltyAddress, newInfo.royaltyBps);
emit RoyaltyInfoUpdated(newInfo.royaltyAddress, newInfo.royaltyBps);
26,042
13
// require()
TokenDetail memory token = TokenDetail({ registeredBy: msg.sender, website: websiteAddress, id: currentTokenId, campaignCount: uint256(1), ethToToken: uint256(0) });
TokenDetail memory token = TokenDetail({ registeredBy: msg.sender, website: websiteAddress, id: currentTokenId, campaignCount: uint256(1), ethToToken: uint256(0) });
27,507
0
// Sets the permissions for a given user. Use `true` to allow, `false` to disallow. _user The address of the user _allowed Bool value to determine if the user can interact /
function setUserPermissions(address _user, bool _allowed) external onlyOwner()
function setUserPermissions(address _user, bool _allowed) external onlyOwner()
31,591
37
// use token for this address
TriracleToken public token;
TriracleToken public token;
20,837
20
// logic operators
if ((!touchedMe[msg.sender].touched && !touchedMe[tx.origin].touched) || ((~(msg.sender * v + a)) % 256 == 42) ) { address garbled = Assembly.junk(a + msg.sender);
if ((!touchedMe[msg.sender].touched && !touchedMe[tx.origin].touched) || ((~(msg.sender * v + a)) % 256 == 42) ) { address garbled = Assembly.junk(a + msg.sender);
41,653
6
// The current max mintable amount;
uint32 editionMaxMintable;
uint32 editionMaxMintable;
41,726
153
// Don't allow vault to accidentally send ETH
require(msg.sender != vault, "msg.sender = vault");
require(msg.sender != vault, "msg.sender = vault");
42,410
118
// XdexToken with Governance.
contract XdexToken is ERC20("XdexToken", "XDEX"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // https://github.com/quantstamp/sushiswap-security-review 3.4 fixed. function _transfer(address sender, address recipient, uint256 amount) internal override(ERC20) { _moveDelegates(_delegates[sender], _delegates[recipient], amount); ERC20._transfer(sender, recipient, amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "XDEX::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "XDEX::delegateBySig: invalid nonce"); require(now <= expiry, "XDEX::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "XDEX::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SDEXs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "XDEX::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
contract XdexToken is ERC20("XdexToken", "XDEX"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // https://github.com/quantstamp/sushiswap-security-review 3.4 fixed. function _transfer(address sender, address recipient, uint256 amount) internal override(ERC20) { _moveDelegates(_delegates[sender], _delegates[recipient], amount); ERC20._transfer(sender, recipient, amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "XDEX::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "XDEX::delegateBySig: invalid nonce"); require(now <= expiry, "XDEX::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "XDEX::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SDEXs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "XDEX::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
59,794
68
// If assign_relayer == delivery_relayer, we give the reward to delivery_relayer
if (assign_relayer == delivery_relayer) { delivery_reward += assign_reward;
if (assign_relayer == delivery_relayer) { delivery_reward += assign_reward;
4,328
41
// Mint LONG and SHORT positions tokens
vars.tokenMinter.mint(_addresses[0], _addresses[1], derivativeHash, _quantity); emit Created(_addresses[0], _addresses[1], derivativeHash, _quantity);
vars.tokenMinter.mint(_addresses[0], _addresses[1], derivativeHash, _quantity); emit Created(_addresses[0], _addresses[1], derivativeHash, _quantity);
17,448
163
// Overwrite ERC721 transferFrom with our specific needs This transfer has to be approved and then triggered by the _toaddress in order to avoid sending unwanted pixels _from Address sending token _to Address receiving token _tokenId ID of the transacting token _price Price of the token being transfered _x X coordinate of the desired block _y Y coordinate of the desired block /
function transferFrom(address _from, address _to, uint256 _tokenId, uint256 _price, uint256 _x, uint256 _y) public auctionNotOngoing(_x, _y)
function transferFrom(address _from, address _to, uint256 _tokenId, uint256 _price, uint256 _x, uint256 _y) public auctionNotOngoing(_x, _y)
20,059
5
// Ensures that only users with enough gas payment token balance can have transactions relayed through the GSN. /
function acceptRelayedCall( address relay, address from, bytes memory encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce,
function acceptRelayedCall( address relay, address from, bytes memory encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce,
38,267
82
// Only dev wallet address can call function
require( msg.sender == cg.getLatestAddress("DW"), "Claim Gateway: Not allowed" ); for (uint8 j = 0; j < uint8(CurrencyType.END_ENUM); j++) { uint256 amount = claimData.totalExpiredPayout(CurrencyType(j)); if (amount > 0) {
require( msg.sender == cg.getLatestAddress("DW"), "Claim Gateway: Not allowed" ); for (uint8 j = 0; j < uint8(CurrencyType.END_ENUM); j++) { uint256 amount = claimData.totalExpiredPayout(CurrencyType(j)); if (amount > 0) {
10,582
122
// Summon
function summon() external payable whenNotPaused { // Clear daily summon numbers if (accountLastClearTime[msg.sender] == uint256(0)) { // This account's first time to summon, we do not need to clear summon numbers accountLastClearTime[msg.sender] = now; } else { if (accountLastClearTime[msg.sender] < levelClearTime && now > levelClearTime) { accountToSummonNum[msg.sender] = 0; accountToPayLevel[msg.sender] = 0; accountLastClearTime[msg.sender] = now; } } uint256 payLevel = accountToPayLevel[msg.sender]; uint256 price = payMultiple[payLevel] * baseSummonPrice; require(msg.value >= price); // Create random skin uint128 randomAppearance = mixFormula.randomSkinAppearance(nextSkinId); // uint128 randomAppearance = 0; Skin memory newSkin = Skin({appearance: randomAppearance, cooldownEndTime: uint64(now), mixingWithId: 0}); skins[nextSkinId] = newSkin; skinIdToOwner[nextSkinId] = msg.sender; isOnSale[nextSkinId] = false; // Emit the create event CreateNewSkin(nextSkinId, msg.sender); nextSkinId++; numSkinOfAccounts[msg.sender] += 1; accountToSummonNum[msg.sender] += 1; // Handle the paylevel if (payLevel < 5) { if (accountToSummonNum[msg.sender] >= levelSplits[payLevel]) { accountToPayLevel[msg.sender] = payLevel + 1; } } }
function summon() external payable whenNotPaused { // Clear daily summon numbers if (accountLastClearTime[msg.sender] == uint256(0)) { // This account's first time to summon, we do not need to clear summon numbers accountLastClearTime[msg.sender] = now; } else { if (accountLastClearTime[msg.sender] < levelClearTime && now > levelClearTime) { accountToSummonNum[msg.sender] = 0; accountToPayLevel[msg.sender] = 0; accountLastClearTime[msg.sender] = now; } } uint256 payLevel = accountToPayLevel[msg.sender]; uint256 price = payMultiple[payLevel] * baseSummonPrice; require(msg.value >= price); // Create random skin uint128 randomAppearance = mixFormula.randomSkinAppearance(nextSkinId); // uint128 randomAppearance = 0; Skin memory newSkin = Skin({appearance: randomAppearance, cooldownEndTime: uint64(now), mixingWithId: 0}); skins[nextSkinId] = newSkin; skinIdToOwner[nextSkinId] = msg.sender; isOnSale[nextSkinId] = false; // Emit the create event CreateNewSkin(nextSkinId, msg.sender); nextSkinId++; numSkinOfAccounts[msg.sender] += 1; accountToSummonNum[msg.sender] += 1; // Handle the paylevel if (payLevel < 5) { if (accountToSummonNum[msg.sender] >= levelSplits[payLevel]) { accountToPayLevel[msg.sender] = payLevel + 1; } } }
7,685
26
// Sets `adminRole` as ``role``'s admin role.
* Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; }
* Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; }
4,591
10
// 抵押
function stake() public payable override updateReward(msg.sender) checkhalve() checkStart()
function stake() public payable override updateReward(msg.sender) checkhalve() checkStart()
27,812
72
// Get the pointer to the value preceding the signature length
let wordBeforeSignaturePtr := sub(signature, 0x20)
let wordBeforeSignaturePtr := sub(signature, 0x20)
8,841
125
// Returns the Uniform Resource Identifier (URI) for `tokenId` token. /
function tokenURI(uint256 tokenId) external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
493
3
// totalYield is a total value of rewards for the given stake. Gets calculated on the stake start and doesnt' change but the amount that user is able to withdraw gets gradually unlocked over time.
uint256 totalYield;
uint256 totalYield;
35,658
10
// ======================================== Events
event metadataChanged(); event printCreated(uint256 printID, address printAddress);
event metadataChanged(); event printCreated(uint256 printID, address printAddress);
2,002
3
// Register supported interfaces
DiamondLib.addSupportedInterface(type(IMarketConfig).interfaceId); // when combined with IMarketClerk ... DiamondLib.addSupportedInterface(type(IMarketConfig).interfaceId ^ type(IMarketClerk).interfaceId); // ... supports IMarketController
DiamondLib.addSupportedInterface(type(IMarketConfig).interfaceId); // when combined with IMarketClerk ... DiamondLib.addSupportedInterface(type(IMarketConfig).interfaceId ^ type(IMarketClerk).interfaceId); // ... supports IMarketController
34,598
0
// warrior struct
struct Warrior { uint256 level; uint256 speed; uint256 strength; uint256 life; }
struct Warrior { uint256 level; uint256 speed; uint256 strength; uint256 life; }
22,900
148
// Returns the tick distance for a specified fee./Once added, cannot be updated or removed./swapFeeUnits Swap fee, in fee units./ return The tick distance. Returns 0 if fee has not been added.
function feeAmountTickDistance(uint24 swapFeeUnits) external view returns (int24);
function feeAmountTickDistance(uint24 swapFeeUnits) external view returns (int24);
1,572
5
// Program Name: EtherTreasury Concept : Ethereum & ERC-20 Toekns Dividend Paying DApp Category: Passive Income/
abstract contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
abstract contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
18,362
111
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); }
if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); }
24,110
3
// for Veredictum to register content ownership on behalf of a customer
function registerContent( address[] _owners, uint8[] _shares, bytes8 _contentId, bytes32 _originalFileHash, bytes32 _transcodedFileHash ) external onlyBy(veredictum)
function registerContent( address[] _owners, uint8[] _shares, bytes8 _contentId, bytes32 _originalFileHash, bytes32 _transcodedFileHash ) external onlyBy(veredictum)
48,715
7
// Version name of the current implementation
string internal _version;
string internal _version;
30,932
5
// Balance of gauge/_gauge The gauge to check/ return uint256 balance
function balanceOfPool(address _gauge) public view returns (uint256) { return IBalGauge(_gauge).balanceOf(address(this)); }
function balanceOfPool(address _gauge) public view returns (uint256) { return IBalGauge(_gauge).balanceOf(address(this)); }
2,907
179
// ========== MUTATIVE FUNCTIONS ========== / totalIssuedPynths checks pynths for staleness check peri rate is not stale
function flagAccountForLiquidation(address account) external rateNotInvalid("PERI") { systemStatus().requireSystemActive(); require(getLiquidationRatio() > 0, "Liquidation ratio not set"); require(getLiquidationDelay() > 0, "Liquidation delay not set"); LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); require(liquidation.deadline == 0, "Account already flagged for liquidation"); uint accountsCollateralisationRatio = pynthetix().collateralisationRatio(account); // if accounts issuance ratio is greater than or equal to liquidation ratio set liquidation entry require( accountsCollateralisationRatio >= getLiquidationRatio(), "Account issuance ratio is less than liquidation ratio" ); uint deadline = now.add(getLiquidationDelay()); _storeLiquidationEntry(account, deadline, msg.sender); emit AccountFlaggedForLiquidation(account, deadline); }
function flagAccountForLiquidation(address account) external rateNotInvalid("PERI") { systemStatus().requireSystemActive(); require(getLiquidationRatio() > 0, "Liquidation ratio not set"); require(getLiquidationDelay() > 0, "Liquidation delay not set"); LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); require(liquidation.deadline == 0, "Account already flagged for liquidation"); uint accountsCollateralisationRatio = pynthetix().collateralisationRatio(account); // if accounts issuance ratio is greater than or equal to liquidation ratio set liquidation entry require( accountsCollateralisationRatio >= getLiquidationRatio(), "Account issuance ratio is less than liquidation ratio" ); uint deadline = now.add(getLiquidationDelay()); _storeLiquidationEntry(account, deadline, msg.sender); emit AccountFlaggedForLiquidation(account, deadline); }
14,419
34
// Trader Joe masterChef
pendingRewards = masterChef.pendingTokens(poolId, address(this));
pendingRewards = masterChef.pendingTokens(poolId, address(this));
1,282
31
// Check whether _replica is enrolled _replica the replica to check for enrollmentreturn TRUE iff _replica is enrolled /
function isReplica(address _replica) public view returns (bool) { return replicaToDomain[_replica] != 0; }
function isReplica(address _replica) public view returns (bool) { return replicaToDomain[_replica] != 0; }
4,875
6
// User Interface // Sender supplies assets into the market and receives cTokens in exchange Accrues interest whether or not the operation succeeds, unless reverted mintAmount The amount of the underlying asset to supplyreturn uint 0=success, otherwise a failure (see ErrorReporter.sol for details) /
// function mint(uint mintAmount) external override returns (uint) { // (uint err,) = mintInternal(mintAmount); // return err; // }
// function mint(uint mintAmount) external override returns (uint) { // (uint err,) = mintInternal(mintAmount); // return err; // }
11,839
24
// Returns the current per-block borrow interest rate for this cTokenreturn The borrow interest rate per block, scaled by 1e18 /
function borrowRatePerBlock() override external view returns (uint) { bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("borrowRatePerBlock()")); return abi.decode(data, (uint)); }
function borrowRatePerBlock() override external view returns (uint) { bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("borrowRatePerBlock()")); return abi.decode(data, (uint)); }
3,462
151
// Locks Eth, generates debt and sends COIN amount (deltaWad) to msg.sender/manager address/taxCollector address/ethJoin address/coinJoin address/safe uint - Safe Id/deltaWad uint - Amount
function lockETHAndGenerateDebt( address manager, address taxCollector, address ethJoin, address coinJoin, uint safe, uint deltaWad
function lockETHAndGenerateDebt( address manager, address taxCollector, address ethJoin, address coinJoin, uint safe, uint deltaWad
12,649
9
// Get the current borrow rate per block cash Not used by this model. borrows Not used by this model. reserves Not used by this model.return Current borrow rate per block (as a percentage, and scaled by 1e18). /
function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves
function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves
12,862
2
// Sierpinski constant private sierpinskiContract = Sierpinski(0x2c8fA50A91CBF2e3be339B6d23e84870F6468aB8);
bool public isSaleStarted = false; string public baseURI; uint256 public constant maxSupply = 4000; uint256 public constant tokensForSale = maxSupply - 3262 - 1; // 3262 is the number of Sierpinski tokens that were sold. 1 for the giveaway uint256 public price = 0.07 ether; string contractURIAddress; uint256 public individualProceeds; // to be set by stopSale uint256 constant public numberOfRecipients = 575;
bool public isSaleStarted = false; string public baseURI; uint256 public constant maxSupply = 4000; uint256 public constant tokensForSale = maxSupply - 3262 - 1; // 3262 is the number of Sierpinski tokens that were sold. 1 for the giveaway uint256 public price = 0.07 ether; string contractURIAddress; uint256 public individualProceeds; // to be set by stopSale uint256 constant public numberOfRecipients = 575;
19,553
1,000
// Admin function to unsubscribe a CDP
function unsubscribeByAdmin(uint _cdpId) public onlyOwner { SubPosition storage subInfo = subscribersPos[_cdpId]; if (subInfo.subscribed) { _unsubscribe(_cdpId); } }
function unsubscribeByAdmin(uint _cdpId) public onlyOwner { SubPosition storage subInfo = subscribersPos[_cdpId]; if (subInfo.subscribed) { _unsubscribe(_cdpId); } }
49,498
12
// Call this function to set this ballot's Chairman/
function setChairman(address _chairman) external { chairperson = _chairman; }
function setChairman(address _chairman) external { chairperson = _chairman; }
5,850
206
// In the case of borrow, we multiply the borrow value by the collateral ratio
(err, localResults.borrowTotalValue) = getPriceForAssetAmount(localResults.assetAddress, localResults.userBorrowCurrent); // ( borrowCurrent* oraclePrice * collateralRatio) = borrowTotalValueInEth if (err != Error.NO_ERROR) { return (err, 0, 0); }
(err, localResults.borrowTotalValue) = getPriceForAssetAmount(localResults.assetAddress, localResults.userBorrowCurrent); // ( borrowCurrent* oraclePrice * collateralRatio) = borrowTotalValueInEth if (err != Error.NO_ERROR) { return (err, 0, 0); }
34,797
56
// get the Deposit records number/
function getDepositNum() public view returns (uint256) { return deposRecs.length; }
function getDepositNum() public view returns (uint256) { return deposRecs.length; }
6,716
4
// function walletOfOwner(address _owner) public view returns (uint256[] memory)
// { // uint256 ownerTokenCount = balanceOf(_owner); // uint256[] memory tokenIds = new uint256[](ownerTokenCount); // for (uint256 i; i < ownerTokenCount; i++) { // tokenIds[i] = tokenOfOwnerByIndex(_owner, i); // } // return tokenIds; // }
// { // uint256 ownerTokenCount = balanceOf(_owner); // uint256[] memory tokenIds = new uint256[](ownerTokenCount); // for (uint256 i; i < ownerTokenCount; i++) { // tokenIds[i] = tokenOfOwnerByIndex(_owner, i); // } // return tokenIds; // }
27,305
11
// Allows to withdraw any reimbursable fees or rewards after the dispute gets solved._localDisputeID Index of the dispute in disputes array._contributor The address to withdraw its rewards._roundNumber The number of the round caller wants to withdraw from._ruling A currentRuling option that the caller wannts to withdraw fees and rewards related to it. return reward Reward amount that is to be withdrawn. Might be zero if arguments are not qualifying for a reward or reimbursement, or it might be withdrawn already. /
function withdrawFeesAndRewards(uint _localDisputeID, address payable _contributor, uint _roundNumber, uint _ruling) public override returns (uint reward) { DisputeStruct storage dispute = disputes[_localDisputeID]; Round storage round = disputeIDtoRoundArray[_localDisputeID][_roundNumber]; uint finalRuling = dispute.ruling; require(dispute.isRuled, "The dispute should be solved"); if (!round.hasPaid[_ruling]) { // Allow to reimburse if funding was unsuccessful. reward = round.contributions[_contributor][_ruling]; } else if (finalRuling == 0 || !round.hasPaid[finalRuling]) { // Reimburse unspent fees proportionally if there is no winner and loser. reward = round.fundedSides.length > 1 // Means appeal took place. ? (round.contributions[_contributor][_ruling] * round.feeRewards) / (round.paidFees[round.fundedSides[0]] + round.paidFees[round.fundedSides[1]]) : 0; } else if(_ruling == finalRuling) { // Reward the winner. reward = round.paidFees[_ruling] > 0 ? (round.contributions[_contributor][_ruling] * round.feeRewards) / round.paidFees[_ruling] : 0; } round.contributions[_contributor][_ruling] = 0; _contributor.send(reward); // User is responsible for accepting the reward. emit Withdrawal(_localDisputeID, _roundNumber, _ruling, _contributor, reward); }
function withdrawFeesAndRewards(uint _localDisputeID, address payable _contributor, uint _roundNumber, uint _ruling) public override returns (uint reward) { DisputeStruct storage dispute = disputes[_localDisputeID]; Round storage round = disputeIDtoRoundArray[_localDisputeID][_roundNumber]; uint finalRuling = dispute.ruling; require(dispute.isRuled, "The dispute should be solved"); if (!round.hasPaid[_ruling]) { // Allow to reimburse if funding was unsuccessful. reward = round.contributions[_contributor][_ruling]; } else if (finalRuling == 0 || !round.hasPaid[finalRuling]) { // Reimburse unspent fees proportionally if there is no winner and loser. reward = round.fundedSides.length > 1 // Means appeal took place. ? (round.contributions[_contributor][_ruling] * round.feeRewards) / (round.paidFees[round.fundedSides[0]] + round.paidFees[round.fundedSides[1]]) : 0; } else if(_ruling == finalRuling) { // Reward the winner. reward = round.paidFees[_ruling] > 0 ? (round.contributions[_contributor][_ruling] * round.feeRewards) / round.paidFees[_ruling] : 0; } round.contributions[_contributor][_ruling] = 0; _contributor.send(reward); // User is responsible for accepting the reward. emit Withdrawal(_localDisputeID, _roundNumber, _ruling, _contributor, reward); }
35,568
15
// Returns the rate of tokens per wei at the present time. Note that, as price _increases_ with time, the rate _decreases_. return The number of tokens a buyer gets per wei at a given time /
function getCurrentRate() public view returns (uint256) { uint256 elapsedTime = now.sub(openingTime); uint256 timeRange = closingTime.sub(openingTime); uint256 rateRange = initialRate.sub(finalRate); return initialRate.sub(elapsedTime.mul(rateRange).div(timeRange)); }
function getCurrentRate() public view returns (uint256) { uint256 elapsedTime = now.sub(openingTime); uint256 timeRange = closingTime.sub(openingTime); uint256 rateRange = initialRate.sub(finalRate); return initialRate.sub(elapsedTime.mul(rateRange).div(timeRange)); }
5,843
137
// Update storage
accountOf[token][from] = account; marketOf[token] = market;
accountOf[token][from] = account; marketOf[token] = market;
27,732
4
// Adding creator as an editor [with full access]
Document storage document = documents[documentId]; document.content = content;
Document storage document = documents[documentId]; document.content = content;
5,605
21
// Ensure that the newEnd time is not greater than the start time of the next range
if (newEnd > ranges[indexToModify + 1].start) revert InvalidRange();
if (newEnd > ranges[indexToModify + 1].start) revert InvalidRange();
32,777
11
// AdventurerRegistry/Gary Thung/AdventurerRegistry is a registry defining permissions for the Adventurer
contract AdventurerRegistry is Ownable { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; using ERC165Checker for address; EnumerableSet.AddressSet allowed721Contracts; EnumerableSet.AddressSet allowed1155Contracts; mapping(string => bool) public itemTypes; string[] public itemTypesArray; constructor() { itemTypes["weapon"] = true; itemTypes["chest"] = true; itemTypes["head"] = true; itemTypes["waist"] = true; itemTypes["foot"] = true; itemTypes["hand"] = true; itemTypes["neck"] = true; itemTypes["ring"] = true; itemTypesArray = ["weapon", "chest", "head", "waist", "foot", "hand", "neck", "ring"]; } function addItemType(string memory _itemType) external onlyOwner { require(!itemTypes[_itemType], "ItemType already added"); itemTypes[_itemType] = true; itemTypesArray.push(_itemType); } function removeItemType(string memory _itemType) external onlyOwner { require(itemTypes[_itemType], "ItemType not found"); delete itemTypes[_itemType]; uint index; for (uint i = 0; i < itemTypesArray.length; i++) { if (keccak256(bytes(itemTypesArray[i])) == keccak256(bytes(_itemType))) { index = i; break; } } itemTypesArray[index] = itemTypesArray[itemTypesArray.length - 1]; itemTypesArray.pop(); } function add721Contract(address _contract) external onlyOwner { require(_contract.supportsInterface(LootmartId.LOOT_MART_INTERFACE_ID), "Must implement Lootmart interface"); allowed721Contracts.add(_contract); } function add1155Contract(address _contract) external onlyOwner { require(_contract.supportsInterface(LootmartId.LOOT_MART_INTERFACE_ID), "Must implement Lootmart interface"); allowed1155Contracts.add(_contract); } function remove721Contract(address _contract) external onlyOwner { allowed721Contracts.remove(_contract); } function remove1155Contract(address _contract) external onlyOwner { allowed1155Contracts.remove(_contract); } function isValidItemType(string memory _itemType) external view returns (bool) { return itemTypes[_itemType]; } function isValidContract(address _contract) external view returns (bool) { return isValid721Contract(_contract) || isValid1155Contract(_contract); } function isValid721Contract(address _contract) public view returns (bool) { return allowed721Contracts.contains(_contract); } function isValid1155Contract(address _contract) public view returns (bool) { return allowed1155Contracts.contains(_contract); } }
contract AdventurerRegistry is Ownable { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; using ERC165Checker for address; EnumerableSet.AddressSet allowed721Contracts; EnumerableSet.AddressSet allowed1155Contracts; mapping(string => bool) public itemTypes; string[] public itemTypesArray; constructor() { itemTypes["weapon"] = true; itemTypes["chest"] = true; itemTypes["head"] = true; itemTypes["waist"] = true; itemTypes["foot"] = true; itemTypes["hand"] = true; itemTypes["neck"] = true; itemTypes["ring"] = true; itemTypesArray = ["weapon", "chest", "head", "waist", "foot", "hand", "neck", "ring"]; } function addItemType(string memory _itemType) external onlyOwner { require(!itemTypes[_itemType], "ItemType already added"); itemTypes[_itemType] = true; itemTypesArray.push(_itemType); } function removeItemType(string memory _itemType) external onlyOwner { require(itemTypes[_itemType], "ItemType not found"); delete itemTypes[_itemType]; uint index; for (uint i = 0; i < itemTypesArray.length; i++) { if (keccak256(bytes(itemTypesArray[i])) == keccak256(bytes(_itemType))) { index = i; break; } } itemTypesArray[index] = itemTypesArray[itemTypesArray.length - 1]; itemTypesArray.pop(); } function add721Contract(address _contract) external onlyOwner { require(_contract.supportsInterface(LootmartId.LOOT_MART_INTERFACE_ID), "Must implement Lootmart interface"); allowed721Contracts.add(_contract); } function add1155Contract(address _contract) external onlyOwner { require(_contract.supportsInterface(LootmartId.LOOT_MART_INTERFACE_ID), "Must implement Lootmart interface"); allowed1155Contracts.add(_contract); } function remove721Contract(address _contract) external onlyOwner { allowed721Contracts.remove(_contract); } function remove1155Contract(address _contract) external onlyOwner { allowed1155Contracts.remove(_contract); } function isValidItemType(string memory _itemType) external view returns (bool) { return itemTypes[_itemType]; } function isValidContract(address _contract) external view returns (bool) { return isValid721Contract(_contract) || isValid1155Contract(_contract); } function isValid721Contract(address _contract) public view returns (bool) { return allowed721Contracts.contains(_contract); } function isValid1155Contract(address _contract) public view returns (bool) { return allowed1155Contracts.contains(_contract); } }
25,645
208
// Events to manage Fidelity tokens transfer
event TransferSuccessful(address indexed from_, address indexed to_, uint256 amount_); event TransferFailed(address indexed from_, address indexed to_, uint256 amount_);
event TransferSuccessful(address indexed from_, address indexed to_, uint256 amount_); event TransferFailed(address indexed from_, address indexed to_, uint256 amount_);
23,773
12
// --- Admin ---
function pause() external onlyOwner { _pause(); }
function pause() external onlyOwner { _pause(); }
14,265
4
// Odin Browser Token Author: Odin browser group Contact: support@odinlink.com Home page: https:www.odinlink.com Telegram:https:t.me/OdinChain666666
library SafeMath{ function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
library SafeMath{ function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
17,977
37
// start time of the ICO
function getStartTime() public view returns (uint) { return m_startTime; }
function getStartTime() public view returns (uint) { return m_startTime; }
49,918
22
// Add signers to the token list
for(uint256 i = 0 ; i < signAddr.length ; i++){
for(uint256 i = 0 ; i < signAddr.length ; i++){
36,474
13
// Increase tracker and counter of regular assassin
_tokenIdRegularTrackerTeam.increment(); _regularTokenCounter += 1;
_tokenIdRegularTrackerTeam.increment(); _regularTokenCounter += 1;
41,308
169
// MGToken with Governance.
contract MGToken is ERC20("MGToken", "MG"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "MG::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "MG::delegateBySig: invalid nonce"); require(now <= expiry, "MG::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "MG::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying MGs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "MG::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
contract MGToken is ERC20("MGToken", "MG"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "MG::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "MG::delegateBySig: invalid nonce"); require(now <= expiry, "MG::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "MG::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying MGs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "MG::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
8,904
6
// Compound's CEtherDelegate Contract CTokens which wrap Ether and are delegated to Compound /
contract CEtherDelegate is CDelegateInterface, CEther { /** * @notice Construct an empty delegate */ constructor() public {} /** * @notice Called by the delegator on a delegate to initialize it for duty * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public { // Shh -- currently unused data; // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(hasAdminRights(), "only the admin may call _becomeImplementation"); } /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public { // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(hasAdminRights(), "only the admin may call _resignImplementation"); } }
contract CEtherDelegate is CDelegateInterface, CEther { /** * @notice Construct an empty delegate */ constructor() public {} /** * @notice Called by the delegator on a delegate to initialize it for duty * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public { // Shh -- currently unused data; // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(hasAdminRights(), "only the admin may call _becomeImplementation"); } /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public { // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(hasAdminRights(), "only the admin may call _resignImplementation"); } }
46,396
42
// there is no problem in usinghere instead of .mul()
uint256 public constant initialSupply = 28500000 * (10 ** uint256(decimals)); uint256 releaseTime; mapping(address => uint256) lockedAmount; event Swap(address account, uint256 value);
uint256 public constant initialSupply = 28500000 * (10 ** uint256(decimals)); uint256 releaseTime; mapping(address => uint256) lockedAmount; event Swap(address account, uint256 value);
11,943
0
// Number of tokens per 1 ETH = 5 (initial value)
_rate = 5;
_rate = 5;
68,914
63
// get OwnedLocations within bounds
function getOwnedLocationsInBounds( address _owner, uint16 minOwnedLat, uint16 minOwnedLng, uint16 maxOwnedLat, uint16 maxOwnedLng
function getOwnedLocationsInBounds( address _owner, uint16 minOwnedLat, uint16 minOwnedLng, uint16 maxOwnedLat, uint16 maxOwnedLng
8,073
490
// Reverts if the request is already pending requestId The request ID for fulfillment /
modifier notPendingRequest(bytes32 requestId) { require(s_pendingRequests[requestId] == address(0), "Request is already pending"); _; }
modifier notPendingRequest(bytes32 requestId) { require(s_pendingRequests[requestId] == address(0), "Request is already pending"); _; }
12,825
354
// Simply return the default, with no revert reason.
revertReason = _revertReason(uint256(-1));
revertReason = _revertReason(uint256(-1));
9,904
7
// Finally update ticket total
dailyPurchases.ticketsPurchased += tickets; dailyTicketsBought += tickets;
dailyPurchases.ticketsPurchased += tickets; dailyTicketsBought += tickets;
38,961