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
22
// Internal function that burns an amount of the token of a givenaccount. account The account whose tokens will be burnt. value The amount that will be burnt. /
function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); }
function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); }
1,032
99
// Make a fee contribution. It cannot be inlined in fundAppeal because of the stack limit. _itemID The item receiving the contribution. _requestID The request to contribute. _roundID The round to contribute. _side The side for which to contribute. _contributor The contributor. _amount The amount contributed. _totalRequired The total amount required for this side.return The amount of appeal fees contributed. /
function contribute( bytes32 _itemID, uint256 _requestID, uint256 _roundID, uint256 _side, address payable _contributor, uint256 _amount, uint256 _totalRequired
function contribute( bytes32 _itemID, uint256 _requestID, uint256 _roundID, uint256 _side, address payable _contributor, uint256 _amount, uint256 _totalRequired
81,127
88
// mortgagePool address
address public _mortgagePool;
address public _mortgagePool;
44,541
5
// onlyOwner Functions
function setSaleState(bool newState) public onlyOwner { isSalesActive = newState; }
function setSaleState(bool newState) public onlyOwner { isSalesActive = newState; }
2,770
18
// src/interfaces/TaxCollectorLike.sol/ pragma solidity 0.6.7; /
abstract contract TaxCollectorLike { function taxSingle(bytes32) public virtual returns (uint256); }
abstract contract TaxCollectorLike { function taxSingle(bytes32) public virtual returns (uint256); }
2,368
39
// Calculates the balance of the user: principal balance + interest generated by the principal user The user whose balance is calculatedreturn The balance of the user /
{ // stored balance is ray (27) uint256 balanceInMapping = _balanceOf(user); // ray -> ray uint256 balanceRay = balanceInMapping.rayMul(liquidityIndex); // ray -> wad return balanceRay.rayToWad(); }
{ // stored balance is ray (27) uint256 balanceInMapping = _balanceOf(user); // ray -> ray uint256 balanceRay = balanceInMapping.rayMul(liquidityIndex); // ray -> wad return balanceRay.rayToWad(); }
41,643
37
// ======= MISCELLANEOUS FUNCTIONS ======= // Overrides the supportsInterface function to include ERC721Enumerable. interfaceId The interface ID to check.return A boolean indicating support for the interface. /
function supportsInterface(bytes4 interfaceId) public view override(ERC721Enumerable) returns (bool)
function supportsInterface(bytes4 interfaceId) public view override(ERC721Enumerable) returns (bool)
28,383
32
// trigger an update of the position fees owed and fee growth snapshots if it has any liquidity
if (position.liquidity > 0) { pool.burn(position.tickLower, position.tickUpper, 0); (, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, , ) = pool.positions(PositionKey.compute(address(this), position.tickLower, position.tickUpper)); tokensOwed0 += uint128( FullMath.mulDiv( feeGrowthInside0LastX128 - position.feeGrowthInside0LastX128, position.liquidity, FixedPoint128.Q128
if (position.liquidity > 0) { pool.burn(position.tickLower, position.tickUpper, 0); (, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, , ) = pool.positions(PositionKey.compute(address(this), position.tickLower, position.tickUpper)); tokensOwed0 += uint128( FullMath.mulDiv( feeGrowthInside0LastX128 - position.feeGrowthInside0LastX128, position.liquidity, FixedPoint128.Q128
17,319
21
// Calculate sqrt (x) rounding down.Revert if x < 0.x signed 64.64-bit fixed point numberreturn signed 64.64-bit fixed point number /
function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64, 0x10000000000000000)); }
function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64, 0x10000000000000000)); }
6,495
43
// Validates that the given information is a claim in the tree and thenissues the mint./
function claim(uint256 index, address account, uint256 tokenId, uint256 price, bytes32[] calldata merkleProof) external override { // Check that this index is unclaimed require(!isClaimed(index), 'MerkleMinter: Token already claimed.'); // Check that the merkle proof is valid require(MerkleProof.verify( merkleProof, merkleRoot, keccak256(abi.encodePacked(index, account, tokenId, price))), 'MerkleMinter: Invalid proof.'); // Perform the mint _mintClaim(index, account, tokenId, price); }
function claim(uint256 index, address account, uint256 tokenId, uint256 price, bytes32[] calldata merkleProof) external override { // Check that this index is unclaimed require(!isClaimed(index), 'MerkleMinter: Token already claimed.'); // Check that the merkle proof is valid require(MerkleProof.verify( merkleProof, merkleRoot, keccak256(abi.encodePacked(index, account, tokenId, price))), 'MerkleMinter: Invalid proof.'); // Perform the mint _mintClaim(index, account, tokenId, price); }
10,355
52
// Update reward variables to be up-to-date.
function _updateVLiquidity(uint256 vLiquidity, bool isAdd) internal { if (isAdd) { totalVLiquidity = totalVLiquidity + vLiquidity; } else { totalVLiquidity = totalVLiquidity - vLiquidity; } // max lockBoostMultiplier is 3 require(totalVLiquidity <= FixedPoints.Q128 * 3, "TOO MUCH LIQUIDITY STAKED"); }
function _updateVLiquidity(uint256 vLiquidity, bool isAdd) internal { if (isAdd) { totalVLiquidity = totalVLiquidity + vLiquidity; } else { totalVLiquidity = totalVLiquidity - vLiquidity; } // max lockBoostMultiplier is 3 require(totalVLiquidity <= FixedPoints.Q128 * 3, "TOO MUCH LIQUIDITY STAKED"); }
28,415
11
// -------------------------------------------------------------------/ Validation/ -------------------------------------------------------------------
uint256 _startTimestamp = startTimestamp(); uint256 _endTimestamp = endTimestamp(); if (block.timestamp >= _endTimestamp) { revert Error_Wrap_VestOver(); }
uint256 _startTimestamp = startTimestamp(); uint256 _endTimestamp = endTimestamp(); if (block.timestamp >= _endTimestamp) { revert Error_Wrap_VestOver(); }
23,095
28
// allow a relayer to execute the transaction for a user and convert his DAI parcel into ETH
function convertParcel(address payable _user) external{ Stream storage s = streams[_user]; uint256 gasPrice = tx.gasprice; uint256 eth_bought = IUniswapExchange(0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667).getTokenToEthInputPrice(s.parcel); // the contract execution requires several conditions: // a) that a stream was created for the user in the past (s.created == 1) // b) that the stream is active (s.isactive == 1) // c) that enough time has passed since the last swap (ready_since>=0) // d) that the estimated gas cost is below 3% of the returned amount from Uniswap; otherwise don't let transaction take place // e) that the current time window is open for this relayer // // starting from the top relayer in the list, each relayer will have a "time windows" of 240 seconds assigned to make the transaction // if that relayer does not respond, the time window will open for the second in the list, and so on // the first relayer that sends the transaction will move up in the list by one position. // this will allow anyone to be a relayer, while discouraging bidding with a high gas price which would ultimately damage the end user address relayer_allowed = 0x0000000000000000000000000000000000000000; uint relayer_allowed_index = 0; uint multiple = 0; if (s.lastSwap == 0){ multiple = (now - s.startTime) / (240 * relayersCount); relayer_allowed_index = ((now - s.startTime) - multiple * (240 * relayersCount)) / 240; relayer_allowed = relayers[relayer_allowed_index]; } else { multiple = (now - s.lastSwap - s.interval) / (240 * relayersCount); relayer_allowed_index = ((now - s.lastSwap - s.interval) - multiple * (240 * relayersCount)) / 240; relayer_allowed = relayers[relayer_allowed_index]; } require(s.created == 1 && s.isactive == 1 && now > s.lastSwap + s.interval && gasPrice * gas_consumption < eth_bought * 3 / 100 && relayer_allowed == msg.sender); // if all the conditions are satisfied, proceed with the swap // first move the parcel of DAI from the owner wallet to this contract, then return the ETH obtained to the contract dai.transferFrom(_user, address(this), s.parcel); uint256 ether_returned = IUniswapExchange(0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667).tokenToEthSwapInput(s.parcel, 1, now+120); // now distribute the ether_returned between the owner, the relayer and the creator // in particular: // a) the owner gets the ETH received from uniswap, net of the gas cost and the fee // b) the relayer gets 50% of the fee, plus a reimbursement for the gas cost // c) the creator gets 50% of the fee _user.transfer(ether_returned * (fee_denominator - fee_numerator)/fee_denominator - gas_consumption * gasPrice); // to the user msg.sender.transfer(gas_consumption * gasPrice + (ether_returned * fee_numerator / 2) / fee_denominator); // to the relayer creator.transfer((ether_returned * fee_numerator / 2) / fee_denominator); // to the creator // record in the contract the amount of DAI swapped and ETH received // also, update the timestamp of the last swap s.dai_swapped = s.dai_swapped + s.parcel; s.eth_received = s.eth_received + ether_returned - gas_consumption * gasPrice - (ether_returned * fee_numerator) / fee_denominator; s.lastSwap = block.timestamp; // finally, readjust the FIFO list of relayers and reward the relayer that made the transaction by moving up one notch if (relayer_allowed_index != 0){ address relayer_before = relayers[relayer_allowed_index - 1]; relayers[relayer_allowed_index - 1] = msg.sender; relayers[relayer_allowed_index] = relayer_before; } }
function convertParcel(address payable _user) external{ Stream storage s = streams[_user]; uint256 gasPrice = tx.gasprice; uint256 eth_bought = IUniswapExchange(0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667).getTokenToEthInputPrice(s.parcel); // the contract execution requires several conditions: // a) that a stream was created for the user in the past (s.created == 1) // b) that the stream is active (s.isactive == 1) // c) that enough time has passed since the last swap (ready_since>=0) // d) that the estimated gas cost is below 3% of the returned amount from Uniswap; otherwise don't let transaction take place // e) that the current time window is open for this relayer // // starting from the top relayer in the list, each relayer will have a "time windows" of 240 seconds assigned to make the transaction // if that relayer does not respond, the time window will open for the second in the list, and so on // the first relayer that sends the transaction will move up in the list by one position. // this will allow anyone to be a relayer, while discouraging bidding with a high gas price which would ultimately damage the end user address relayer_allowed = 0x0000000000000000000000000000000000000000; uint relayer_allowed_index = 0; uint multiple = 0; if (s.lastSwap == 0){ multiple = (now - s.startTime) / (240 * relayersCount); relayer_allowed_index = ((now - s.startTime) - multiple * (240 * relayersCount)) / 240; relayer_allowed = relayers[relayer_allowed_index]; } else { multiple = (now - s.lastSwap - s.interval) / (240 * relayersCount); relayer_allowed_index = ((now - s.lastSwap - s.interval) - multiple * (240 * relayersCount)) / 240; relayer_allowed = relayers[relayer_allowed_index]; } require(s.created == 1 && s.isactive == 1 && now > s.lastSwap + s.interval && gasPrice * gas_consumption < eth_bought * 3 / 100 && relayer_allowed == msg.sender); // if all the conditions are satisfied, proceed with the swap // first move the parcel of DAI from the owner wallet to this contract, then return the ETH obtained to the contract dai.transferFrom(_user, address(this), s.parcel); uint256 ether_returned = IUniswapExchange(0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667).tokenToEthSwapInput(s.parcel, 1, now+120); // now distribute the ether_returned between the owner, the relayer and the creator // in particular: // a) the owner gets the ETH received from uniswap, net of the gas cost and the fee // b) the relayer gets 50% of the fee, plus a reimbursement for the gas cost // c) the creator gets 50% of the fee _user.transfer(ether_returned * (fee_denominator - fee_numerator)/fee_denominator - gas_consumption * gasPrice); // to the user msg.sender.transfer(gas_consumption * gasPrice + (ether_returned * fee_numerator / 2) / fee_denominator); // to the relayer creator.transfer((ether_returned * fee_numerator / 2) / fee_denominator); // to the creator // record in the contract the amount of DAI swapped and ETH received // also, update the timestamp of the last swap s.dai_swapped = s.dai_swapped + s.parcel; s.eth_received = s.eth_received + ether_returned - gas_consumption * gasPrice - (ether_returned * fee_numerator) / fee_denominator; s.lastSwap = block.timestamp; // finally, readjust the FIFO list of relayers and reward the relayer that made the transaction by moving up one notch if (relayer_allowed_index != 0){ address relayer_before = relayers[relayer_allowed_index - 1]; relayers[relayer_allowed_index - 1] = msg.sender; relayers[relayer_allowed_index] = relayer_before; } }
33,153
1
// The id of the token to be redeemed. Must be unique - if another token with this ID already exists, the redeem function will revert.
uint256 tokenId;
uint256 tokenId;
19,862
275
// What is the value of their DET balance in dUSD?
uint256 collateralValue = exchangeRates().effectiveValue( "DET", collateralForAccount, dUSD );
uint256 collateralValue = exchangeRates().effectiveValue( "DET", collateralForAccount, dUSD );
9,694
24
// Calculates black scholes for the ITM option at mint given strikeprice and underlying given the parameters (if underling >= strike price this ispremium of call, and put otherwise) t is the days until expiry v is the annualized volatility sp is the underlying price st is the strike pricereturn premium is the premium of option /
function blackScholes( uint256 t, uint256 v, uint256 sp, uint256 st
function blackScholes( uint256 t, uint256 v, uint256 sp, uint256 st
33,643
472
// Internal function to determine if an address is a contract/_addr The address being queried/ return True if `_addr` is a contract
function isContract(address _addr) view internal returns(bool) { uint size; if (_addr == address(0)) return false; assembly { size := extcodesize(_addr) } return size>0; }
function isContract(address _addr) view internal returns(bool) { uint size; if (_addr == address(0)) return false; assembly { size := extcodesize(_addr) } return size>0; }
40,910
55
// Check for authorization of msg.sender here
_;
_;
39,830
8
// Special value representing a question that was answered too soon. bytes32(-2). By convention we use bytes32(-1) for "invalid", although the contract does not handle this.
bytes32 constant UNRESOLVED_ANSWER = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe; event LogSetQuestionFee( address arbitrator, uint256 amount ); event LogNewTemplate( uint256 indexed template_id, address indexed user,
bytes32 constant UNRESOLVED_ANSWER = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe; event LogSetQuestionFee( address arbitrator, uint256 amount ); event LogNewTemplate( uint256 indexed template_id, address indexed user,
26,565
1
// TODO
function verify( bytes memory pubkey, bytes memory sig, bytes memory signBytes
function verify( bytes memory pubkey, bytes memory sig, bytes memory signBytes
16,556
272
// Gets current Lady price based on current supply./
function getNFTPrice(uint256 amount) public view returns (uint256) { require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started yet so you can't get a price yet."); require(totalSupply() < MAX_SUPPLY, "Sale has already ended, no more Txts left to sell."); return amount.mul(BASE_RATE); }
function getNFTPrice(uint256 amount) public view returns (uint256) { require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started yet so you can't get a price yet."); require(totalSupply() < MAX_SUPPLY, "Sale has already ended, no more Txts left to sell."); return amount.mul(BASE_RATE); }
35,092
180
// Constant value used as max loop limit
uint256 private constant MAX_LOOP_LIMIT = 256;
uint256 private constant MAX_LOOP_LIMIT = 256;
17,347
201
// Replacement for msg.sender. Returns the actual sender of a transaction: msg.sender for regular transactions,and the end-user for GSN relayed calls (where msg.sender is actually `RelayHub`).
* IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.sender`, and use {_msgSender} instead. */ function _msgSender() internal view returns (address payable) { if (msg.sender != _relayHub) { return msg.sender; } else { return _getRelayedCallSender(); } }
* IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.sender`, and use {_msgSender} instead. */ function _msgSender() internal view returns (address payable) { if (msg.sender != _relayHub) { return msg.sender; } else { return _getRelayedCallSender(); } }
43,379
637
// Send remaining to designer in ETH, the discount does not effect this
(bool designerTransferSuccess,) = garmentNft.garmentDesigners(garmentTokenId).call{value : offer.primarySalePrice.sub(feeInETH)}("");
(bool designerTransferSuccess,) = garmentNft.garmentDesigners(garmentTokenId).call{value : offer.primarySalePrice.sub(feeInETH)}("");
41,945
3
// سازنده
constructor () payable public
constructor () payable public
2,382
20
// Add a signer whose signature can pass the validation in `executeWithSignerFee` by owner/signer The signer address to be added
function addSigner(address signer) external onlyOwner { signers[signer] = true; emit SignerAdded(signer); }
function addSigner(address signer) external onlyOwner { signers[signer] = true; emit SignerAdded(signer); }
9,187
8
// timestamp + 2 years can never realistically overflow 256 bits.
unchecked { if (time > block.timestamp + MAX_SCHEDULED_TIME_IN_THE_FUTURE) {
unchecked { if (time > block.timestamp + MAX_SCHEDULED_TIME_IN_THE_FUTURE) {
27,424
16
// Additional methods available for WETH
interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint wad) external; }
interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint wad) external; }
11,254
177
// lib/uma/packages/core/contracts/common/implementation/Timer.sol/ pragma solidity ^0.8.0; // Universal store of current contract time for testing environments. /
contract Timer { uint256 private currentTime; constructor() { currentTime = block.timestamp; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { currentTime = time; } /** * @notice Gets the currentTime variable set in the Timer. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } }
contract Timer { uint256 private currentTime; constructor() { currentTime = block.timestamp; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { currentTime = time; } /** * @notice Gets the currentTime variable set in the Timer. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } }
7,740
9
// Set the contract interaction delay.newInteractionDelay The new interaction delay. /
function setInteractionDelay(uint newInteractionDelay) external override onlyOwner { interactionDelay = newInteractionDelay; emit InteractionDelaySet(interactionDelay); }
function setInteractionDelay(uint newInteractionDelay) external override onlyOwner { interactionDelay = newInteractionDelay; emit InteractionDelaySet(interactionDelay); }
17,212
93
// This should never happen, as we have an overflow check in setTotalDeposit
assert(total_deposit >= participant_state.deposit); assert(total_deposit >= partner_state.deposit);
assert(total_deposit >= participant_state.deposit); assert(total_deposit >= partner_state.deposit);
58,223
266
// get enable stat
bool fromEnabled = trueRewardEnabled(_from); bool toEnabled = trueRewardEnabled(_to);
bool fromEnabled = trueRewardEnabled(_from); bool toEnabled = trueRewardEnabled(_to);
32,646
48
// See {IERC20-approve}. Requirements: - `spender` cannot be the zero address. /
function approve(address spender, uint256 amount) public virtual override returns (bool) {
function approve(address spender, uint256 amount) public virtual override returns (bool) {
13,850
609
// How much Reward tokens to keep
uint256 public keepRewardToken = 500; uint256 public keepRewardTokenMax = 10000; constructor( address _token0, address _token1, uint256 _poolId, address _lp, address _governance, address _strategist,
uint256 public keepRewardToken = 500; uint256 public keepRewardTokenMax = 10000; constructor( address _token0, address _token1, uint256 _poolId, address _lp, address _governance, address _strategist,
51,036
64
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the benefit is lost if 'b' is also tested. See: https:github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c);
if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c);
9,488
145
// Fallback function accepts Ether transactions.
receive() external payable { emit SafeReceived(msg.sender, msg.value); }
receive() external payable { emit SafeReceived(msg.sender, msg.value); }
58,137
39
// uint _guaranteedBuyAmount = convertDiv(_buyAddr.decimals(), _sellAddr.decimals(), buyAmt, sellAmt); _guaranteedBuyAmount = convert18ToDec(_buyAddr.decimals(), wmul(_guaranteedBuyAmount, _sellAmt18));
uint _guaranteedBuyAmount = uint96(-1); uint _slippageAmt = convert18ToDec(_buyDec, wmul(unitAmt, _sellAmt18)); _callData = encodeData(data, _sellAmt, _guaranteedBuyAmount, _slippageAmt);
uint _guaranteedBuyAmount = uint96(-1); uint _slippageAmt = convert18ToDec(_buyDec, wmul(unitAmt, _sellAmt18)); _callData = encodeData(data, _sellAmt, _guaranteedBuyAmount, _slippageAmt);
37,216
170
// Collects up to a maximum amount of fees owed to a specific position to the recipient/params tokenId The ID of the NFT for which tokens are being collected,/ recipient The account that should receive the tokens,/ amount0Max The maximum amount of token0 to collect,/ amount1Max The maximum amount of token1 to collect/ return amount0 The amount of fees collected in token0/ return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
11,444
6
// The address interpreted as native token of the chain.
address public constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
3,337
177
// for update param
function getFinancialCRFIRate(FinancialPackage storage package) internal view
function getFinancialCRFIRate(FinancialPackage storage package) internal view
23,017
0
// Must match definition in ForwardProxy keccak256("com.eco.ForwardProxy.target")
uint256 private constant IMPLEMENTATION_SLOT = 0xf86c915dad5894faca0dfa067c58fdf4307406d255ed0a65db394f82b77f53d4;
uint256 private constant IMPLEMENTATION_SLOT = 0xf86c915dad5894faca0dfa067c58fdf4307406d255ed0a65db394f82b77f53d4;
9,644
416
// grad rewards and set IDLE action
_freeWarriors(packedContenders);
_freeWarriors(packedContenders);
24,168
10
// packed uint: max of 95, max uint8 = 255
uint8 secondaryMarketRoyaltyPercentage; address payable additionalPayeeSecondarySales;
uint8 secondaryMarketRoyaltyPercentage; address payable additionalPayeeSecondarySales;
12,984
69
// Default payable function which can be used to purchase tokens.
function () payable public { buyTokens(msg.sender); }
function () payable public { buyTokens(msg.sender); }
37,294
61
// 1 - sqrt(ratio)2 / (1 + ratio)
return (1e18).sub(ratio.mul(1e18).sqrt().mul(2e18).div(ratio.add(1e18)));
return (1e18).sub(ratio.mul(1e18).sqrt().mul(2e18).div(ratio.add(1e18)));
14,001
197
// Turn on pre-reveal mod. All NFT Metadata are the same. /
function revealMod(bool value) public { require(owner() == _msgSender() || admin == _msgSender()); reveal = value; }
function revealMod(bool value) public { require(owner() == _msgSender() || admin == _msgSender()); reveal = value; }
21,347
55
// Fail if mint not allowed //Return if mintAmount is zero.Put behind `mintAllowed` for accuring potential JOE rewards. /
if (mintAmount == 0) { return (uint256(Error.NO_ERROR), 0); }
if (mintAmount == 0) { return (uint256(Error.NO_ERROR), 0); }
3,669
245
// REQUIRED OVERRIDES /Due to multiple inheritance, we require to overwrite the totalSupply method.
function totalSupply(uint256 id) public view override(ERC1155Supply, IVaultChefCore) returns (uint256)
function totalSupply(uint256 id) public view override(ERC1155Supply, IVaultChefCore) returns (uint256)
35,093
6
// 투자 가능한 금액과 환불금을 산출함_userValue 유저의 기존 투자금액_fromValue 투자를 원하는 금액 return possibleValue_ 투자 가능한 금액 return refundValue_ maxcap 도달로 환불해야하는 금액/
function getRefundAmount(uint256 _userValue, uint256 _fromValue) private view returns (uint256 possibleValue_, uint256 refundValue_) { uint256 d1 = maxcap.sub(fundRise); uint256 d2 = maximum.sub(_userValue); possibleValue_ = (d1.min(d2)).min(_fromValue); refundValue_ = _fromValue.sub(possibleValue_); }
function getRefundAmount(uint256 _userValue, uint256 _fromValue) private view returns (uint256 possibleValue_, uint256 refundValue_) { uint256 d1 = maxcap.sub(fundRise); uint256 d2 = maximum.sub(_userValue); possibleValue_ = (d1.min(d2)).min(_fromValue); refundValue_ = _fromValue.sub(possibleValue_); }
52,763
448
// A temporary method for migrating LINA tokens from LnSimpleStaking to LnCollateralSystemwithout user intervention. /
function migrateCollateral( bytes32 _currency, address[] calldata _users, uint256[] calldata _amounts
function migrateCollateral( bytes32 _currency, address[] calldata _users, uint256[] calldata _amounts
42,884
259
// 5. Subtract the collateral.
loan.collateral = loan.collateral.sub(amount);
loan.collateral = loan.collateral.sub(amount);
30,003
419
// Gets the current mStable Savings Contract address./ return address of mStable Savings Contract.
function _fetchMStableSavings() internal view returns (address) { address manager = IMStable(nexusGovernance).getModule(keccak256('SavingsManager')); return IMStable(manager).savingsContracts(musd); }
function _fetchMStableSavings() internal view returns (address) { address manager = IMStable(nexusGovernance).getModule(keccak256('SavingsManager')); return IMStable(manager).savingsContracts(musd); }
19,325
123
// return _tokenOwners.contains(tokenId);
return tokenExists[tokenId];
return tokenExists[tokenId];
27,709
151
// Use the genesis tokens to claim free mints.
function genesisClaim(uint[] memory _genesisIds) public nonReentrant { require(saleState == 3, "Not open."); uint n = _genesisIds.length; require(n > 0 && n % 3 == 0, "Please submit a positive multiple of 3."); address sender = msg.sender; uint qPrevInitial = 1 << 255; uint qPrev = qPrevInitial; uint m; for (uint i = 0; i < n; i += 3) { for (uint j = 0; j < 3; ++j) { uint t = _genesisIds[i + j]; uint q = t >> 8; uint r = t & 255; if (q != qPrev) { if (qPrev != qPrevInitial) { genesisClaimedMap[qPrev] = m; } m = genesisClaimedMap[q]; } qPrev = q; uint b = 1 << r; // Token must be unused and owned. require(m & b == 0 && genesisContract.ownerOf(t) == sender, "Invalid submission."); // Modifying the map and checking will ensure that there // are no duplicates in _genesisIds. m = m | b; } mintOne(sender); } genesisClaimedMap[qPrev] = m; }
function genesisClaim(uint[] memory _genesisIds) public nonReentrant { require(saleState == 3, "Not open."); uint n = _genesisIds.length; require(n > 0 && n % 3 == 0, "Please submit a positive multiple of 3."); address sender = msg.sender; uint qPrevInitial = 1 << 255; uint qPrev = qPrevInitial; uint m; for (uint i = 0; i < n; i += 3) { for (uint j = 0; j < 3; ++j) { uint t = _genesisIds[i + j]; uint q = t >> 8; uint r = t & 255; if (q != qPrev) { if (qPrev != qPrevInitial) { genesisClaimedMap[qPrev] = m; } m = genesisClaimedMap[q]; } qPrev = q; uint b = 1 << r; // Token must be unused and owned. require(m & b == 0 && genesisContract.ownerOf(t) == sender, "Invalid submission."); // Modifying the map and checking will ensure that there // are no duplicates in _genesisIds. m = m | b; } mintOne(sender); } genesisClaimedMap[qPrev] = m; }
21,972
159
// If we shouldn't invest, don't do it :D
if (!investWant) { return; }
if (!investWant) { return; }
66,979
6
// Emitted when `value` tokens are moved from one account (`from`) to another (`to`). Note that `value` may be zero./
event Transfer(address indexed from, address indexed to, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
29,452
54
// Perfomance fee 30% to buyback
uint256 public performanceFee = 30000; uint256 public constant performanceMax = 100000;
uint256 public performanceFee = 30000; uint256 public constant performanceMax = 100000;
61,870
45
// essentially the same as buy, but instead of you sending etherfrom your wallet, it uses your unwithdrawn earnings.-functionhash- 0x349cdcac (using ID for affiliate)-functionhash- 0x82bfc739 (using address for affiliate)-functionhash- 0x079ce327 (using name for affiliate) _affCode the ID/address/name of the player who gets the affiliate fee _team what team is the player playing for? _eth amount of earnings to use (remainder returned to gen vault) /
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public
34,782
26
// See {ERC20-_burn} and {ERC20-allowance}. Requirements: - the caller must have allowance for ``accounts``'s tokens of at least`amount`.- the caller must have the `BURNER_ROLE`. /
function burnFrom(address account, uint256 amount) public { require(hasRole(BURNER_ROLE, _msgSender()), "Standard: must have burner role to burn"); uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); }
function burnFrom(address account, uint256 amount) public { require(hasRole(BURNER_ROLE, _msgSender()), "Standard: must have burner role to burn"); uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); }
55,531
200
// Applies accrued interest to total borrows and reserves This calculates interest accrued from the last checkpointed blockup to the current block and writes new checkpoint to storage. /
function accrueInterest() public returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calculate block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr)); } (mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint(Error.NO_ERROR); }
function accrueInterest() public returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calculate block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr)); } (mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint(Error.NO_ERROR); }
579
6
// Fallback function is called when msg.data is not empty
fallback() external payable { }
fallback() external payable { }
26,949
12
// Function to set mint and burn locks_set boolean flag (true | false)/
function setSupplyLock(bool _set) onlyAdmin public { //Only the admin can set a lock on supply lockSupply = _set; emit SetSupplyLock(_set); }
function setSupplyLock(bool _set) onlyAdmin public { //Only the admin can set a lock on supply lockSupply = _set; emit SetSupplyLock(_set); }
68,315
134
// adds protected liquidity to a poolalso mints new governance tokens for the caller if the caller adds network tokens_poolAnchoranchor of the pool _reserveTokenreserve token to add to the pool _amountamount of tokens to add to the poolreturn new protected liquidity id /
function addLiquidity( IConverterAnchor _poolAnchor, IERC20Token _reserveToken, uint256 _amount ) external payable protected poolSupported(_poolAnchor) poolWhitelisted(_poolAnchor)
function addLiquidity( IConverterAnchor _poolAnchor, IERC20Token _reserveToken, uint256 _amount ) external payable protected poolSupported(_poolAnchor) poolWhitelisted(_poolAnchor)
14,042
109
// These next few lines are used when the totalSupply of the token is requested before a check point was ever created for this token, it requires that the `parentToken.totalSupplyAt` be queried at the genesis block for this token as that contains totalSupply of this token at this block number.
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else {
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else {
54,602
73
// Initialize last accrual timestamp to time that cellar was created, otherwise the first `accrue` will take platform fees from 1970 to the time it is called.
feeData.lastAccrual = uint64(block.timestamp); (, , , , , address _strategistPayout, uint128 _assetRiskTolerance, uint128 _protocolRiskTolerance) = abi.decode( params, (uint32[], uint32[], bytes[], bytes[], uint8, address, uint128, uint128) ); feeData.strategistPayoutAddress = _strategistPayout; assetRiskTolerance = _assetRiskTolerance;
feeData.lastAccrual = uint64(block.timestamp); (, , , , , address _strategistPayout, uint128 _assetRiskTolerance, uint128 _protocolRiskTolerance) = abi.decode( params, (uint32[], uint32[], bytes[], bytes[], uint8, address, uint128, uint128) ); feeData.strategistPayoutAddress = _strategistPayout; assetRiskTolerance = _assetRiskTolerance;
3,829
0
// Queue struct Internally keeps track of the `first` and `last` elements throughindices and a mapping of indices to enqueued elements. /
struct Queue { uint128 first; uint128 last; mapping(uint256 => bytes32) queue; }
struct Queue { uint128 first; uint128 last; mapping(uint256 => bytes32) queue; }
20,574
54
// Update the value of `maxNumTxInChunk`./_maxNumTxInChunk The new value of `maxNumTxInChunk`.
function updateMaxNumTxInChunk(uint256 _maxNumTxInChunk) external onlyOwner { uint256 _oldMaxNumTxInChunk = maxNumTxInChunk; maxNumTxInChunk = _maxNumTxInChunk; emit UpdateMaxNumTxInChunk(_oldMaxNumTxInChunk, _maxNumTxInChunk); }
function updateMaxNumTxInChunk(uint256 _maxNumTxInChunk) external onlyOwner { uint256 _oldMaxNumTxInChunk = maxNumTxInChunk; maxNumTxInChunk = _maxNumTxInChunk; emit UpdateMaxNumTxInChunk(_oldMaxNumTxInChunk, _maxNumTxInChunk); }
34,176
84
// make decimals consistent with oToken strike price decimals (108)
return ( finalStrike.mul(10**8).div(assetOracleMultiplier), finalDelta );
return ( finalStrike.mul(10**8).div(assetOracleMultiplier), finalDelta );
21,512
421
// Rescue tokens
function rescueTokens( address token, address to, uint256 amount
function rescueTokens( address token, address to, uint256 amount
18,201
36
// Work out the max token ID for an edition ID
function maxTokenIdOfEdition(uint256 _editionId) external view returns (uint256 _tokenId);
function maxTokenIdOfEdition(uint256 _editionId) external view returns (uint256 _tokenId);
18,063
10
// Enables anyone with a masternode to earn referral fees on P3D reinvestments. /
function reinvest() external { // reinvest must be enabled require(disabled == false); // setup p3c P3C p3c = P3C(0xDF9AaC76b722B08511A4C561607A9bf3AfA62E49); // withdraw dividends p3c.withdraw(); // reinvest with a referral fee for sender p3c.buy.value(address(this).balance)(msg.sender); }
function reinvest() external { // reinvest must be enabled require(disabled == false); // setup p3c P3C p3c = P3C(0xDF9AaC76b722B08511A4C561607A9bf3AfA62E49); // withdraw dividends p3c.withdraw(); // reinvest with a referral fee for sender p3c.buy.value(address(this).balance)(msg.sender); }
5,291
12
// Moves `amount` tokens from the caller's account to `recipient`. Returns a boolean value indicating whether the operation succeeded.
* Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
* Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
953
51
// Determine loser role
bytes32 _loser = _winner == BetHelperLib.BETTOR_ROLE ? BetHelperLib.COUNTER_BETTOR_ROLE : BetHelperLib.BETTOR_ROLE; betStorage.winner = betStorage.roleParticipants[_winner]; betStorage.loser = betStorage.roleParticipants[_loser]; if (address(exchange) != address(0)) { _swapTokensToMatic(_txExpirationTime); } else {
bytes32 _loser = _winner == BetHelperLib.BETTOR_ROLE ? BetHelperLib.COUNTER_BETTOR_ROLE : BetHelperLib.BETTOR_ROLE; betStorage.winner = betStorage.roleParticipants[_winner]; betStorage.loser = betStorage.roleParticipants[_loser]; if (address(exchange) != address(0)) { _swapTokensToMatic(_txExpirationTime); } else {
16,185
4
// lockTimestamp: block.timestamp,
lockTimestamp: _lockTimestamp, lockHours: _lockHours, lastUpdated: block.timestamp, claimedAmount: 0
lockTimestamp: _lockTimestamp, lockHours: _lockHours, lastUpdated: block.timestamp, claimedAmount: 0
82,751
13
// Set an upgrade agent that handles the upgrade process /
function setUpgradeAgent(address agent) onlyMaster external { // Check whether the token is in a state that we could think of upgrading require(canUpgrade()); require(agent != 0x0); // Upgrade has already begun for an agent require(getUpgradeState() != UpgradeState.Upgrading); upgradeAgent = UpgradeAgent(agent); // Bad interface require(upgradeAgent.isUpgradeAgent()); // Make sure that token supplies match in source and target require(upgradeAgent.originalSupply() == totalSupply()); UpgradeAgentSet(upgradeAgent); }
function setUpgradeAgent(address agent) onlyMaster external { // Check whether the token is in a state that we could think of upgrading require(canUpgrade()); require(agent != 0x0); // Upgrade has already begun for an agent require(getUpgradeState() != UpgradeState.Upgrading); upgradeAgent = UpgradeAgent(agent); // Bad interface require(upgradeAgent.isUpgradeAgent()); // Make sure that token supplies match in source and target require(upgradeAgent.originalSupply() == totalSupply()); UpgradeAgentSet(upgradeAgent); }
17,812
22
// Get _appContract address return A address of _appContract/
function getAppContract() public view returns(address)
function getAppContract() public view returns(address)
5,622
24
// change request obj
requestList[reqAddr].status = '2'; //validating requestList[reqAddr].resultID = resultID;
requestList[reqAddr].status = '2'; //validating requestList[reqAddr].resultID = resultID;
13,393
2
// Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `518`. a uint to convert into a FixedPoint.return the converted FixedPoint. /
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); }
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); }
1,104
135
// convert to signed int in order-preserving manner
return int(begin - 0x8000000000000000000000000000000000000000000000000000000000000000);
return int(begin - 0x8000000000000000000000000000000000000000000000000000000000000000);
54,167
167
// SL2 = min(RmaxP1, L2) S1 = RmaxP1 - SL2 Both operations are done by failsafe_subtract We take out participant2's pending transfers locked amount, bounding it by the maximum receivable amount of participant1
(participant1_amount, participant2_locked_amount) = failsafe_subtract( participant1_amount, participant2_locked_amount );
(participant1_amount, participant2_locked_amount) = failsafe_subtract( participant1_amount, participant2_locked_amount );
14,904
5
// Create an `address public` variable called `kaseiTokenAddress`.
address public kaseiTokenAddress;
address public kaseiTokenAddress;
30,553
14
// View function to see pending Reward on frontend.
function pendingReward(address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[_user]; uint256 accRewardPerShare = pool.accRewardPerShare; uint256 stokenSupply = pool.stakeToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && stokenSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 tokenReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accRewardPerShare = accRewardPerShare.add(tokenReward.mul(1e12).div(stokenSupply)); } return user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt); }
function pendingReward(address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[_user]; uint256 accRewardPerShare = pool.accRewardPerShare; uint256 stokenSupply = pool.stakeToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && stokenSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 tokenReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accRewardPerShare = accRewardPerShare.add(tokenReward.mul(1e12).div(stokenSupply)); } return user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt); }
19,116
2
// Validates a withdraw action reserveAddress The address of the reserve amount The amount to be withdrawn userBalance The balance of the user reservesData The reserves state userConfig The user configuration reserves The addresses of the reserves reservesCount The number of reserves oracle The price oracle /
function validateWithdraw( address reserveAddress, uint256 amount, uint256 userBalance, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle
function validateWithdraw( address reserveAddress, uint256 amount, uint256 userBalance, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle
21,474
320
// ========== EVENTS ========== // Event for when alpaca's energy changed from `fromEnergy` /
event EnergyChanged( uint256 indexed id, uint256 oldEnergy, uint256 newEnergy );
event EnergyChanged( uint256 indexed id, uint256 oldEnergy, uint256 newEnergy );
39,448
79
// //Handler method called by Chainlink for the first house open price/
function firstHouseOpen(uint256 _price, uint256 warIndex) external onlyDoTxLib { wars[warIndex].firstHouse.openPrice = _price; openPriceEvent(warIndex); }
function firstHouseOpen(uint256 _price, uint256 warIndex) external onlyDoTxLib { wars[warIndex].firstHouse.openPrice = _price; openPriceEvent(warIndex); }
22,389
43
// Solutionner un projet
function solutionnerProjet(uint _id,address _solutionneur,uint256 montant_) public { require(projetCounter > 0); require(_id > 0 && _id <= projetCounter); Projet storage projet = projets[_id]; require(montant_<=projet.price); balances[msg.sender]-=montant_; balances[_solutionneur]+=montant_; projet.priceSolution+=montant_; /*operationCounter++; Operation memory op; op.id=operationCounter; op.montant = montant_; op.operateur = msg.sender; op.typeOperation = TypeOperation.SOLUTIONNER_PROJET; operations[operationCounter] = op;*/ LogSolutionnerProjet(operationCounter,_solutionneur,_id,projet.name,montant_,projet.createur); }
function solutionnerProjet(uint _id,address _solutionneur,uint256 montant_) public { require(projetCounter > 0); require(_id > 0 && _id <= projetCounter); Projet storage projet = projets[_id]; require(montant_<=projet.price); balances[msg.sender]-=montant_; balances[_solutionneur]+=montant_; projet.priceSolution+=montant_; /*operationCounter++; Operation memory op; op.id=operationCounter; op.montant = montant_; op.operateur = msg.sender; op.typeOperation = TypeOperation.SOLUTIONNER_PROJET; operations[operationCounter] = op;*/ LogSolutionnerProjet(operationCounter,_solutionneur,_id,projet.name,montant_,projet.createur); }
17,652
21
// Function for changing the price to correlate with the USD
function setPrice (uint256 _newPrice) external onlyOwner virtual returns (bool){ require(price != _newPrice, "Please change the price to a new value!"); price = _newPrice * 1 ether; emit NewPriceChange(msg.sender, price); return true; }
function setPrice (uint256 _newPrice) external onlyOwner virtual returns (bool){ require(price != _newPrice, "Please change the price to a new value!"); price = _newPrice * 1 ether; emit NewPriceChange(msg.sender, price); return true; }
47,458
7
// WhitelisterRole Whitelisters are responsible for assigning and removing Whitelisted accounts. /
contract WhitelisterRole { using Roles for Roles.Role; event WhitelisterAdded(address indexed account); event WhitelisterRemoved(address indexed account); Roles.Role private _whitelisters; constructor () internal { _addWhitelister(msg.sender); } modifier onlyWhitelister() { require(isWhitelister(msg.sender)); _; } function isWhitelister(address account) public view returns (bool) { return _whitelisters.has(account); } function addWhitelister(address account) public onlyWhitelister { _addWhitelister(account); } function renounceWhitelister() public { _removeWhitelister(msg.sender); } function _addWhitelister(address account) internal { _whitelisters.add(account); emit WhitelisterAdded(account); } function _removeWhitelister(address account) internal { _whitelisters.remove(account); emit WhitelisterRemoved(account); } }
contract WhitelisterRole { using Roles for Roles.Role; event WhitelisterAdded(address indexed account); event WhitelisterRemoved(address indexed account); Roles.Role private _whitelisters; constructor () internal { _addWhitelister(msg.sender); } modifier onlyWhitelister() { require(isWhitelister(msg.sender)); _; } function isWhitelister(address account) public view returns (bool) { return _whitelisters.has(account); } function addWhitelister(address account) public onlyWhitelister { _addWhitelister(account); } function renounceWhitelister() public { _removeWhitelister(msg.sender); } function _addWhitelister(address account) internal { _whitelisters.add(account); emit WhitelisterAdded(account); } function _removeWhitelister(address account) internal { _whitelisters.remove(account); emit WhitelisterRemoved(account); } }
36,756
6
// update the messageFee to take out mintAmount
messageFee = msg.value - mintAmount;
messageFee = msg.value - mintAmount;
28,937
3
// Retain existings NFT into custody bridge smart contract.NFT holder will call this function to transfer their NFT to this bridgeNFT will be hold into bridge address until release (`releaseNFT`),
* Emits a {NFTCustody} event. */ function retainNFT( address nftAddress, uint256 tokenId, string memory to ) public payable nonReentrant { require( msg.value == costNative, "Not enough balance to complete transaction." ); require( supportedCollections[nftAddress] > 0, "Collection is not supported" ); if (supportedCollections[nftAddress] == STANDARD) {} else if ( supportedCollections[nftAddress] == MINTABLE ) { PioneerNFT nft = PioneerNFT(nftAddress); require(nft.ownerOf(tokenId) == msg.sender, "NFT not yours"); require( holdCustody[nftAddress][tokenId] == address(0), "NFT already stored" ); holdCustody[nftAddress][tokenId] = msg.sender; nft.transferFrom(msg.sender, address(this), tokenId); emit NFTCustody(tokenId, msg.sender, to); } }
* Emits a {NFTCustody} event. */ function retainNFT( address nftAddress, uint256 tokenId, string memory to ) public payable nonReentrant { require( msg.value == costNative, "Not enough balance to complete transaction." ); require( supportedCollections[nftAddress] > 0, "Collection is not supported" ); if (supportedCollections[nftAddress] == STANDARD) {} else if ( supportedCollections[nftAddress] == MINTABLE ) { PioneerNFT nft = PioneerNFT(nftAddress); require(nft.ownerOf(tokenId) == msg.sender, "NFT not yours"); require( holdCustody[nftAddress][tokenId] == address(0), "NFT already stored" ); holdCustody[nftAddress][tokenId] = msg.sender; nft.transferFrom(msg.sender, address(this), tokenId); emit NFTCustody(tokenId, msg.sender, to); } }
6,126
4
// xref:ROOT:erc1155.adocbatch-operations[Batched] variant of {mint}. /
function mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint"); _mintBatch(to, ids, amounts, data); }
function mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint"); _mintBatch(to, ids, amounts, data); }
582
6
// 2. setup()
address[] memory owners = new address[](1);
address[] memory owners = new address[](1);
34,148
55
// ERC20 balanceOf _owner Owner addressreturn True if success /
function balanceOf(address _owner) public override view returns (uint256) { return balances[_owner]; }
function balanceOf(address _owner) public override view returns (uint256) { return balances[_owner]; }
27,036
27
// FOURTH tower. (ID = 3) Robin Hood has to cross a sea to an island! 1 day time range! 75% payout of the amount20% price increaseTimer halfs at 2 ETH. Minimum price is 10 finney.Price reduces 75% (100% - 25%) after someone has won the tower! 0% creator fee.
AddTower(86400, 7500, 2000, (2000000000000000000), 10000000000000000, 2500, 0);
AddTower(86400, 7500, 2000, (2000000000000000000), 10000000000000000, 2500, 0);
21,201
145
// An user can own one or more Vaults, with each vault being able to borrow from a single series.
function vaults(bytes12 vault) external view returns (DataTypes.Vault memory);
function vaults(bytes12 vault) external view returns (DataTypes.Vault memory);
72,559
15
// enms
enum userType {buyer, seller} //mapping mapping(address => uint) public balances; // Special varables: // token: ether, szabo, finney, //time: weeks, hours, minutes, seconds // bool isTime = (1 hours = 60 minutes); // block uint n = block.number; uint d = block.difficulty; // block.coinbase(); // message, what sent to you.. address who = msg.sender; uint value = msg.value; // msg.data; // transaction // tx.origin }
enum userType {buyer, seller} //mapping mapping(address => uint) public balances; // Special varables: // token: ether, szabo, finney, //time: weeks, hours, minutes, seconds // bool isTime = (1 hours = 60 minutes); // block uint n = block.number; uint d = block.difficulty; // block.coinbase(); // message, what sent to you.. address who = msg.sender; uint value = msg.value; // msg.data; // transaction // tx.origin }
17,148
76
// return the current dividend accrual rate, in USD per second the returned value in 1e18 may not be precise enoughreturn dividend in USD per second /
function getCurrentValue() external view virtual override returns (uint256) { return getHistoricalValue(_dividendPhases.length.sub(1)); }
function getCurrentValue() external view virtual override returns (uint256) { return getHistoricalValue(_dividendPhases.length.sub(1)); }
75,129
450
// Store last byte.
result = b[b.length - 1]; assembly {
result = b[b.length - 1]; assembly {
8,049
7
// web3.utils.soliditySha3('count')
bytes32 public constant COUNT_LABEL = 0xc82306b6ab1b4c67429442feb1e6d238135a6cfcaa471a01b0e336f01b048e38;
bytes32 public constant COUNT_LABEL = 0xc82306b6ab1b4c67429442feb1e6d238135a6cfcaa471a01b0e336f01b048e38;
17,095
24
// _memPtr Item memory pointer.return Number of bytes until the data. /
function _payloadOffset(uint256 _memPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, mload(_memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; }
function _payloadOffset(uint256 _memPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, mload(_memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; }
15,646