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
85
// Update number of storage slots pushed to -
mstore(0x120, add(1, mload(0x120)))
mstore(0x120, add(1, mload(0x120)))
8,671
2
// this operation provides when the data the Block Sat was last updated by a Node return _lastUpdated the epoch time since the last oracle update /
function getLastUpdated() external view returns (uint256 _lastUpdated);
function getLastUpdated() external view returns (uint256 _lastUpdated);
15,670
54
// Permissions this to a Permission module, which has a key of 1 If no Permission return false - note that IModule withPerm will allow ST owner all permissions anyway this allows individual modules to override this logic if needed (to not allow ST owner all permissions)
function checkPermission(address _delegate, address _module, bytes32 _perm) public view returns(bool);
function checkPermission(address _delegate, address _module, bytes32 _perm) public view returns(bool);
9,682
385
// Calculates partial value given a numerator and denominator rounded down./numerator Numerator./denominator Denominator./target Value to calculate partial of./ return Partial value of target rounded up.
function getPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) {
function getPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) {
14,403
133
// Emits a {RoleAdminChanged} event. /
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; }
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; }
91
1
// solium-enable no-empty-blocks // Public Views //Compute the start and end of the dispute's current or next appeal period, if possible._disputeID ID of the dispute. return The start and end of the period. /
function appealPeriod(uint256 _disputeID) public view returns (uint256 start, uint256 end) { if (appealDisputes[_disputeID].arbitrator != IArbitrator(address(0))) (start, end) = appealDisputes[_disputeID].arbitrator.appealPeriod( appealDisputes[_disputeID].appealDisputeID );
function appealPeriod(uint256 _disputeID) public view returns (uint256 start, uint256 end) { if (appealDisputes[_disputeID].arbitrator != IArbitrator(address(0))) (start, end) = appealDisputes[_disputeID].arbitrator.appealPeriod( appealDisputes[_disputeID].appealDisputeID );
12,567
103
// Time pricing related private variables /
uint256 private _minTimeStamp; uint256 private _maxTimeStamp; mapping(uint256 => uint256) private _timeStampToPrice;
uint256 private _minTimeStamp; uint256 private _maxTimeStamp; mapping(uint256 => uint256) private _timeStampToPrice;
54,762
5
// Constructor // /
constructor(address storageAddress) public Base(storageAddress) {} /** Fallback Method */ /** Functions */ /** @notice It registers a new post action in the platform. @dev The sender must be a super user. @dev The post action address must not be empty. @param newPostAction the post action address to register. */ function registerPostAction(address newPostAction) external onlySuperUser() nonReentrant() isValidAddress(newPostAction) postActionNotExists(newPostAction) { actions[newPostAction] = true; emit NewPostActionRegistered(address(this), newPostAction, msg.sender, now); }
constructor(address storageAddress) public Base(storageAddress) {} /** Fallback Method */ /** Functions */ /** @notice It registers a new post action in the platform. @dev The sender must be a super user. @dev The post action address must not be empty. @param newPostAction the post action address to register. */ function registerPostAction(address newPostAction) external onlySuperUser() nonReentrant() isValidAddress(newPostAction) postActionNotExists(newPostAction) { actions[newPostAction] = true; emit NewPostActionRegistered(address(this), newPostAction, msg.sender, now); }
7,653
15
// Withdraws PAY claimed by the user.
function withdraw() { // Store the user's amount of claimed PAY as the amount of PAY to withdraw. uint256 pay_to_withdraw = pay_claimed[msg.sender]; // Update the user's amount of claimed PAY first to prevent recursive call. pay_claimed[msg.sender] = 0; // Update the total amount of claimed PAY. total_pay_claimed -= pay_to_withdraw; // Send the user their PAY. Throws on failure to prevent loss of funds. token.transfer(msg.sender, pay_to_withdraw); }
function withdraw() { // Store the user's amount of claimed PAY as the amount of PAY to withdraw. uint256 pay_to_withdraw = pay_claimed[msg.sender]; // Update the user's amount of claimed PAY first to prevent recursive call. pay_claimed[msg.sender] = 0; // Update the total amount of claimed PAY. total_pay_claimed -= pay_to_withdraw; // Send the user their PAY. Throws on failure to prevent loss of funds. token.transfer(msg.sender, pay_to_withdraw); }
39,650
29
// calculate amount of shares to be minted to the user
uint256 shares = _aethContract.bondsToShares(value);
uint256 shares = _aethContract.bondsToShares(value);
8,489
10
// Calculate the hash of the solution which will be the index in the mapping
uint256 indexHash = calculateHashIndexOfSolution(a, a_p, b, b_p, c, c_p, h, k, input);
uint256 indexHash = calculateHashIndexOfSolution(a, a_p, b, b_p, c, c_p, h, k, input);
2,659
2
// Struct to provide the details of the token and it is populated after token is mintedtokenSupply total supply of the token. tokenPriceprice of each token. expectedUsageLife time period to which token can be used. isMintedtells whether the token is minted or not. If `true` then token is minted and if `false` the token is not minted. expireOnexpiry date for the token. /
struct TokenDetails { // 256-bits uint256 totalSupply; // 192-bits uint104 tokenPrice; uint32 expectedUsageLife; bool isMinted; uint48 expireOn; }
struct TokenDetails { // 256-bits uint256 totalSupply; // 192-bits uint104 tokenPrice; uint32 expectedUsageLife; bool isMinted; uint48 expireOn; }
24,727
13
// address of the uniswap v2 router
address private constant UNISWAP_V2_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address private constant UNISWAP_V2_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
2,720
374
// disable transfers
function _transfer(address _from, address _to, uint256 _amount) internal override { revert("NON_TRANSFERABLE"); }
function _transfer(address _from, address _to, uint256 _amount) internal override { revert("NON_TRANSFERABLE"); }
30,927
203
// allows the caller to claim network token balance that is no longer lockednote that the function can revert if the range is too large_startIndexstart index in the caller's list of locked balances _endIndexend index in the caller's list of locked balances (exclusive) /
function claimBalance(uint256 _startIndex, uint256 _endIndex) external protected { // get the locked balances from the store (uint256[] memory amounts, uint256[] memory expirationTimes) = store.lockedBalanceRange(msg.sender, _startIndex, _endIndex); uint256 totalAmount = 0; uint256 length = amounts.length; assert(length == expirationTimes.length); // reverse iteration since we're removing from the list for (uint256 i = length; i > 0; i--) { uint256 index = i - 1; if (expirationTimes[index] > time()) { continue; } // remove the locked balance item store.removeLockedBalance(msg.sender, _startIndex + index); totalAmount = totalAmount.add(amounts[index]); } if (totalAmount > 0) { // transfer the tokens to the caller in a single call store.withdrawTokens(networkToken, msg.sender, totalAmount); } }
function claimBalance(uint256 _startIndex, uint256 _endIndex) external protected { // get the locked balances from the store (uint256[] memory amounts, uint256[] memory expirationTimes) = store.lockedBalanceRange(msg.sender, _startIndex, _endIndex); uint256 totalAmount = 0; uint256 length = amounts.length; assert(length == expirationTimes.length); // reverse iteration since we're removing from the list for (uint256 i = length; i > 0; i--) { uint256 index = i - 1; if (expirationTimes[index] > time()) { continue; } // remove the locked balance item store.removeLockedBalance(msg.sender, _startIndex + index); totalAmount = totalAmount.add(amounts[index]); } if (totalAmount > 0) { // transfer the tokens to the caller in a single call store.withdrawTokens(networkToken, msg.sender, totalAmount); } }
14,096
77
// require(_start.add(_cliff) < block.timestamp, "not that time");
if ( _vestingList[acc].Start.add(_vestingList[acc].Cliff) > block.timestamp ) {
if ( _vestingList[acc].Start.add(_vestingList[acc].Cliff) > block.timestamp ) {
52,406
66
// SZ: Change here to collection address before deploy // SZ: price1..3 in AIRX per 1 ETH // SZ: lev1..2 in ETH // SZ: AIRX constructor with HardCap in AIRX tokens /
function SalesManagerUpgradable () public { tokenAddress = new AirEX(5550000 ether); }
function SalesManagerUpgradable () public { tokenAddress = new AirEX(5550000 ether); }
49,937
13
// Keep adapter interface. We only pay the tx gas for this bridge.
function bridgeCost(uint256, uint256, address) external pure returns (uint256 gasCost) { return 0; // unused; }
function bridgeCost(uint256, uint256, address) external pure returns (uint256 gasCost) { return 0; // unused; }
6,573
103
// Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. a a FixedPoint. b a FixedPoint.return the product of `a` and `b`. /
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } }
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } }
5,454
0
// See {_setURI} for more information. /
constructor(string memory uri_) ERC1155(uri_) {}
constructor(string memory uri_) ERC1155(uri_) {}
22,777
19
// EFFECTS /
_totalSold.add(n);
_totalSold.add(n);
9,016
22
// _NAME.concatenate("paused")
); if(from.isNull()){ LogicConstraints.alwaysRevert(
); if(from.isNull()){ LogicConstraints.alwaysRevert(
40,997
293
// liquidity fee precision
uint256 public constant PRECISION = 1_000;
uint256 public constant PRECISION = 1_000;
10,343
7
// arb here
bool success1 = true; bool success2 = true; for(uint i=0; i<_loop; i++){ if(success1) (success1, ) = address(this).call(abi.encodeWithSelector(this.arb_DAI.selector)); if(success2) (success2, ) = address(this).call(abi.encodeWithSelector(this.arb_TRIBE.selector)); }
bool success1 = true; bool success2 = true; for(uint i=0; i<_loop; i++){ if(success1) (success1, ) = address(this).call(abi.encodeWithSelector(this.arb_DAI.selector)); if(success2) (success2, ) = address(this).call(abi.encodeWithSelector(this.arb_TRIBE.selector)); }
13,015
4
// Query the current deposit count./ return The deposit count encoded as a little endian 64-bit number.
function get_deposit_count() external view returns (bytes memory);
function get_deposit_count() external view returns (bytes memory);
42,347
12
// If market creation was stopped then it can be started again. If market creation wasn't stopped then you must wait for market end time to resolve.
require(block.timestamp >= nextResolutionTime, "Must wait for market resolution"); require(_roundIds.length == coins.length, "Must specify one roundId for each coin"); uint256 _resolutionTime = nextResolutionTime; nextResolutionTime = _nextResolutionTime;
require(block.timestamp >= nextResolutionTime, "Must wait for market resolution"); require(_roundIds.length == coins.length, "Must specify one roundId for each coin"); uint256 _resolutionTime = nextResolutionTime; nextResolutionTime = _nextResolutionTime;
30,332
4
// Admin can set allowTransfer to allow user transfer token normally /
function adminUnlockTransfer() public onlyOwner returns (bool) { require(!allowTransfer, "Already-allowed"); allowTransfer = true; return true; }
function adminUnlockTransfer() public onlyOwner returns (bool) { require(!allowTransfer, "Already-allowed"); allowTransfer = true; return true; }
20,769
166
// Returns maximum total supply of the token
function getMaxTotalSupply() external pure returns (uint256) { return _maxTotalSupply; }
function getMaxTotalSupply() external pure returns (uint256) { return _maxTotalSupply; }
27,946
115
// update remainingToRaise in case amountToSell is zero (everything has been sold)
uint256 remainingToRaise = (either(multiply(wad, RAY) >= bids[id].amountToRaise, bids[id].amountToSell == 0)) ? bids[id].amountToRaise : subtract(bids[id].amountToRaise, multiply(wad, RAY));
uint256 remainingToRaise = (either(multiply(wad, RAY) >= bids[id].amountToRaise, bids[id].amountToSell == 0)) ? bids[id].amountToRaise : subtract(bids[id].amountToRaise, multiply(wad, RAY));
47,483
191
// 挖矿手续费比例
paramsMapping[3101] = 100;//百分比 n/1000
paramsMapping[3101] = 100;//百分比 n/1000
7,405
12
// Set Uint value in InstaMemory Contract. /
function setUint(uint setId, uint val) internal { if (setId != 0) MemoryInterface(getMemoryAddr()).setUint(setId, val); }
function setUint(uint setId, uint val) internal { if (setId != 0) MemoryInterface(getMemoryAddr()).setUint(setId, val); }
39,361
65
// totalHsu
totalHsu = totalHsu.add(rewardsOfPool).add(hsuCount);
totalHsu = totalHsu.add(rewardsOfPool).add(hsuCount);
9,702
32
// if the board is now full, then go ahead and make it live.
if ((Battleboards[battleboardId].numTeams1 == 3) && (Battleboards[battleboardId].numTeams2 ==3)) {Battleboards[battleboardId].isLive = true;}
if ((Battleboards[battleboardId].numTeams1 == 3) && (Battleboards[battleboardId].numTeams2 ==3)) {Battleboards[battleboardId].isLive = true;}
49,791
1
// Initial request /
function requestElectionWinner() public returns (bytes32 requestId)
function requestElectionWinner() public returns (bytes32 requestId)
40,402
7
// The ID of the permission required to call the `updateVotingSettings` function.
bytes32 public constant UPDATE_VOTING_SETTINGS_PERMISSION_ID = keccak256("UPDATE_VOTING_SETTINGS_PERMISSION");
bytes32 public constant UPDATE_VOTING_SETTINGS_PERMISSION_ID = keccak256("UPDATE_VOTING_SETTINGS_PERMISSION");
9,999
10
// The count of s hitting their target
uint256 public count;
uint256 public count;
21,315
178
// useful for when we want the ability to add tokens without trading. For instance, the initial liquidity queueing event.
function setWhiteListUser(address user, bool whiteList) external onlyOwner { whiteListUsers[user] = whiteList; }
function setWhiteListUser(address user, bool whiteList) external onlyOwner { whiteListUsers[user] = whiteList; }
6,706
3
// Read/write proposals
mapping(uint => Proposal) public proposals;
mapping(uint => Proposal) public proposals;
29,400
6
// Combines 'self' and 'other' into a single array. Returns the concatenated arrays:[self[0], self[1], ... , self[self.length - 1], other[0], other[1], ... , other[other.length - 1]] The length of the new array is 'self.length + other.length'
function concat(bytes memory self, bytes memory other) internal pure returns (bytes memory)
function concat(bytes memory self, bytes memory other) internal pure returns (bytes memory)
11,138
359
// hasVotedOnUpgradePoll(): returns true if _galaxy has voted on the _proposal
function hasVotedOnUpgradePoll(uint8 _galaxy, address _proposal) external view returns (bool result)
function hasVotedOnUpgradePoll(uint8 _galaxy, address _proposal) external view returns (bool result)
39,197
66
// get level from xp
function calclevel(uint16 _xp) internal pure returns (uint8) { return uint8(sqrt(5*uint32(_xp)) / 4); }
function calclevel(uint16 _xp) internal pure returns (uint8) { return uint8(sqrt(5*uint32(_xp)) / 4); }
12,066
9
// Admin is initialized to the contract creator.
address public admin = msg.sender;
address public admin = msg.sender;
11,766
31
// Add liquidity.
router.addLiquidityETH{value: ethAmount}(
router.addLiquidityETH{value: ethAmount}(
13,789
113
// Emitted when validity of a forge-factory pair is updated _forgeId the forge id _marketFactoryId the market factory id _valid valid or not // Emitted when Pendle and PendleFactory addresses have been updated. treasury The address of the new treasury contract. // Emitted when LockParams is changed // Emitted when ExpiryDivisor is changed // Emitted when forge fee is changed // Emitted when interestUpdateRateDeltaForMarket is changed interestUpdateRateDeltaForMarket new interestUpdateRateDeltaForMarket setting // Emitted when market fees are changed _swapFee new swapFee setting _protocolSwapFee new protocolSwapFee setting // Emitted when the curve shift block delta is changed _blockDelta new block delta setting //
event NewMarketFactory(bytes32 indexed marketFactoryId, address indexed marketFactoryAddress);
event NewMarketFactory(bytes32 indexed marketFactoryId, address indexed marketFactoryAddress);
46,577
2
// how much chips max you can be buy per tx
uint16 public maxChipsBuyableAtOnce = 200;
uint16 public maxChipsBuyableAtOnce = 200;
4,756
1
// but ends before the requested end time
{ length++; }
{ length++; }
24,105
46
// Use the public getter function for earnTerms for a single earnTermreturn An array of type EarnTerm /
function getAllEarnTerms() public view returns (EarnTerm[] memory) { return earnTerms; }
function getAllEarnTerms() public view returns (EarnTerm[] memory) { return earnTerms; }
14,492
122
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
_approve(address(this), address(uniswapV2Router), tokenAmount);
18,706
43
// And transfer the fees from the Borrower to the Loan
underlying.safeTransferFrom(_borrower, address(_newLoan), _feeAmount);
underlying.safeTransferFrom(_borrower, address(_newLoan), _feeAmount);
38,608
324
// Accumulate the amount FIN mined by borrowing between _lastBlock and _currentBlock /
function calculateBorrowFIN(uint256 _lastBlock, address _token, address _accountAddr, uint256 _currentBlock) internal { Bank bank = globalConfig.bank(); uint256 indexDifference = bank.borrowFINRateIndex(_token, _currentBlock) .sub(bank.borrowFINRateIndex(_token, _lastBlock)); uint256 getFIN = getBorrowBalanceCurrent(_token, _accountAddr) .mul(indexDifference) .div(bank.borrowRateIndex(_token, _currentBlock)); FINAmount[_accountAddr] = FINAmount[_accountAddr].add(getFIN); }
function calculateBorrowFIN(uint256 _lastBlock, address _token, address _accountAddr, uint256 _currentBlock) internal { Bank bank = globalConfig.bank(); uint256 indexDifference = bank.borrowFINRateIndex(_token, _currentBlock) .sub(bank.borrowFINRateIndex(_token, _lastBlock)); uint256 getFIN = getBorrowBalanceCurrent(_token, _accountAddr) .mul(indexDifference) .div(bank.borrowRateIndex(_token, _currentBlock)); FINAmount[_accountAddr] = FINAmount[_accountAddr].add(getFIN); }
54,545
1
// Returns the metadata URI for an NFT. See `BatchMintMetadata` for handling of metadata in this contract. _tokenId The tokenId of an NFT. /
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { string memory cid = "bafybeiaxucaszbmk6zmjtmxixzrifwdol4khjvq2m3oew64ukliy7ivug4";
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { string memory cid = "bafybeiaxucaszbmk6zmjtmxixzrifwdol4khjvq2m3oew64ukliy7ivug4";
17,881
179
// Get authorize contract by id _cid Then authorize contract idreturn The authorize contract info(_name, _acontract) /
function getAuthorizeContract(uint256 _cid) external view
function getAuthorizeContract(uint256 _cid) external view
14,502
82
// first 2 hours
uint256 tokens = amount * tokensPerUSDT; require( amount <= purchaseLimitStageOne, "Over purchase limit in stage one" ); require( whitelistAmount[msg.sender].add(amount) <= purchaseLimitStageOne, "can't purchase more than allowed amount stage one" ); usdt.safeTransferFrom(msg.sender, collector, amount);
uint256 tokens = amount * tokensPerUSDT; require( amount <= purchaseLimitStageOne, "Over purchase limit in stage one" ); require( whitelistAmount[msg.sender].add(amount) <= purchaseLimitStageOne, "can't purchase more than allowed amount stage one" ); usdt.safeTransferFrom(msg.sender, collector, amount);
38,823
24
// Call the specified target and supply the specified data.
(ok, returnData) = target.call.value(0)(data); emit Call(target, amount, data, ok, returnData);
(ok, returnData) = target.call.value(0)(data); emit Call(target, amount, data, ok, returnData);
40,044
59
// This is an alternative to {approve} that can be used as a mitigation forproblems described in {BEP20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address.- `spender` must have allowance for the caller of at least`subtractedValue`. /
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero")); return true; }
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero")); return true; }
10,930
8
// struct for ballot
struct Vote { bytes32 voteData; bytes32 castTsAndSender; bytes extra; }
struct Vote { bytes32 voteData; bytes32 castTsAndSender; bytes extra; }
4,033
118
// for non-tippyTopHat wearers: destination local tophat must be either... a) the same as origin local tophat, or b) within the tippy top hat's local tree
uint256 originLocalTopHat = linkedAdmin >> 224 << 224; // (256 - TOPHAT_ADDRESS_SPACE); if (destLocalTopHat != originLocalTopHat && destLocalTopHat != tippyTopHat) { revert CrossTreeLinkage(); }
uint256 originLocalTopHat = linkedAdmin >> 224 << 224; // (256 - TOPHAT_ADDRESS_SPACE); if (destLocalTopHat != originLocalTopHat && destLocalTopHat != tippyTopHat) { revert CrossTreeLinkage(); }
22,011
79
// hasBeenLinked(): returns true if the point has ever been assigned keys
function hasBeenLinked(uint32 _point) view external returns (bool result)
function hasBeenLinked(uint32 _point) view external returns (bool result)
38,460
17
// PRIVILEGED FACTORY FUNCTION. Adds a newly deployed Domani tokens as an enabled Domani._domani Address of the Domani contract to add /
function addDomani(address _domani) external onlyInitialized onlyFactory { require(!isDomani[_domani], "Domani already exists"); isDomani[_domani] = true; sets.push(_domani); emit DomaniAdded(_domani, msg.sender); }
function addDomani(address _domani) external onlyInitialized onlyFactory { require(!isDomani[_domani], "Domani already exists"); isDomani[_domani] = true; sets.push(_domani); emit DomaniAdded(_domani, msg.sender); }
6,583
192
// Claim pool ownership with new address
function becomePoolOwner(uint256 _pid) external { if (tempAdmin[_pid] == _msgSender()) poolInfo[_pid].owner = _msgSender(); }
function becomePoolOwner(uint256 _pid) external { if (tempAdmin[_pid] == _msgSender()) poolInfo[_pid].owner = _msgSender(); }
34,318
119
// Allows the owner to withdraw profits and failed payouts. Owner should check failedPayoutsSum to not withdraw extra.
function withdraw(uint256 amount) onlyContractOwner public { msg.sender.transfer(amount); }
function withdraw(uint256 amount) onlyContractOwner public { msg.sender.transfer(amount); }
19,063
7
// Auction start block. Where bidding of any ticker can start
uint256 public startBlock;
uint256 public startBlock;
11,618
538
// revokes burner role from address/burner ex burner
function revokeBurner(address burner) external override onlyGovernor { revokeRole(BURNER_ROLE, burner); }
function revokeBurner(address burner) external override onlyGovernor { revokeRole(BURNER_ROLE, burner); }
9,245
39
// Our last node is either an extension node or a leaf node with a different key.
bytes memory lastNodeKey = _getNodeKey(lastNode); uint256 sharedNibbleLength = _getSharedNibbleLength(lastNodeKey, keyRemainder); if (sharedNibbleLength != 0) {
bytes memory lastNodeKey = _getNodeKey(lastNode); uint256 sharedNibbleLength = _getSharedNibbleLength(lastNodeKey, keyRemainder); if (sharedNibbleLength != 0) {
12,477
353
// To get all the registered Gateway contracts set count to `0`.
function getMintGatewaySymbols(uint256 from, uint256 count) external view returns (string[] memory) { return enumerateSet(mintGatewaySymbols, from, count); }
function getMintGatewaySymbols(uint256 from, uint256 count) external view returns (string[] memory) { return enumerateSet(mintGatewaySymbols, from, count); }
33,491
23
// A mixin that implements vairous useful views that are used externally butaren't used inside the core contract (so don't need to clutter the contract file) /
contract MixinFuturesViews is FuturesMarketBase { /* * Sizes of the long and short sides of the market (in sUSD) */ function marketSizes() public view returns (uint long, uint short) { int size = int(marketSize); int skew = marketSkew; return (_abs(size.add(skew).div(2)), _abs(size.sub(skew).div(2))); } /* * The debt contributed by this market to the overall system. * The total market debt is equivalent to the sum of remaining margins in all open positions. */ function marketDebt() external view returns (uint debt, bool invalid) { (uint price, bool isInvalid) = assetPrice(); return (_marketDebt(price), isInvalid); } /* * The current funding rate as determined by the market skew; this is returned as a percentage per day. * If this is positive, shorts pay longs, if it is negative, longs pay shorts. */ function currentFundingRate() external view returns (int) { (uint price, ) = assetPrice(); return _currentFundingRate(price); } /* * The funding per base unit accrued since the funding rate was last recomputed, which has not yet * been persisted in the funding sequence. */ function unrecordedFunding() external view returns (int funding, bool invalid) { (uint price, bool isInvalid) = assetPrice(); return (_unrecordedFunding(price), isInvalid); } /* * The number of entries in the funding sequence. */ function fundingSequenceLength() external view returns (uint) { return fundingSequence.length; } /* * The notional value of a position is its size multiplied by the current price. Margin and leverage are ignored. */ function notionalValue(address account) external view returns (int value, bool invalid) { (uint price, bool isInvalid) = assetPrice(); return (_notionalValue(positions[account].size, price), isInvalid); } /* * The PnL of a position is the change in its notional value. Funding is not taken into account. */ function profitLoss(address account) external view returns (int pnl, bool invalid) { (uint price, bool isInvalid) = assetPrice(); return (_profitLoss(positions[account], price), isInvalid); } /* * The funding accrued in a position since it was opened; this does not include PnL. */ function accruedFunding(address account) external view returns (int funding, bool invalid) { (uint price, bool isInvalid) = assetPrice(); return (_accruedFunding(positions[account], price), isInvalid); } /* * The initial margin plus profit and funding; returns zero balance if losses exceed the initial margin. */ function remainingMargin(address account) external view returns (uint marginRemaining, bool invalid) { (uint price, bool isInvalid) = assetPrice(); return (_remainingMargin(positions[account], price), isInvalid); } /* * The approximate amount of margin the user may withdraw given their current position; this underestimates the * true value slightly. */ function accessibleMargin(address account) external view returns (uint marginAccessible, bool invalid) { (uint price, bool isInvalid) = assetPrice(); return (_accessibleMargin(positions[account], price), isInvalid); } /* * The price at which a position is subject to liquidation; otherwise the price at which the user's remaining * margin has run out. When they have just enough margin left to pay a liquidator, then they are liquidated. * If a position is long, then it is safe as long as the current price is above the liquidation price; if it is * short, then it is safe whenever the current price is below the liquidation price. * A position's accurate liquidation price can move around slightly due to accrued funding. */ function liquidationPrice(address account) external view returns (uint price, bool invalid) { (uint aPrice, bool isInvalid) = assetPrice(); uint liqPrice = _approxLiquidationPrice(positions[account], aPrice); return (liqPrice, isInvalid); } /** * The fee paid to liquidator in the event of successful liquidation of an account at current price. * Returns 0 if account cannot be liquidated right now. * @param account address of the trader's account * @return fee that will be paid for liquidating the account if it can be liquidated * in sUSD fixed point decimal units or 0 if account is not liquidatable. */ function liquidationFee(address account) external view returns (uint) { (uint price, bool invalid) = assetPrice(); if (!invalid && _canLiquidate(positions[account], price)) { return _liquidationFee(int(positions[account].size), price); } else { // theoretically we can calculate a value, but this value is always incorrect because // it's for a price at which liquidation cannot happen - so is misleading, because // it won't be paid, and what will be paid is a different fee (for a different price) return 0; } } /* * True if and only if a position is ready to be liquidated. */ function canLiquidate(address account) external view returns (bool) { (uint price, bool invalid) = assetPrice(); return !invalid && _canLiquidate(positions[account], price); } /* * Reports the fee for submitting an order of a given size. Orders that increase the skew will be more * expensive than ones that decrease it. Dynamic fee is added according to the recent volatility * according to SIP-184. * @param sizeDelta size of the order in baseAsset units (negative numbers for shorts / selling) * @return fee in sUSD decimal, and invalid boolean flag for invalid rates or dynamic fee that is * too high due to recent volatility. */ function orderFee(int sizeDelta) external view returns (uint fee, bool invalid) { (uint price, bool isInvalid) = assetPrice(); (uint dynamicFeeRate, bool tooVolatile) = _dynamicFeeRate(); TradeParams memory params = TradeParams({ sizeDelta: sizeDelta, price: price, takerFee: _takerFee(marketKey), makerFee: _makerFee(marketKey), trackingCode: bytes32("") }); return (_orderFee(params, dynamicFeeRate), isInvalid || tooVolatile); } /* * Returns all new position details if a given order from `sender` was confirmed at the current price. */ function postTradeDetails(int sizeDelta, address sender) external view returns ( uint margin, int size, uint price, uint liqPrice, uint fee, Status status ) { bool invalid; (price, invalid) = assetPrice(); if (invalid) { return (0, 0, 0, 0, 0, Status.InvalidPrice); } TradeParams memory params = TradeParams({ sizeDelta: sizeDelta, price: price, takerFee: _takerFee(marketKey), makerFee: _makerFee(marketKey), trackingCode: bytes32("") }); (Position memory newPosition, uint fee_, Status status_) = _postTradeDetails(positions[sender], params); liqPrice = _approxLiquidationPrice(newPosition, newPosition.lastPrice); return (newPosition.margin, newPosition.size, newPosition.lastPrice, liqPrice, fee_, status_); } /// helper methods calculates the approximate liquidation price function _approxLiquidationPrice(Position memory position, uint currentPrice) internal view returns (uint) { int positionSize = int(position.size); // short circuit if (positionSize == 0) { return 0; } // price = lastPrice + (liquidationMargin - margin) / positionSize - netAccrued int fundingPerUnit = _netFundingPerUnit(position.lastFundingIndex, currentPrice); // minimum margin beyond which position can be liqudiated uint liqMargin = _liquidationMargin(positionSize, currentPrice); // A position can be liquidated whenever: // remainingMargin <= liquidationMargin // Hence, expanding the definition of remainingMargin the exact price // at which a position can first be liquidated is: // margin + profitLoss + funding = liquidationMargin // substitute with: profitLoss = (price - last-price) * positionSize // and also with: funding = netFundingPerUnit * positionSize // we get: margin + (price - last-price) * positionSize + netFundingPerUnit * positionSize = liquidationMargin // moving around: price = lastPrice + (liquidationMargin - margin) / positionSize - netFundingPerUnit int result = int(position.lastPrice).add(int(liqMargin).sub(int(position.margin)).divideDecimal(positionSize)).sub( fundingPerUnit ); // If the user has leverage less than 1, their liquidation price may actually be negative; return 0 instead. return uint(_max(0, result)); } }
contract MixinFuturesViews is FuturesMarketBase { /* * Sizes of the long and short sides of the market (in sUSD) */ function marketSizes() public view returns (uint long, uint short) { int size = int(marketSize); int skew = marketSkew; return (_abs(size.add(skew).div(2)), _abs(size.sub(skew).div(2))); } /* * The debt contributed by this market to the overall system. * The total market debt is equivalent to the sum of remaining margins in all open positions. */ function marketDebt() external view returns (uint debt, bool invalid) { (uint price, bool isInvalid) = assetPrice(); return (_marketDebt(price), isInvalid); } /* * The current funding rate as determined by the market skew; this is returned as a percentage per day. * If this is positive, shorts pay longs, if it is negative, longs pay shorts. */ function currentFundingRate() external view returns (int) { (uint price, ) = assetPrice(); return _currentFundingRate(price); } /* * The funding per base unit accrued since the funding rate was last recomputed, which has not yet * been persisted in the funding sequence. */ function unrecordedFunding() external view returns (int funding, bool invalid) { (uint price, bool isInvalid) = assetPrice(); return (_unrecordedFunding(price), isInvalid); } /* * The number of entries in the funding sequence. */ function fundingSequenceLength() external view returns (uint) { return fundingSequence.length; } /* * The notional value of a position is its size multiplied by the current price. Margin and leverage are ignored. */ function notionalValue(address account) external view returns (int value, bool invalid) { (uint price, bool isInvalid) = assetPrice(); return (_notionalValue(positions[account].size, price), isInvalid); } /* * The PnL of a position is the change in its notional value. Funding is not taken into account. */ function profitLoss(address account) external view returns (int pnl, bool invalid) { (uint price, bool isInvalid) = assetPrice(); return (_profitLoss(positions[account], price), isInvalid); } /* * The funding accrued in a position since it was opened; this does not include PnL. */ function accruedFunding(address account) external view returns (int funding, bool invalid) { (uint price, bool isInvalid) = assetPrice(); return (_accruedFunding(positions[account], price), isInvalid); } /* * The initial margin plus profit and funding; returns zero balance if losses exceed the initial margin. */ function remainingMargin(address account) external view returns (uint marginRemaining, bool invalid) { (uint price, bool isInvalid) = assetPrice(); return (_remainingMargin(positions[account], price), isInvalid); } /* * The approximate amount of margin the user may withdraw given their current position; this underestimates the * true value slightly. */ function accessibleMargin(address account) external view returns (uint marginAccessible, bool invalid) { (uint price, bool isInvalid) = assetPrice(); return (_accessibleMargin(positions[account], price), isInvalid); } /* * The price at which a position is subject to liquidation; otherwise the price at which the user's remaining * margin has run out. When they have just enough margin left to pay a liquidator, then they are liquidated. * If a position is long, then it is safe as long as the current price is above the liquidation price; if it is * short, then it is safe whenever the current price is below the liquidation price. * A position's accurate liquidation price can move around slightly due to accrued funding. */ function liquidationPrice(address account) external view returns (uint price, bool invalid) { (uint aPrice, bool isInvalid) = assetPrice(); uint liqPrice = _approxLiquidationPrice(positions[account], aPrice); return (liqPrice, isInvalid); } /** * The fee paid to liquidator in the event of successful liquidation of an account at current price. * Returns 0 if account cannot be liquidated right now. * @param account address of the trader's account * @return fee that will be paid for liquidating the account if it can be liquidated * in sUSD fixed point decimal units or 0 if account is not liquidatable. */ function liquidationFee(address account) external view returns (uint) { (uint price, bool invalid) = assetPrice(); if (!invalid && _canLiquidate(positions[account], price)) { return _liquidationFee(int(positions[account].size), price); } else { // theoretically we can calculate a value, but this value is always incorrect because // it's for a price at which liquidation cannot happen - so is misleading, because // it won't be paid, and what will be paid is a different fee (for a different price) return 0; } } /* * True if and only if a position is ready to be liquidated. */ function canLiquidate(address account) external view returns (bool) { (uint price, bool invalid) = assetPrice(); return !invalid && _canLiquidate(positions[account], price); } /* * Reports the fee for submitting an order of a given size. Orders that increase the skew will be more * expensive than ones that decrease it. Dynamic fee is added according to the recent volatility * according to SIP-184. * @param sizeDelta size of the order in baseAsset units (negative numbers for shorts / selling) * @return fee in sUSD decimal, and invalid boolean flag for invalid rates or dynamic fee that is * too high due to recent volatility. */ function orderFee(int sizeDelta) external view returns (uint fee, bool invalid) { (uint price, bool isInvalid) = assetPrice(); (uint dynamicFeeRate, bool tooVolatile) = _dynamicFeeRate(); TradeParams memory params = TradeParams({ sizeDelta: sizeDelta, price: price, takerFee: _takerFee(marketKey), makerFee: _makerFee(marketKey), trackingCode: bytes32("") }); return (_orderFee(params, dynamicFeeRate), isInvalid || tooVolatile); } /* * Returns all new position details if a given order from `sender` was confirmed at the current price. */ function postTradeDetails(int sizeDelta, address sender) external view returns ( uint margin, int size, uint price, uint liqPrice, uint fee, Status status ) { bool invalid; (price, invalid) = assetPrice(); if (invalid) { return (0, 0, 0, 0, 0, Status.InvalidPrice); } TradeParams memory params = TradeParams({ sizeDelta: sizeDelta, price: price, takerFee: _takerFee(marketKey), makerFee: _makerFee(marketKey), trackingCode: bytes32("") }); (Position memory newPosition, uint fee_, Status status_) = _postTradeDetails(positions[sender], params); liqPrice = _approxLiquidationPrice(newPosition, newPosition.lastPrice); return (newPosition.margin, newPosition.size, newPosition.lastPrice, liqPrice, fee_, status_); } /// helper methods calculates the approximate liquidation price function _approxLiquidationPrice(Position memory position, uint currentPrice) internal view returns (uint) { int positionSize = int(position.size); // short circuit if (positionSize == 0) { return 0; } // price = lastPrice + (liquidationMargin - margin) / positionSize - netAccrued int fundingPerUnit = _netFundingPerUnit(position.lastFundingIndex, currentPrice); // minimum margin beyond which position can be liqudiated uint liqMargin = _liquidationMargin(positionSize, currentPrice); // A position can be liquidated whenever: // remainingMargin <= liquidationMargin // Hence, expanding the definition of remainingMargin the exact price // at which a position can first be liquidated is: // margin + profitLoss + funding = liquidationMargin // substitute with: profitLoss = (price - last-price) * positionSize // and also with: funding = netFundingPerUnit * positionSize // we get: margin + (price - last-price) * positionSize + netFundingPerUnit * positionSize = liquidationMargin // moving around: price = lastPrice + (liquidationMargin - margin) / positionSize - netFundingPerUnit int result = int(position.lastPrice).add(int(liqMargin).sub(int(position.margin)).divideDecimal(positionSize)).sub( fundingPerUnit ); // If the user has leverage less than 1, their liquidation price may actually be negative; return 0 instead. return uint(_max(0, result)); } }
8,935
86
// Transfer Fee
event TransferFeeChanged(uint256 newFee); event FeeRecipientChange(address account); event AddFeeException(address account); event RemoveFeeException(address account); bool private activeFee; uint256 public transferFee; // Fee as percentage, where 123 = 1.23% address public feeRecipient; // Account or contract to send transfer fees to
event TransferFeeChanged(uint256 newFee); event FeeRecipientChange(address account); event AddFeeException(address account); event RemoveFeeException(address account); bool private activeFee; uint256 public transferFee; // Fee as percentage, where 123 = 1.23% address public feeRecipient; // Account or contract to send transfer fees to
47,375
28
// Returns true if `account` is a contract. [IMPORTANT]====It is unsafe to assume that an address for which this function returnsfalse is an externally-owned account (EOA) and not a contract. Among others, `isContract` will return false for the followingtypes of addresses:- an externally-owned account - a contract in construction - an address where a contract will be created - an address where a contract lived, but was destroyed==== /
function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; }
function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; }
151
253
// ensure that there's liquidity in the pair
require(_reserve0 != 0 && _reserve1 != 0, "TWAPOracle: NO_RESERVES");
require(_reserve0 != 0 && _reserve1 != 0, "TWAPOracle: NO_RESERVES");
18,536
130
// transfer and transferFrom both ultimately call this function, so we check blacklist and pay staking fee here.
function transferAllArgsNoAllowance(address _from, address _to, uint256 _value) internal { require(!blackList.onList(_from)); require(!blackList.onList(_to)); super.transferAllArgsNoAllowance(_from, _to, _value); payStakingFee(_to, _value, transferFeeNumerator, transferFeeDenominator, burnFeeFlat, _from); }
function transferAllArgsNoAllowance(address _from, address _to, uint256 _value) internal { require(!blackList.onList(_from)); require(!blackList.onList(_to)); super.transferAllArgsNoAllowance(_from, _to, _value); payStakingFee(_to, _value, transferFeeNumerator, transferFeeDenominator, burnFeeFlat, _from); }
25,969
50
// Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. _beneficiaries Addresses to be added to the whitelist /
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } }
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } }
63,697
382
// 获取某个头寸,以基金本币衡量的所有资产/pool 交易池索引号/token 头寸索引号/ return amount 资产数量
function assets( Info storage self, address pool, address token, mapping(address => bytes) storage sellPath, address uniV3Factory
function assets( Info storage self, address pool, address token, mapping(address => bytes) storage sellPath, address uniV3Factory
50,233
10
// Stake worlds for a first time. You may optionally stake to a different wallet. Ownership will be transferred to the stakeTo address. Initial weights passed as input parameters, which are secured by a dev signature. weight = 40003 - 3rank When you stake you can set rental conditions for all of them. Initialized and uninitialized stake can be mixed into one tx using this method. If you set rentalPerDay to 0 and rentableUntil to some time in the future, then anyone can rent for free until the rentableUntil timestamp with no way of backing out
function initialStake(uint[] calldata tokenIds, uint[] calldata weights, address stakeTo, uint16 _deposit, uint16 _rentalPerDay, uint16 _minRentDays, uint32 _rentableUntil, uint32 _maxTimestamp, bytes calldata _signature) external virtual override nonReentrant
function initialStake(uint[] calldata tokenIds, uint[] calldata weights, address stakeTo, uint16 _deposit, uint16 _rentalPerDay, uint16 _minRentDays, uint32 _rentableUntil, uint32 _maxTimestamp, bytes calldata _signature) external virtual override nonReentrant
42,997
209
// Mint the Tokens that Founders of the companions ownedRequires any minted tokens to be blockedMints to another user or the owner
function mintFoundersBlockedNfts( uint256[] calldata tokenIds_, uint _mintoption, address _to
function mintFoundersBlockedNfts( uint256[] calldata tokenIds_, uint _mintoption, address _to
2,495
41
// main staking contract
abstract contract TMEAccessControl is MyOwnable{ bool public pausedHatch; modifier whenNotPausedHatch() { require(!pausedHatch, "Hatching is paused!"); _; } modifier whenPausedHatch { require(pausedHatch, "Hatching is not paused!"); _; } function pauseHatch() public onlyOwner whenNotPausedHatch { pausedHatch = true; } function unpauseHatch() public onlyOwner whenPausedHatch { pausedHatch = false; } bool public pausedIncubate; modifier whenNotPausedIncubate() { require(!pausedIncubate, "Incubate is paused!"); _; } modifier whenPausedIncubate { require(pausedIncubate, "Incubate is not paused!"); _; } function pauseIncubate() public onlyOwner whenNotPausedIncubate { pausedIncubate = true; } function unpauseIncubate() public onlyOwner whenPausedIncubate { pausedIncubate = false; } }
abstract contract TMEAccessControl is MyOwnable{ bool public pausedHatch; modifier whenNotPausedHatch() { require(!pausedHatch, "Hatching is paused!"); _; } modifier whenPausedHatch { require(pausedHatch, "Hatching is not paused!"); _; } function pauseHatch() public onlyOwner whenNotPausedHatch { pausedHatch = true; } function unpauseHatch() public onlyOwner whenPausedHatch { pausedHatch = false; } bool public pausedIncubate; modifier whenNotPausedIncubate() { require(!pausedIncubate, "Incubate is paused!"); _; } modifier whenPausedIncubate { require(pausedIncubate, "Incubate is not paused!"); _; } function pauseIncubate() public onlyOwner whenNotPausedIncubate { pausedIncubate = true; } function unpauseIncubate() public onlyOwner whenPausedIncubate { pausedIncubate = false; } }
12,183
11
// mapping of whitelisted addresses
mapping(address => bool) public canApeMapping;
mapping(address => bool) public canApeMapping;
9,197
37
// 只有 creator (即创建当前合约的合约)能够更改名称 —— 因为合约是隐式转换为地址的, 所以这里的比较是可行的。
if (msg.sender == address(creator)) name = newName;
if (msg.sender == address(creator)) name = newName;
31,895
15
// Cost of arbitration. Accessor to arbitrationPrice._extraData Not used by this contract. return fee Amount to be paid. /
function arbitrationCost(bytes _extraData) public view returns(uint fee) { return arbitrationPrice; }
function arbitrationCost(bytes _extraData) public view returns(uint fee) { return arbitrationPrice; }
23,643
8
// Calculate the rewards they are owed, and pay them out.
uint256 reward = calculateRewards(msg.sender); rewardsToken.transfer(msg.sender, reward);
uint256 reward = calculateRewards(msg.sender); rewardsToken.transfer(msg.sender, reward);
2,423
135
// Allow the clippermom to access the feed
addReaderToWhitelist(co.pip, clipperMom_);
addReaderToWhitelist(co.pip, clipperMom_);
24,834
63
// Moves `amount` tokens from `sender` to `recipient` using theallowance mechanism. `amount` is then deducted from the caller'sallowance. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. /
function transferFrom(
function transferFrom(
184
83
// When uninitialized we mint exactly the underlying input in LP tokens
_mintPoolTokens(recipient, inputUnderlying);
_mintPoolTokens(recipient, inputUnderlying);
23,546
4
// Array Storage operators
function addGameRequest(uint256 inID) public { gameRequestsList.push(inID); gameRequestsListByAddress[gameList[inID].player1] = inID; gameRequestsCount++; }
function addGameRequest(uint256 inID) public { gameRequestsList.push(inID); gameRequestsListByAddress[gameList[inID].player1] = inID; gameRequestsCount++; }
45,420
0
// Pool factory interfacethis defines the Pool factory interface, primarily intended forthe Pool contract to interact with /
interface IPoolFactory { /** * @return GYSR treasury address */ function treasury() external view returns (address); /** * @return GYSR spending fee */ function fee() external view returns (uint256); }
interface IPoolFactory { /** * @return GYSR treasury address */ function treasury() external view returns (address); /** * @return GYSR spending fee */ function fee() external view returns (uint256); }
40,985
21
// number of total tokens sold
uint256 public totalNumberTokenSold=0; bool public tradable = false; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
uint256 public totalNumberTokenSold=0; bool public tradable = false; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
22,604
30
// Can be used by the contract owner to return a user's stake back to them,without need for going through the withdrawal period. This should only really be usedat the end of the campaign, if a user does not manually withdraw their stake. This function only works on single addresses, in order to avoid potentialdeadlocks caused by high gas requirements. /
function returnStake(address _staker) external onlyOwner { Staker storage staker = stakersMap[_staker]; require(staker.amount > 0, "This person is not staking"); // If this user has a pending reward, add it to the accumulated reward before // paying him out. staker.accumulatedReward = staker.accumulatedReward.add(staker.pendingReward); removeUser(staker, _staker); }
function returnStake(address _staker) external onlyOwner { Staker storage staker = stakersMap[_staker]; require(staker.amount > 0, "This person is not staking"); // If this user has a pending reward, add it to the accumulated reward before // paying him out. staker.accumulatedReward = staker.accumulatedReward.add(staker.pendingReward); removeUser(staker, _staker); }
13,202
57
// ProductProxy This contract implements a proxy that it is deploied by ProxyFactory, and it's implementation is stored in factory. /
contract ProductProxy is Proxy { /** * @dev Storage slot with the address of the ProxyFactory. * This is the keccak-256 hash of "eip1967.proxy.factory" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant FACTORY_SLOT = 0x7a45a402e4cb6e08ebc196f20f66d5d30e67285a2a8aa80503fa409e727a4af1; function productName() virtual public pure returns (bytes32) { return 0x0; } /** * @dev Sets the factory address of the ProductProxy. * @param newFactory Address of the new factory. */ function _setFactory(address newFactory) internal { require(OpenZeppelinUpgradesAddress.isContract(newFactory), "Cannot set a factory to a non-contract address"); bytes32 slot = FACTORY_SLOT; assembly { sstore(slot, newFactory) } } /** * @dev Returns the factory. * @return factory Address of the factory. */ function _factory() internal view returns (address factory) { bytes32 slot = FACTORY_SLOT; assembly { factory := sload(slot) } } /** * @dev Returns the current implementation. * @return Address of the current implementation */ function _implementation() virtual override internal view returns (address) { address factory = _factory(); if(OpenZeppelinUpgradesAddress.isContract(factory)) return IProxyFactory(factory).productImplementations(productName()); else return address(0); } }
contract ProductProxy is Proxy { /** * @dev Storage slot with the address of the ProxyFactory. * This is the keccak-256 hash of "eip1967.proxy.factory" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant FACTORY_SLOT = 0x7a45a402e4cb6e08ebc196f20f66d5d30e67285a2a8aa80503fa409e727a4af1; function productName() virtual public pure returns (bytes32) { return 0x0; } /** * @dev Sets the factory address of the ProductProxy. * @param newFactory Address of the new factory. */ function _setFactory(address newFactory) internal { require(OpenZeppelinUpgradesAddress.isContract(newFactory), "Cannot set a factory to a non-contract address"); bytes32 slot = FACTORY_SLOT; assembly { sstore(slot, newFactory) } } /** * @dev Returns the factory. * @return factory Address of the factory. */ function _factory() internal view returns (address factory) { bytes32 slot = FACTORY_SLOT; assembly { factory := sload(slot) } } /** * @dev Returns the current implementation. * @return Address of the current implementation */ function _implementation() virtual override internal view returns (address) { address factory = _factory(); if(OpenZeppelinUpgradesAddress.isContract(factory)) return IProxyFactory(factory).productImplementations(productName()); else return address(0); } }
8,783
143
// withdraws multiple funds held by the contract and sends them to an accountcan only be called by the ownertokens ERC20 token contract addresses (with a special handling of NATIVE_TOKEN_ADDRESS) to account to receive the new amount amounts amounts to withdraw /
function withdrawTokensMultiple( IERC20[] calldata tokens, address payable to, uint256[] calldata amounts
function withdrawTokensMultiple( IERC20[] calldata tokens, address payable to, uint256[] calldata amounts
46,316
30
// First we multiply the interest rate (expressed in rate/sec) by the time since the last update. This result represents the proportional amount of interest to apply to the system at a whole
uint256 interestAccumulated = interestRate.mul(currentTimestamp().sub(indexLastUpdate));
uint256 interestAccumulated = interestRate.mul(currentTimestamp().sub(indexLastUpdate));
49,866
13
// Performs a Solidity function call using a low level `call`. Aplain `call` is an unsafe replacement for a function call: use thisfunction instead. If `target` reverts with a revert reason, it is bubbled up by thisfunction (like regular Solidity function calls). Returns the raw returned data. To convert to the expected return value, Requirements: - `target` must be a contract.- calling `target` with `data` must not revert. _Available since v3.1._ /
function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); }
function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); }
21,660
236
// pause a specific mint request_opIndex the index of the mint request the caller wants to pause/
function pauseMint(uint _opIndex) external onlyMintPauserOrOwner { mintOperations[_opIndex].paused = true; emit MintPaused(_opIndex, true); }
function pauseMint(uint _opIndex) external onlyMintPauserOrOwner { mintOperations[_opIndex].paused = true; emit MintPaused(_opIndex, true); }
1,114
6
// Set update to return a boolean
oracle.givenQueryReturnResponse( abi.encodePacked(IOracle.update.selector),
oracle.givenQueryReturnResponse( abi.encodePacked(IOracle.update.selector),
41,276
73
// View function to see pending ICE on frontend.
function pendingIce(uint256 _pid, address _user) external view returns (uint256)
function pendingIce(uint256 _pid, address _user) external view returns (uint256)
12,810
48
// ERC-173 Contract Ownership Standard/Note: the ERC-165 identifier for this interface is 0x7f5828d0/ is ERC165 /
interface IERC173 { /// @dev This emits when ownership of a contract changes. event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice Get the address of the owner /// @return owner_ The address of the owner. function owner() external view returns (address owner_); /// @notice Set the address of the new owner of the contract /// @dev Set _newOwner to address(0) to renounce any ownership. /// @param _newOwner The address of the new owner of the contract function transferOwnership(address _newOwner) external; }
interface IERC173 { /// @dev This emits when ownership of a contract changes. event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice Get the address of the owner /// @return owner_ The address of the owner. function owner() external view returns (address owner_); /// @notice Set the address of the new owner of the contract /// @dev Set _newOwner to address(0) to renounce any ownership. /// @param _newOwner The address of the new owner of the contract function transferOwnership(address _newOwner) external; }
35,096
38
// Check that signature data pointer (s) is in bounds (points to the length of data -> 32 bytes)
require(uint256(s).add(32) <= signatures.length, "GS022");
require(uint256(s).add(32) <= signatures.length, "GS022");
58,071
55
// Struct to define the gps coordinates of a station. Since latitudes and longitudes are floats (with 13 numbers after the dot), we basically store the information about latitude and longitude by multiplying the respective values by the variable SCALE = 1013
uint256 private constant SCALE = 10 ** 13;
uint256 private constant SCALE = 10 ** 13;
43,668
22
// DON'T Change This - unlock 100% Tokens over lockDuration
uint public constant unlockRate = 100e2; uint public lastClaimedTime; uint public deployTime;
uint public constant unlockRate = 100e2; uint public lastClaimedTime; uint public deployTime;
18,948
12
// Emitted when staker cancelled withdrawal/staker staker's address/compoundAmount amount that was moved from withdrawal to unstaking period/unstakingPeriod specified unstaking period to find withdrawal
event WithdrawalCanceled( address indexed staker, uint256 compoundAmount, uint256 unstakingPeriod );
event WithdrawalCanceled( address indexed staker, uint256 compoundAmount, uint256 unstakingPeriod );
5,882
60
// The timestamp from the block when this player token was minted.
uint64 mintedTime;
uint64 mintedTime;
23,639
203
// 借款年利率
function APR() public view returns (uint256) { uint256 cash = tokenCash(underlying, address(controller)); return interestRateModel.APR(cash, totalBorrows, totalReserves); }
function APR() public view returns (uint256) { uint256 cash = tokenCash(underlying, address(controller)); return interestRateModel.APR(cash, totalBorrows, totalReserves); }
40,139