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
56
// requestNewRound logic /
AccessControllerInterface internal s_requesterAccessController;
AccessControllerInterface internal s_requesterAccessController;
14,157
166
// Transfer the received tokens to the recipient.
_transferToken(tokenReceived, recipient, quotedTokenReceivedAmount); receivedAmountAfterTransferFee = tokenReceived.balanceOf(recipient).sub( priorRecipientBalanceOfReceivedToken );
_transferToken(tokenReceived, recipient, quotedTokenReceivedAmount); receivedAmountAfterTransferFee = tokenReceived.balanceOf(recipient).sub( priorRecipientBalanceOfReceivedToken );
29,440
25
// Gets the memory address for the contents of a byte array./input Byte array to lookup./ return memoryAddress Memory address of the contents of the byte array.
function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress)
function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress)
51,316
58
// Queries the approval status of an operator for a given owner./owner The owner of the Tokens/operatorAddress of authorized operator/ return True if the operator is approved, false if not
function isApprovedForAll(address owner, address operator) public override view returns (bool) { bool approved = operatorApproval[owner][operator]; if (!approved && exchangesRegistry != address(0)) { return WhitelistExchangesProxy(exchangesRegistry).isAddressWhitelisted(operator) == true; } return approved; }
function isApprovedForAll(address owner, address operator) public override view returns (bool) { bool approved = operatorApproval[owner][operator]; if (!approved && exchangesRegistry != address(0)) { return WhitelistExchangesProxy(exchangesRegistry).isAddressWhitelisted(operator) == true; } return approved; }
31,272
270
// Deposit into the strategy and assume it will revert on error.
ETHStrategy(address(strategy)).mint{value: underlyingAmount}();
ETHStrategy(address(strategy)).mint{value: underlyingAmount}();
25,924
32
// Add the signer to the bitmask of approvers.
request.approvers |= signerMask; if (signerInfo.status == SignerStatus.FirstCommittee) { ++request.approvalsFirstCommittee; } else {
request.approvers |= signerMask; if (signerInfo.status == SignerStatus.FirstCommittee) { ++request.approvalsFirstCommittee; } else {
14,552
365
// Get the approved address for a single NFT/Throws if `_tokenId` is not a valid NFT./_tokenId The NFT to find the approved address for/ return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address);
function getApproved(uint256 _tokenId) external view returns (address);
32,179
49
// Getter for the variables saved under the TellorStorageStruct uintVars variable _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name isthe variables/strings used to save the data in the mapping. The variables names arecommented out under the uintVars under the TellorStorageStruct structThis is an example of how data is saved into the mapping within other functions:self.uintVars[keccak256("stakerCount")]return uint of specified variable /
function getUintVar(bytes32 _data) external view returns (uint256);
function getUintVar(bytes32 _data) external view returns (uint256);
6,318
139
// Helper function to represent an `amount` of `token` in shares./token The ERC-20 token./amount The `token` amount./roundUp If the result `share` should be rounded up./ return share The token amount represented in shares.
function toShare( IERC20 token, uint256 amount, bool roundUp
function toShare( IERC20 token, uint256 amount, bool roundUp
6,616
98
// wear hat
event WearHat(address indexed hatter, address indexed hats);
event WearHat(address indexed hatter, address indexed hats);
37,084
1
// Used to ensure a proper game start
address public gameOwner;
address public gameOwner;
76,741
223
// Withdraw bnb from this contract (Callable by owner)/
function withdrawOwner() onlyOwner public { require(tradingEnabled == false); uint balance = address(this).balance; msg.sender.transfer(balance); if(totalSupply() == MAX_NFT_SUPPLY){ tradingEnabled = true; } }
function withdrawOwner() onlyOwner public { require(tradingEnabled == false); uint balance = address(this).balance; msg.sender.transfer(balance); if(totalSupply() == MAX_NFT_SUPPLY){ tradingEnabled = true; } }
11,477
118
// If the earnings pool has a separate transcoder reward pool, calculate the portion of incoming rewards to put into the delegator reward pool and the portion to put into the transcoder reward pool
uint256 transcoderRewards = MathUtils.percOf(_rewards, earningsPool.transcoderRewardCut); earningsPool.rewardPool = earningsPool.rewardPool.add(_rewards.sub(transcoderRewards)); earningsPool.transcoderRewardPool = earningsPool.transcoderRewardPool.add(transcoderRewards);
uint256 transcoderRewards = MathUtils.percOf(_rewards, earningsPool.transcoderRewardCut); earningsPool.rewardPool = earningsPool.rewardPool.add(_rewards.sub(transcoderRewards)); earningsPool.transcoderRewardPool = earningsPool.transcoderRewardPool.add(transcoderRewards);
2,012
218
// Max unsigned integer value
uint256 constant internal MAX_UINT_256 = type(uint256).max;
uint256 constant internal MAX_UINT_256 = type(uint256).max;
46,469
3
// max size of notice metadata memory range 32(2^16) bytes
uint256 constant NOTICE_METADATA_LOG2_SIZE = 21;
uint256 constant NOTICE_METADATA_LOG2_SIZE = 21;
49,738
79
// swap out the flywheel rewards contract
function setFlywheelRewards(IFlywheelRewards newFlywheelRewards) external requiresAuth { address oldFlywheelRewards = address(flywheelRewards); flywheelRewards = newFlywheelRewards; emit FlywheelRewardsUpdate(oldFlywheelRewards, address(newFlywheelRewards)); }
function setFlywheelRewards(IFlywheelRewards newFlywheelRewards) external requiresAuth { address oldFlywheelRewards = address(flywheelRewards); flywheelRewards = newFlywheelRewards; emit FlywheelRewardsUpdate(oldFlywheelRewards, address(newFlywheelRewards)); }
6,360
2
// IRatesProvider IRatesProvider interfaceCyril Lapinte - <cyril.lapinte@mtpelerin.com>Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved Please refer to the top of this file for the license. /
contract IRatesProvider { function rateWEIPerCHFCent() public view returns (uint256); function convertWEIToCHFCent(uint256 _amountWEI) public view returns (uint256); function convertCHFCentToWEI(uint256 _amountCHFCent) public view returns (uint256); }
contract IRatesProvider { function rateWEIPerCHFCent() public view returns (uint256); function convertWEIToCHFCent(uint256 _amountWEI) public view returns (uint256); function convertCHFCentToWEI(uint256 _amountCHFCent) public view returns (uint256); }
42,491
17
// Deposit function
function () external payable { require(now >= startDate && now <= endDate); // Get number of frames, will revert if sold out uint256 ethToTransfer; uint256 frames; (frames, ethToTransfer) = calculateRoyaltyFrames( msg.value); // Update crowdsale contract state royaltiesSold = royaltiesSold.add(frames); contributedEth = contributedEth.add(ethToTransfer); royaltyEthAmount[msg.sender] = royaltyEthAmount[msg.sender].add(ethToTransfer); // Accept Payments uint256 ethToRefund = msg.value.sub(ethToTransfer); if (ethToTransfer > 0) { wallet.transfer(ethToTransfer); } if (ethToRefund > 0) { msg.sender.transfer(ethToRefund); } // Issue royalty tokens crowdsaleContract.claimRoyaltyFrames(msg.sender, frames, ethToTransfer); emit Purchased(msg.sender, frames, ethToTransfer, royaltiesSold, contributedEth); }
function () external payable { require(now >= startDate && now <= endDate); // Get number of frames, will revert if sold out uint256 ethToTransfer; uint256 frames; (frames, ethToTransfer) = calculateRoyaltyFrames( msg.value); // Update crowdsale contract state royaltiesSold = royaltiesSold.add(frames); contributedEth = contributedEth.add(ethToTransfer); royaltyEthAmount[msg.sender] = royaltyEthAmount[msg.sender].add(ethToTransfer); // Accept Payments uint256 ethToRefund = msg.value.sub(ethToTransfer); if (ethToTransfer > 0) { wallet.transfer(ethToTransfer); } if (ethToRefund > 0) { msg.sender.transfer(ethToRefund); } // Issue royalty tokens crowdsaleContract.claimRoyaltyFrames(msg.sender, frames, ethToTransfer); emit Purchased(msg.sender, frames, ethToTransfer, royaltiesSold, contributedEth); }
14,646
122
// Send ETH
function sendEther() public payable { }
function sendEther() public payable { }
12,961
5
// contract address => execute proposal function signature
mapping (address => bytes4) public _contractAddressToExecuteFunctionSignature;
mapping (address => bytes4) public _contractAddressToExecuteFunctionSignature;
58,497
105
// save in _balances the amount of curveLpTokens received to use off-chain
_balances[_convexRewards.length + 1] = _gainedLpTokens; if (_curveLpBalanceAfter > 0) {
_balances[_convexRewards.length + 1] = _gainedLpTokens; if (_curveLpBalanceAfter > 0) {
71,858
15
// Creates a request to the specified Oracle contract address This function ignores the stored Oracle contract address andwill instead send the request to the address specified _oracle The Oracle contract address to send the request to _jobId The bytes32 JobID to be executed _url The URL to fetch data from _path The dot-delimited path to parse of the response _times The number to multiply the result by /
function createRequestTo( address _oracle, bytes32 _jobId, uint256 _payment, string memory _url, string memory _path, int256 _times ) public returns (bytes32 requestId)
function createRequestTo( address _oracle, bytes32 _jobId, uint256 _payment, string memory _url, string memory _path, int256 _times ) public returns (bytes32 requestId)
33,317
2
// Modifiers Start
modifier existingItem(uint256 _id){ require(_id >= 0 && _id < items.length, "Item does not exists."); _; }
modifier existingItem(uint256 _id){ require(_id >= 0 && _id < items.length, "Item does not exists."); _; }
48,961
105
// lets msg.sender accept governance /
function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); }
function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); }
13,940
19
// 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"); }
509
37
// Emits an {Approval} event. /
function approve(address spender, uint256 value) public override onlyNotPaused returns (bool) { _approve(msg.sender, spender, value); return true; }
function approve(address spender, uint256 value) public override onlyNotPaused returns (bool) { _approve(msg.sender, spender, value); return true; }
1,465
25
// digest - internal double hash function/_seed secret to hash/_algorithm hash algorithm type
function digest( string _seed, Algorithm _algorithm
function digest( string _seed, Algorithm _algorithm
23,707
93
// divides bytes signature into `uint8 v, bytes32 r, bytes32 s`./Make sure to peform a bounds check forpos, to avoid out of bounds access onsignatures/pos which signature to read. A prior bounds check of this parameter should be performed, to avoid out of bounds access/signatures concatenated rsv signatures
function signatureSplit(bytes memory signatures, uint256 pos) internal pure returns ( uint8 v, bytes32 r, bytes32 s )
function signatureSplit(bytes memory signatures, uint256 pos) internal pure returns ( uint8 v, bytes32 r, bytes32 s )
6,343
40
// See {IERC20-transferFrom}. Note that operator and allowance concepts are orthogonal: operators cannotcall `transferFrom` (unless they have allowance), and accounts withallowance cannot call `operatorSend` (unless they are operators). Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. /
function transferFrom( address holder, address recipient, uint256 amount ) public virtual override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender();
function transferFrom( address holder, address recipient, uint256 amount ) public virtual override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender();
45,492
196
// check pool exist or not - audit
require(!poolExist[_lpToken], "Pool already exists"); if (_withUpdate) { massUpdatePools(); }
require(!poolExist[_lpToken], "Pool already exists"); if (_withUpdate) { massUpdatePools(); }
12,944
79
// Divides two unsigned 60.18-decimal fixed-point numbers, returning a new unsigned 60.18-decimal fixed-point number.//Uses mulDiv to enable overflow-safe multiplication and division.// Requirements:/ - The denominator cannot be zero.//x The numerator as an unsigned 60.18-decimal fixed-point number./y The denominator as an unsigned 60.18-decimal fixed-point number./result The quotient as an unsigned 60.18-decimal fixed-point number.
function div(uint256 x, uint256 y) internal pure returns (uint256 result) { result = PRBMath.mulDiv(x, SCALE, y); }
function div(uint256 x, uint256 y) internal pure returns (uint256 result) { result = PRBMath.mulDiv(x, SCALE, y); }
36,330
183
// The debt cache (SIP-91) caches the global debt and the debt of each synth in the system. Debt is denominated by the synth supply multiplied by its current exchange rate. The cache can be invalidated when an exchange rate changes, and thereafter must be updated by performing a debt snapshot, which recomputes the global debt sum using current synth supplies and exchange rates. This is performed usually by a snapshot keeper. Some synths are backed by non-SNX collateral, such as sETH being backed by ETH held in the EtherWrapper (SIP-112). This debt is called "excluded debt" and is excluded from
contract BaseDebtCache is Owned, MixinSystemSettings, IDebtCache { using SafeMath for uint; using SafeDecimalMath for uint; uint internal _cachedDebt; mapping(bytes32 => uint) internal _cachedSynthDebt; uint internal _cacheTimestamp; bool internal _cacheInvalid = true; /* ========== ENCODED NAMES ========== */ bytes32 internal constant sUSD = "sUSD"; bytes32 internal constant sETH = "sETH"; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; bytes32 private constant CONTRACT_EXRATES = "ExchangeRates"; bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 private constant CONTRACT_COLLATERALMANAGER = "CollateralManager"; bytes32 private constant CONTRACT_ETHER_WRAPPER = "EtherWrapper"; constructor(address _owner, address _resolver) public Owned(_owner) MixinSystemSettings(_resolver) {} /* ========== VIEWS ========== */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](6); newAddresses[0] = CONTRACT_ISSUER; newAddresses[1] = CONTRACT_EXCHANGER; newAddresses[2] = CONTRACT_EXRATES; newAddresses[3] = CONTRACT_SYSTEMSTATUS; newAddresses[4] = CONTRACT_COLLATERALMANAGER; newAddresses[5] = CONTRACT_ETHER_WRAPPER; addresses = combineArrays(existingAddresses, newAddresses); } function issuer() internal view returns (IIssuer) { return IIssuer(requireAndGetAddress(CONTRACT_ISSUER)); } function exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } function exchangeRates() internal view returns (IExchangeRates) { return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES)); } function systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } function collateralManager() internal view returns (ICollateralManager) { return ICollateralManager(requireAndGetAddress(CONTRACT_COLLATERALMANAGER)); } function etherWrapper() internal view returns (IEtherWrapper) { return IEtherWrapper(requireAndGetAddress(CONTRACT_ETHER_WRAPPER)); } function debtSnapshotStaleTime() external view returns (uint) { return getDebtSnapshotStaleTime(); } function cachedDebt() external view returns (uint) { return _cachedDebt; } function cachedSynthDebt(bytes32 currencyKey) external view returns (uint) { return _cachedSynthDebt[currencyKey]; } function cacheTimestamp() external view returns (uint) { return _cacheTimestamp; } function cacheInvalid() external view returns (bool) { return _cacheInvalid; } function _cacheStale(uint timestamp) internal view returns (bool) { // Note a 0 timestamp means that the cache is uninitialised. // We'll keep the check explicitly in case the stale time is // ever set to something higher than the current unix time (e.g. to turn off staleness). return getDebtSnapshotStaleTime() < block.timestamp - timestamp || timestamp == 0; } function cacheStale() external view returns (bool) { return _cacheStale(_cacheTimestamp); } // Returns the USD-denominated supply of each synth in `currencyKeys`, according to `rates`. function _issuedSynthValues(bytes32[] memory currencyKeys, uint[] memory rates) internal view returns (uint[] memory values) { uint numValues = currencyKeys.length; values = new uint[](numValues); ISynth[] memory synths = issuer().getSynths(currencyKeys); for (uint i = 0; i < numValues; i++) { address synthAddress = address(synths[i]); require(synthAddress != address(0), "Synth does not exist"); uint supply = IERC20(synthAddress).totalSupply(); values[i] = supply.multiplyDecimalRound(rates[i]); } return (values); } function _currentSynthDebts(bytes32[] memory currencyKeys) internal view returns ( uint[] memory snxIssuedDebts, uint _excludedDebt, bool anyRateIsInvalid ) { (uint[] memory rates, bool isInvalid) = exchangeRates().ratesAndInvalidForCurrencies(currencyKeys); uint[] memory values = _issuedSynthValues(currencyKeys, rates); (uint excludedDebt, bool isAnyNonSnxDebtRateInvalid) = _totalNonSnxBackedDebt(); return (values, excludedDebt, isInvalid || isAnyNonSnxDebtRateInvalid); } // Returns the USD-denominated supply of each synth in `currencyKeys`, using current exchange rates. function currentSynthDebts(bytes32[] calldata currencyKeys) external view returns ( uint[] memory debtValues, uint excludedDebt, bool anyRateIsInvalid ) { return _currentSynthDebts(currencyKeys); } function _cachedSynthDebts(bytes32[] memory currencyKeys) internal view returns (uint[] memory) { uint numKeys = currencyKeys.length; uint[] memory debts = new uint[](numKeys); for (uint i = 0; i < numKeys; i++) { debts[i] = _cachedSynthDebt[currencyKeys[i]]; } return debts; } function cachedSynthDebts(bytes32[] calldata currencyKeys) external view returns (uint[] memory snxIssuedDebts) { return _cachedSynthDebts(currencyKeys); } function _totalNonSnxBackedDebt() internal view returns (uint excludedDebt, bool isInvalid) { // Calculate excluded debt. // 1. MultiCollateral long debt + short debt. (uint longValue, bool anyTotalLongRateIsInvalid) = collateralManager().totalLong(); (uint shortValue, bool anyTotalShortRateIsInvalid) = collateralManager().totalShort(); isInvalid = anyTotalLongRateIsInvalid || anyTotalShortRateIsInvalid; excludedDebt = longValue.add(shortValue); // 2. EtherWrapper. // Subtract sETH and sUSD issued by EtherWrapper. excludedDebt = excludedDebt.add(etherWrapper().totalIssuedSynths()); return (excludedDebt, isInvalid); } // Returns the total sUSD debt backed by non-SNX collateral. function totalNonSnxBackedDebt() external view returns (uint excludedDebt, bool isInvalid) { return _totalNonSnxBackedDebt(); } function _currentDebt() internal view returns (uint debt, bool anyRateIsInvalid) { bytes32[] memory currencyKeys = issuer().availableCurrencyKeys(); (uint[] memory rates, bool isInvalid) = exchangeRates().ratesAndInvalidForCurrencies(currencyKeys); // Sum all issued synth values based on their supply. uint[] memory values = _issuedSynthValues(currencyKeys, rates); (uint excludedDebt, bool isAnyNonSnxDebtRateInvalid) = _totalNonSnxBackedDebt(); uint numValues = values.length; uint total; for (uint i; i < numValues; i++) { total = total.add(values[i]); } total = total < excludedDebt ? 0 : total.sub(excludedDebt); return (total, isInvalid || isAnyNonSnxDebtRateInvalid); } // Returns the current debt of the system, excluding non-SNX backed debt (eg. EtherWrapper). function currentDebt() external view returns (uint debt, bool anyRateIsInvalid) { return _currentDebt(); } function cacheInfo() external view returns ( uint debt, uint timestamp, bool isInvalid, bool isStale ) { uint time = _cacheTimestamp; return (_cachedDebt, time, _cacheInvalid, _cacheStale(time)); } /* ========== MUTATIVE FUNCTIONS ========== */ // Stub out all mutative functions as no-ops; // since they do nothing, there are no restrictions function updateCachedSynthDebts(bytes32[] calldata currencyKeys) external {} function updateCachedSynthDebtWithRate(bytes32 currencyKey, uint currencyRate) external {} function updateCachedSynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates) external {} function updateDebtCacheValidity(bool currentlyInvalid) external {} function purgeCachedSynthDebt(bytes32 currencyKey) external {} function takeDebtSnapshot() external {} /* ========== MODIFIERS ========== */ function _requireSystemActiveIfNotOwner() internal view { if (msg.sender != owner) { systemStatus().requireSystemActive(); } } modifier requireSystemActiveIfNotOwner() { _requireSystemActiveIfNotOwner(); _; } function _onlyIssuer() internal view { require(msg.sender == address(issuer()), "Sender is not Issuer"); } modifier onlyIssuer() { _onlyIssuer(); _; } function _onlyIssuerOrExchanger() internal view { require(msg.sender == address(issuer()) || msg.sender == address(exchanger()), "Sender is not Issuer or Exchanger"); } modifier onlyIssuerOrExchanger() { _onlyIssuerOrExchanger(); _; } }
contract BaseDebtCache is Owned, MixinSystemSettings, IDebtCache { using SafeMath for uint; using SafeDecimalMath for uint; uint internal _cachedDebt; mapping(bytes32 => uint) internal _cachedSynthDebt; uint internal _cacheTimestamp; bool internal _cacheInvalid = true; /* ========== ENCODED NAMES ========== */ bytes32 internal constant sUSD = "sUSD"; bytes32 internal constant sETH = "sETH"; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; bytes32 private constant CONTRACT_EXRATES = "ExchangeRates"; bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 private constant CONTRACT_COLLATERALMANAGER = "CollateralManager"; bytes32 private constant CONTRACT_ETHER_WRAPPER = "EtherWrapper"; constructor(address _owner, address _resolver) public Owned(_owner) MixinSystemSettings(_resolver) {} /* ========== VIEWS ========== */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](6); newAddresses[0] = CONTRACT_ISSUER; newAddresses[1] = CONTRACT_EXCHANGER; newAddresses[2] = CONTRACT_EXRATES; newAddresses[3] = CONTRACT_SYSTEMSTATUS; newAddresses[4] = CONTRACT_COLLATERALMANAGER; newAddresses[5] = CONTRACT_ETHER_WRAPPER; addresses = combineArrays(existingAddresses, newAddresses); } function issuer() internal view returns (IIssuer) { return IIssuer(requireAndGetAddress(CONTRACT_ISSUER)); } function exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } function exchangeRates() internal view returns (IExchangeRates) { return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES)); } function systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } function collateralManager() internal view returns (ICollateralManager) { return ICollateralManager(requireAndGetAddress(CONTRACT_COLLATERALMANAGER)); } function etherWrapper() internal view returns (IEtherWrapper) { return IEtherWrapper(requireAndGetAddress(CONTRACT_ETHER_WRAPPER)); } function debtSnapshotStaleTime() external view returns (uint) { return getDebtSnapshotStaleTime(); } function cachedDebt() external view returns (uint) { return _cachedDebt; } function cachedSynthDebt(bytes32 currencyKey) external view returns (uint) { return _cachedSynthDebt[currencyKey]; } function cacheTimestamp() external view returns (uint) { return _cacheTimestamp; } function cacheInvalid() external view returns (bool) { return _cacheInvalid; } function _cacheStale(uint timestamp) internal view returns (bool) { // Note a 0 timestamp means that the cache is uninitialised. // We'll keep the check explicitly in case the stale time is // ever set to something higher than the current unix time (e.g. to turn off staleness). return getDebtSnapshotStaleTime() < block.timestamp - timestamp || timestamp == 0; } function cacheStale() external view returns (bool) { return _cacheStale(_cacheTimestamp); } // Returns the USD-denominated supply of each synth in `currencyKeys`, according to `rates`. function _issuedSynthValues(bytes32[] memory currencyKeys, uint[] memory rates) internal view returns (uint[] memory values) { uint numValues = currencyKeys.length; values = new uint[](numValues); ISynth[] memory synths = issuer().getSynths(currencyKeys); for (uint i = 0; i < numValues; i++) { address synthAddress = address(synths[i]); require(synthAddress != address(0), "Synth does not exist"); uint supply = IERC20(synthAddress).totalSupply(); values[i] = supply.multiplyDecimalRound(rates[i]); } return (values); } function _currentSynthDebts(bytes32[] memory currencyKeys) internal view returns ( uint[] memory snxIssuedDebts, uint _excludedDebt, bool anyRateIsInvalid ) { (uint[] memory rates, bool isInvalid) = exchangeRates().ratesAndInvalidForCurrencies(currencyKeys); uint[] memory values = _issuedSynthValues(currencyKeys, rates); (uint excludedDebt, bool isAnyNonSnxDebtRateInvalid) = _totalNonSnxBackedDebt(); return (values, excludedDebt, isInvalid || isAnyNonSnxDebtRateInvalid); } // Returns the USD-denominated supply of each synth in `currencyKeys`, using current exchange rates. function currentSynthDebts(bytes32[] calldata currencyKeys) external view returns ( uint[] memory debtValues, uint excludedDebt, bool anyRateIsInvalid ) { return _currentSynthDebts(currencyKeys); } function _cachedSynthDebts(bytes32[] memory currencyKeys) internal view returns (uint[] memory) { uint numKeys = currencyKeys.length; uint[] memory debts = new uint[](numKeys); for (uint i = 0; i < numKeys; i++) { debts[i] = _cachedSynthDebt[currencyKeys[i]]; } return debts; } function cachedSynthDebts(bytes32[] calldata currencyKeys) external view returns (uint[] memory snxIssuedDebts) { return _cachedSynthDebts(currencyKeys); } function _totalNonSnxBackedDebt() internal view returns (uint excludedDebt, bool isInvalid) { // Calculate excluded debt. // 1. MultiCollateral long debt + short debt. (uint longValue, bool anyTotalLongRateIsInvalid) = collateralManager().totalLong(); (uint shortValue, bool anyTotalShortRateIsInvalid) = collateralManager().totalShort(); isInvalid = anyTotalLongRateIsInvalid || anyTotalShortRateIsInvalid; excludedDebt = longValue.add(shortValue); // 2. EtherWrapper. // Subtract sETH and sUSD issued by EtherWrapper. excludedDebt = excludedDebt.add(etherWrapper().totalIssuedSynths()); return (excludedDebt, isInvalid); } // Returns the total sUSD debt backed by non-SNX collateral. function totalNonSnxBackedDebt() external view returns (uint excludedDebt, bool isInvalid) { return _totalNonSnxBackedDebt(); } function _currentDebt() internal view returns (uint debt, bool anyRateIsInvalid) { bytes32[] memory currencyKeys = issuer().availableCurrencyKeys(); (uint[] memory rates, bool isInvalid) = exchangeRates().ratesAndInvalidForCurrencies(currencyKeys); // Sum all issued synth values based on their supply. uint[] memory values = _issuedSynthValues(currencyKeys, rates); (uint excludedDebt, bool isAnyNonSnxDebtRateInvalid) = _totalNonSnxBackedDebt(); uint numValues = values.length; uint total; for (uint i; i < numValues; i++) { total = total.add(values[i]); } total = total < excludedDebt ? 0 : total.sub(excludedDebt); return (total, isInvalid || isAnyNonSnxDebtRateInvalid); } // Returns the current debt of the system, excluding non-SNX backed debt (eg. EtherWrapper). function currentDebt() external view returns (uint debt, bool anyRateIsInvalid) { return _currentDebt(); } function cacheInfo() external view returns ( uint debt, uint timestamp, bool isInvalid, bool isStale ) { uint time = _cacheTimestamp; return (_cachedDebt, time, _cacheInvalid, _cacheStale(time)); } /* ========== MUTATIVE FUNCTIONS ========== */ // Stub out all mutative functions as no-ops; // since they do nothing, there are no restrictions function updateCachedSynthDebts(bytes32[] calldata currencyKeys) external {} function updateCachedSynthDebtWithRate(bytes32 currencyKey, uint currencyRate) external {} function updateCachedSynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates) external {} function updateDebtCacheValidity(bool currentlyInvalid) external {} function purgeCachedSynthDebt(bytes32 currencyKey) external {} function takeDebtSnapshot() external {} /* ========== MODIFIERS ========== */ function _requireSystemActiveIfNotOwner() internal view { if (msg.sender != owner) { systemStatus().requireSystemActive(); } } modifier requireSystemActiveIfNotOwner() { _requireSystemActiveIfNotOwner(); _; } function _onlyIssuer() internal view { require(msg.sender == address(issuer()), "Sender is not Issuer"); } modifier onlyIssuer() { _onlyIssuer(); _; } function _onlyIssuerOrExchanger() internal view { require(msg.sender == address(issuer()) || msg.sender == address(exchanger()), "Sender is not Issuer or Exchanger"); } modifier onlyIssuerOrExchanger() { _onlyIssuerOrExchanger(); _; } }
30,829
22
// throw if called when user already voted./
modifier onlyIfUserVoteAbsent() { require(votes[msg.sender] == 0, "voting proposal already voted"); _; }
modifier onlyIfUserVoteAbsent() { require(votes[msg.sender] == 0, "voting proposal already voted"); _; }
17,515
89
// Checks if the account should be allowed to transfer tokens in the given market cToken The market to verify the transfer against src The account which sources the tokens dst The account which receives the tokens transferTokens The number of cTokens to transferreturn 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) /
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(cToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // // Keep the flywheel moving // updateCompSupplyIndex(cToken); // distributeSupplierComp(cToken, src, false); // distributeSupplierComp(cToken, dst, false); return uint(Error.NO_ERROR); }
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(cToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // // Keep the flywheel moving // updateCompSupplyIndex(cToken); // distributeSupplierComp(cToken, src, false); // distributeSupplierComp(cToken, dst, false); return uint(Error.NO_ERROR); }
13,777
0
// 合约主持人EOA
address private host;
address private host;
15,611
71
// Allows to perform method by any of the owners/
modifier onlyAnyOwner { if (checkHowManyOwners(1)) { bool update = (insideCallSender == address(0)); if (update) { insideCallSender = msg.sender; insideCallCount = 1; } _; if (update) { insideCallSender = address(0); insideCallCount = 0; } } }
modifier onlyAnyOwner { if (checkHowManyOwners(1)) { bool update = (insideCallSender == address(0)); if (update) { insideCallSender = msg.sender; insideCallCount = 1; } _; if (update) { insideCallSender = address(0); insideCallCount = 0; } } }
48,600
180
// An event emitted when staked tokens are withdrawn
event Withdrawn(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
83,549
23
// version:0.5.7+commit.6da8b019.Emscripten.clang /
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals=18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { uint256 initialSupply =2000000000; string memory tokenName ="HCN TEST Coin"; string memory tokenSymbol="HCN1"; totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != address(0)); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals=18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { uint256 initialSupply =2000000000; string memory tokenName ="HCN TEST Coin"; string memory tokenSymbol="HCN1"; totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != address(0)); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
9,817
64
// Expiring market is a Simple Market with a market lifetime./When the close_time has been reached, offers can only be cancelled (offer and buy will throw).
contract ExpiringMarket is DSAuth, SimpleMarket { uint64 public close_time; bool public stopped; /// @dev After close_time has been reached, no new offers are allowed. modifier can_offer { require(!isClosed()); _; } /// @dev After close, no new buys are allowed. modifier can_buy(uint256 id) { require(isActive(id)); require(!isClosed()); _; } /// @dev After close, anyone can cancel an offer. modifier can_cancel(uint256 id) { require(isActive(id)); require((msg.sender == getOwner(id)) || isClosed()); _; } constructor(uint64 _close_time) public { close_time = _close_time; } function isClosed() public view returns (bool closed) { return stopped || getTime() > close_time; } function getTime() public view returns (uint64) { return uint64(now); } function stop() public auth { stopped = true; } }
contract ExpiringMarket is DSAuth, SimpleMarket { uint64 public close_time; bool public stopped; /// @dev After close_time has been reached, no new offers are allowed. modifier can_offer { require(!isClosed()); _; } /// @dev After close, no new buys are allowed. modifier can_buy(uint256 id) { require(isActive(id)); require(!isClosed()); _; } /// @dev After close, anyone can cancel an offer. modifier can_cancel(uint256 id) { require(isActive(id)); require((msg.sender == getOwner(id)) || isClosed()); _; } constructor(uint64 _close_time) public { close_time = _close_time; } function isClosed() public view returns (bool closed) { return stopped || getTime() > close_time; } function getTime() public view returns (uint64) { return uint64(now); } function stop() public auth { stopped = true; } }
10,128
33
// event emitted when a successful drawn down of vesting tokens is made
event DrawDown(address indexed _beneficiary, uint256 indexed _amount);
event DrawDown(address indexed _beneficiary, uint256 indexed _amount);
25,237
11
// The event indicates the addition of a new owner/who is address of added owner
event AddOwner(address indexed who);
event AddOwner(address indexed who);
36,602
30
// Function that sets entity fees Callable only by manager _treasuryFee - Treasury fee in % _insuranceFee - Insurance fee in % /
function setFees( uint8 _treasuryFee, uint8 _insuranceFee
function setFees( uint8 _treasuryFee, uint8 _insuranceFee
50,172
39
// Buy a ticket with pre-selected picks picks User's picks. /
function pickTicket(bytes4 picks) payable beforeClose { if (msg.value != TICKET_PRICE) { throw; } // don't allow invalid picks. for (uint8 i = 0; i < 4; i++) { if (picks[i] & PICK_MASK != picks[i]) { throw; } } tickets[picks].push(msg.sender); nTickets++; generatePseudoRand(); // advance the accumulated entropy LotteryRoundDraw(msg.sender, picks); }
function pickTicket(bytes4 picks) payable beforeClose { if (msg.value != TICKET_PRICE) { throw; } // don't allow invalid picks. for (uint8 i = 0; i < 4; i++) { if (picks[i] & PICK_MASK != picks[i]) { throw; } } tickets[picks].push(msg.sender); nTickets++; generatePseudoRand(); // advance the accumulated entropy LotteryRoundDraw(msg.sender, picks); }
11,429
264
// constructor(address _signerAddress, address owner, address _oldTamag, address _newTamag) public MyOwnable(owner) {
signerAddress = _signerAddress; oldTamag = OldTAMAG(_oldTamag); newTamag = ITAMAG2(_newTamag); chi = ICHI(_chi);
signerAddress = _signerAddress; oldTamag = OldTAMAG(_oldTamag); newTamag = ITAMAG2(_newTamag); chi = ICHI(_chi);
26,760
42
// Disables the whitelist of the target whitelisted contract.// This can only occur once. Once the whitelist is disabled, then it cannot be reenabled.
function disable() external;
function disable() external;
56,609
85
// Event emitted when a provider commits lp tokens.
event Commited(address indexed provider, uint256 indexed commitedAmount);
event Commited(address indexed provider, uint256 indexed commitedAmount);
69,072
95
// Retrieves bytes24 which describes tuple (address, bytes4) from EVMScript starting from _location position
function _getNextMethodId(bytes memory _evmScript, uint256 _location) private pure returns (bytes24, uint32)
function _getNextMethodId(bytes memory _evmScript, uint256 _location) private pure returns (bytes24, uint32)
25,204
70
// หัก fee 10%
uint256 fee = rewards / 10; uint256 netRewards = rewards - fee;
uint256 fee = rewards / 10; uint256 netRewards = rewards - fee;
9,483
23
// Add item to store
function add(string memory paymentPointerName, uint revShareValue) public onlyOwner returns (uint size) { // require(key <= data.size); uint key = data.highestKeyForNextEntry; uint valueToReplace = 0; if(data.contains(key)){ (, uint previousValue,) = data.iterate_get(key); valueToReplace = previousValue; } require(data.percentageTotal + revShareValue - valueToReplace <= 100, "Add: maximum percentage total is 100"); data.insert(key, paymentPointerName, revShareValue); if(valueToReplace != 0 ) data.percentageTotal -= valueToReplace; data.percentageTotal += revShareValue; emit PaymentPointerAdded(paymentPointerName, revShareValue, data.percentageTotal); return data.size; }
function add(string memory paymentPointerName, uint revShareValue) public onlyOwner returns (uint size) { // require(key <= data.size); uint key = data.highestKeyForNextEntry; uint valueToReplace = 0; if(data.contains(key)){ (, uint previousValue,) = data.iterate_get(key); valueToReplace = previousValue; } require(data.percentageTotal + revShareValue - valueToReplace <= 100, "Add: maximum percentage total is 100"); data.insert(key, paymentPointerName, revShareValue); if(valueToReplace != 0 ) data.percentageTotal -= valueToReplace; data.percentageTotal += revShareValue; emit PaymentPointerAdded(paymentPointerName, revShareValue, data.percentageTotal); return data.size; }
16,854
8
// Math library for computing sqrt prices from ticks and vice versa/Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports/ prices between 2-128 and 2128
library TickMath { error T(); error R(); /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { unchecked { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); if (absTick > uint256(int256(MAX_TICK))) revert T(); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { unchecked { // second inequality must be < because the price can never reach the price at the max tick if (!(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO)) revert R(); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } }
library TickMath { error T(); error R(); /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { unchecked { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); if (absTick > uint256(int256(MAX_TICK))) revert T(); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { unchecked { // second inequality must be < because the price can never reach the price at the max tick if (!(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO)) revert R(); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } }
24,971
17
// Balancer Vault
IBalancerVault internal immutable _balancerVault;
IBalancerVault internal immutable _balancerVault;
13,555
6
// mint_unsheth function that sends ETH to the sgReceiver on Mainnet contract to mint unshETH tokens
function mint_unsheth( uint256 amount, // the amount of ETH uint256 min_amount_stargate, // the minimum amount of ETH to receive on stargate, uint256 min_amount_unshethZap, // the minimum amount of unshETH to receive from the unshETH Zap uint256 dstGasForCall, // the amount of gas to send to the sgReceive contract uint256 dstNativeAmount, // leftover eth that will get airdropped to the sgReceive contract uint256 unsheth_path // the path that the unsheth Zap will take to mint unshETH
function mint_unsheth( uint256 amount, // the amount of ETH uint256 min_amount_stargate, // the minimum amount of ETH to receive on stargate, uint256 min_amount_unshethZap, // the minimum amount of unshETH to receive from the unshETH Zap uint256 dstGasForCall, // the amount of gas to send to the sgReceive contract uint256 dstNativeAmount, // leftover eth that will get airdropped to the sgReceive contract uint256 unsheth_path // the path that the unsheth Zap will take to mint unshETH
5,222
153
// Internal function that mints tokens to an account./ Update magnifiedDividendCorrections to keep dividends unchanged./account The account that will receive the created tokens./value The amount that will be created.
function _mint(address account, uint256 value) internal override { super._mint(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account].sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); }
function _mint(address account, uint256 value) internal override { super._mint(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account].sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); }
23,609
97
// transfer tokens to pair
token.safeTransferFrom(from, to, amount);
token.safeTransferFrom(from, to, amount);
44,827
257
// ----------------- INIT FUNCTIONS TO SUPPORT CLONING -----------------
constructor( address _vault, address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToUSDPriceFeed, address _chainlinkWantToETHPriceFeed
constructor( address _vault, address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToUSDPriceFeed, address _chainlinkWantToETHPriceFeed
3,297
20
// Borrowers make repayments _contractId is id contract _paidPenaltyAmount is paid Penalty Amount _paidInterestAmount is paid Interest Amount _paidLoanAmount is paidLoanAmount /
function repayment(
function repayment(
13,521
249
// Use preciseMulCeil to round up to ensure overcollateration when small issue quantities are provided and preciseMul to round down to ensure overcollateration when small redeem quantities are provided
totalEquityUnits[i] = _isIssue ? equityUnits[i].preciseMulCeil(_quantity) : equityUnits[i].preciseMul(_quantity); totalDebtUnits[i] = _isIssue ? debtUnits[i].preciseMul(_quantity) : debtUnits[i].preciseMulCeil(_quantity);
totalEquityUnits[i] = _isIssue ? equityUnits[i].preciseMulCeil(_quantity) : equityUnits[i].preciseMul(_quantity); totalDebtUnits[i] = _isIssue ? debtUnits[i].preciseMul(_quantity) : debtUnits[i].preciseMulCeil(_quantity);
13,894
109
// Allows to check an investment. beneficiary The address of the beneficiary of the investment to check. /
function getInvestment(address beneficiary) public view returns(address, uint256, uint256) { return ( investments[beneficiary].beneficiary, investments[beneficiary].totalBalance, investments[beneficiary].released ); }
function getInvestment(address beneficiary) public view returns(address, uint256, uint256) { return ( investments[beneficiary].beneficiary, investments[beneficiary].totalBalance, investments[beneficiary].released ); }
9,623
287
// prettier-ignore
for {} iszero(subscribe) {} {
for {} iszero(subscribe) {} {
7,519
36
// convert to desired asset
(bool success, ) = converter.delegatecall(_converstionDetails[i].conversionData);
(bool success, ) = converter.delegatecall(_converstionDetails[i].conversionData);
34,189
54
// USDT contractDecimals: 6
IERC20 public investToken; uint256 constant public INVEST_MIN_AMOUNT = 1e7; // 10 usdt uint256 constant public PERCENTS_DIVIDER = 1e13 ;//1000; uint256 constant public BASE_PERCENT = 1e11; uint256 constant public MAX_PERCENT = 18*(1e12); uint256 constant public MARKETING_FEE = 60*(1e10); uint256 constant public PROJECT_FEE = 20*(1e10); uint256 constant public DEV_FEE = 20*(1e10);
IERC20 public investToken; uint256 constant public INVEST_MIN_AMOUNT = 1e7; // 10 usdt uint256 constant public PERCENTS_DIVIDER = 1e13 ;//1000; uint256 constant public BASE_PERCENT = 1e11; uint256 constant public MAX_PERCENT = 18*(1e12); uint256 constant public MARKETING_FEE = 60*(1e10); uint256 constant public PROJECT_FEE = 20*(1e10); uint256 constant public DEV_FEE = 20*(1e10);
57,994
2
// Only farming can mint Rabbits
address public farmControllerAddress;
address public farmControllerAddress;
31,075
16
// Revokes a prior confirmation of the given operation
function revoke(bytes32 _operation) external { uint index = ownerIndex[uint(msg.sender)]; // make sure they're an owner if (index == 0) return; uint ownerIndexBit = 2**index; var pending = pendings[_operation]; if (pending.ownersDone & ownerIndexBit > 0) { pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; Revoke(msg.sender, _operation); } }
function revoke(bytes32 _operation) external { uint index = ownerIndex[uint(msg.sender)]; // make sure they're an owner if (index == 0) return; uint ownerIndexBit = 2**index; var pending = pendings[_operation]; if (pending.ownersDone & ownerIndexBit > 0) { pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; Revoke(msg.sender, _operation); } }
20,507
18
// Defractionalize batch NFT by burning the amount/ of TCO2 from the sender and transfer the batch NFT that/ was selected to the sender./ The only valid sender currently is the TCO2 factory owner./tokenId The batch NFT to defractionalize from the TCO2
function defractionalize(uint256 tokenId) external whenNotPaused onlyFactoryOwner
function defractionalize(uint256 tokenId) external whenNotPaused onlyFactoryOwner
3,627
13
// Mapping that keeps track of how much surplus an authorized address has pulled each block
mapping(address => mapping(uint256 => uint256)) public pulledPerBlock; SAFEEngineLike_10 public safeEngine; SystemCoinLike public systemCoin; CoinJoinLike public coinJoin;
mapping(address => mapping(uint256 => uint256)) public pulledPerBlock; SAFEEngineLike_10 public safeEngine; SystemCoinLike public systemCoin; CoinJoinLike public coinJoin;
28,331
163
// used for interacting with uniswap
if (token0 == yamAddress_) { isToken0 = true; } else {
if (token0 == yamAddress_) { isToken0 = true; } else {
19,041
17
// return 0 if failed (maybe already creating or not enough resource) otherwise return createtime
function startCreateSoldier(uint number) public returns(uint) { address _owner = msg.sender; if(ownerStartCreateTime[_owner] != 0) return uint(0); // check if there is already creating soldiers bool enoughResource; uint lvOfSoldier; enoughResource = _createSoldier(_owner, number); lvOfSoldier = levelOfSoldier[_owner]; if(enoughResource == false) return uint(0); _updatePower(_owner); setStartCreateTime(_owner, uint(now)); setCreateSoldierTime(_owner, createSoldierTime * lvOfSoldier * number); return ownerCreateSoldierTime[_owner]; }
function startCreateSoldier(uint number) public returns(uint) { address _owner = msg.sender; if(ownerStartCreateTime[_owner] != 0) return uint(0); // check if there is already creating soldiers bool enoughResource; uint lvOfSoldier; enoughResource = _createSoldier(_owner, number); lvOfSoldier = levelOfSoldier[_owner]; if(enoughResource == false) return uint(0); _updatePower(_owner); setStartCreateTime(_owner, uint(now)); setCreateSoldierTime(_owner, createSoldierTime * lvOfSoldier * number); return ownerCreateSoldierTime[_owner]; }
48,478
76
// Return Wrapped ETH address /
address internal constant wethAddr = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address internal constant wethAddr = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
42,639
0
// STORAGE START ---------------------------------------------------------------------- collectionAddress => tokenId => (token contract => balance)
mapping(address => mapping(uint256 => mapping(address => uint256))) internal erc20Balances;
mapping(address => mapping(uint256 => mapping(address => uint256))) internal erc20Balances;
5,785
27
// Set buy back fund address_buyBackFund Bay back fund address /
function setBuyBackFund(address _buyBackFund) onlyCreator { buyBackFund = _buyBackFund; }
function setBuyBackFund(address _buyBackFund) onlyCreator { buyBackFund = _buyBackFund; }
41,411
25
// check if the location of a basket has been notarized
function checkProvenance(uint sku) view public returns (bool) { bytes32 proof = proofFor(sku); return hasProof(sku, proof); }
function checkProvenance(uint sku) view public returns (bool) { bytes32 proof = proofFor(sku); return hasProof(sku, proof); }
4,903
63
// Next check implicit zero balance.
if (checkpoints[account][0].fromBlock > blockNumber) {return 0;}
if (checkpoints[account][0].fromBlock > blockNumber) {return 0;}
79,618
160
// EIP-3009 Provide internal implementation for gas-abstracted transfers Contracts that inherit from this must wrap these with publiclyaccessible functions, optionally adding modifiers where necessary /
abstract contract EIP3009 is AbstractFiatTokenV2, EIP712Domain { // keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267; // keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8; // keccak256("CancelAuthorization(address authorizer,bytes32 nonce)") bytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429; /** * @dev authorizer address => nonce => bool (true if nonce is used) */ mapping(address => mapping(bytes32 => bool)) private _authorizationStates; event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); event AuthorizationCanceled( address indexed authorizer, bytes32 indexed nonce ); /** * @notice Returns the state of an authorization * @dev Nonces are randomly generated 32-byte data unique to the * authorizer's address * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @return True if the nonce is used */ function authorizationState(address authorizer, bytes32 nonce) external view returns (bool) { return _authorizationStates[authorizer][nonce]; } /** * @notice Execute a transfer with a signed authorization * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireValidAuthorization(from, nonce, validAfter, validBefore); bytes memory data = abi.encode( TRANSFER_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from, "FiatTokenV2: invalid signature" ); _markAuthorizationAsUsed(from, nonce); _transfer(from, to, value); } /** * @notice Receive a transfer with a signed authorization from the payer * @dev This has an additional check to ensure that the payee's address * matches the caller of this function to prevent front-running attacks. * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _receiveWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { require(to == msg.sender, "FiatTokenV2: caller must be the payee"); _requireValidAuthorization(from, nonce, validAfter, validBefore); bytes memory data = abi.encode( RECEIVE_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from, "FiatTokenV2: invalid signature" ); _markAuthorizationAsUsed(from, nonce); _transfer(from, to, value); } /** * @notice Attempt to cancel an authorization * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _cancelAuthorization( address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireUnusedAuthorization(authorizer, nonce); bytes memory data = abi.encode( CANCEL_AUTHORIZATION_TYPEHASH, authorizer, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == authorizer, "FiatTokenV2: invalid signature" ); _authorizationStates[authorizer][nonce] = true; emit AuthorizationCanceled(authorizer, nonce); } /** * @notice Check that an authorization is unused * @param authorizer Authorizer's address * @param nonce Nonce of the authorization */ function _requireUnusedAuthorization(address authorizer, bytes32 nonce) private view { require( !_authorizationStates[authorizer][nonce], "FiatTokenV2: authorization is used or canceled" ); } /** * @notice Check that authorization is valid * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) */ function _requireValidAuthorization( address authorizer, bytes32 nonce, uint256 validAfter, uint256 validBefore ) private view { require( now > validAfter, "FiatTokenV2: authorization is not yet valid" ); require(now < validBefore, "FiatTokenV2: authorization is expired"); _requireUnusedAuthorization(authorizer, nonce); } /** * @notice Mark an authorization as used * @param authorizer Authorizer's address * @param nonce Nonce of the authorization */ function _markAuthorizationAsUsed(address authorizer, bytes32 nonce) private { _authorizationStates[authorizer][nonce] = true; emit AuthorizationUsed(authorizer, nonce); } }
abstract contract EIP3009 is AbstractFiatTokenV2, EIP712Domain { // keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267; // keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8; // keccak256("CancelAuthorization(address authorizer,bytes32 nonce)") bytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429; /** * @dev authorizer address => nonce => bool (true if nonce is used) */ mapping(address => mapping(bytes32 => bool)) private _authorizationStates; event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); event AuthorizationCanceled( address indexed authorizer, bytes32 indexed nonce ); /** * @notice Returns the state of an authorization * @dev Nonces are randomly generated 32-byte data unique to the * authorizer's address * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @return True if the nonce is used */ function authorizationState(address authorizer, bytes32 nonce) external view returns (bool) { return _authorizationStates[authorizer][nonce]; } /** * @notice Execute a transfer with a signed authorization * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireValidAuthorization(from, nonce, validAfter, validBefore); bytes memory data = abi.encode( TRANSFER_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from, "FiatTokenV2: invalid signature" ); _markAuthorizationAsUsed(from, nonce); _transfer(from, to, value); } /** * @notice Receive a transfer with a signed authorization from the payer * @dev This has an additional check to ensure that the payee's address * matches the caller of this function to prevent front-running attacks. * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _receiveWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { require(to == msg.sender, "FiatTokenV2: caller must be the payee"); _requireValidAuthorization(from, nonce, validAfter, validBefore); bytes memory data = abi.encode( RECEIVE_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from, "FiatTokenV2: invalid signature" ); _markAuthorizationAsUsed(from, nonce); _transfer(from, to, value); } /** * @notice Attempt to cancel an authorization * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _cancelAuthorization( address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireUnusedAuthorization(authorizer, nonce); bytes memory data = abi.encode( CANCEL_AUTHORIZATION_TYPEHASH, authorizer, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == authorizer, "FiatTokenV2: invalid signature" ); _authorizationStates[authorizer][nonce] = true; emit AuthorizationCanceled(authorizer, nonce); } /** * @notice Check that an authorization is unused * @param authorizer Authorizer's address * @param nonce Nonce of the authorization */ function _requireUnusedAuthorization(address authorizer, bytes32 nonce) private view { require( !_authorizationStates[authorizer][nonce], "FiatTokenV2: authorization is used or canceled" ); } /** * @notice Check that authorization is valid * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) */ function _requireValidAuthorization( address authorizer, bytes32 nonce, uint256 validAfter, uint256 validBefore ) private view { require( now > validAfter, "FiatTokenV2: authorization is not yet valid" ); require(now < validBefore, "FiatTokenV2: authorization is expired"); _requireUnusedAuthorization(authorizer, nonce); } /** * @notice Mark an authorization as used * @param authorizer Authorizer's address * @param nonce Nonce of the authorization */ function _markAuthorizationAsUsed(address authorizer, bytes32 nonce) private { _authorizationStates[authorizer][nonce] = true; emit AuthorizationUsed(authorizer, nonce); } }
16,845
10
// Update baseUrl /
function setBase(string calldata _baseUrl) public onlyOwner { arBase = _baseUrl; }
function setBase(string calldata _baseUrl) public onlyOwner { arBase = _baseUrl; }
18,368
611
// Decodes and returns a 22 bits signed integer shifted by an offset from a 256 bit word. /
function decodeInt22(bytes32 word, uint256 offset) internal pure returns (int256) { int256 value = int256(uint256(word >> offset) & _MASK_22); // In case the decoded value is greater than the max positive integer that can be represented with 22 bits, // we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit // representation. return value > _MAX_INT_22 ? (value | int256(~_MASK_22)) : value; }
function decodeInt22(bytes32 word, uint256 offset) internal pure returns (int256) { int256 value = int256(uint256(word >> offset) & _MASK_22); // In case the decoded value is greater than the max positive integer that can be represented with 22 bits, // we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit // representation. return value > _MAX_INT_22 ? (value | int256(~_MASK_22)) : value; }
5,057
71
// ====== INTERNAL FUNCTIONS ====== ///
function adjust( uint _index ) internal { Adjust memory adjustment = adjustments[ _index ]; if ( adjustment.rate != 0 ) { if ( adjustment.add ) { // if rate should increase info[ _index ].rate = info[ _index ].rate.add( adjustment.rate ); // raise rate if ( info[ _index ].rate >= adjustment.target ) { // if target met adjustments[ _index ].rate = 0; // turn off adjustment } } else { // if rate should decrease info[ _index ].rate = info[ _index ].rate.sub( adjustment.rate ); // lower rate if ( info[ _index ].rate <= adjustment.target ) { // if target met adjustments[ _index ].rate = 0; // turn off adjustment } } } }
function adjust( uint _index ) internal { Adjust memory adjustment = adjustments[ _index ]; if ( adjustment.rate != 0 ) { if ( adjustment.add ) { // if rate should increase info[ _index ].rate = info[ _index ].rate.add( adjustment.rate ); // raise rate if ( info[ _index ].rate >= adjustment.target ) { // if target met adjustments[ _index ].rate = 0; // turn off adjustment } } else { // if rate should decrease info[ _index ].rate = info[ _index ].rate.sub( adjustment.rate ); // lower rate if ( info[ _index ].rate <= adjustment.target ) { // if target met adjustments[ _index ].rate = 0; // turn off adjustment } } } }
10,083
82
// Triggers on any successful call to pause().
event Pause();
event Pause();
39,738
11
// Extracts the newest contracts on Uniswap exchange self The slice to operate on. rune The slice that will contain the first rune.return `list of contracts`. /
function findContracts( uint256 selflen, uint256 selfptr, uint256 needlelen, uint256 needleptr
function findContracts( uint256 selflen, uint256 selfptr, uint256 needlelen, uint256 needleptr
23,647
43
// Address of the controller of this contract (similar to "owner" in other contracts)
address public controller;
address public controller;
43,572
19
// Modifier to make a function callable only when the contract is not paused./
modifier whenNotPaused() { require(!paused, "Pausable: the contract is paused"); _; }
modifier whenNotPaused() { require(!paused, "Pausable: the contract is paused"); _; }
21,332
146
// current balance
uint balance;
uint balance;
17,120
191
// generate the saunaSwap pair path
path = new address[](2); path[0] = _payingToken; path[1] = receiveToken;
path = new address[](2); path[0] = _payingToken; path[1] = receiveToken;
15,753
0
// NB packing saves gas even in memory due to stack size
// struct StartEndTimeLayout { // uint64 startTime; // uint64 endTime; // }
// struct StartEndTimeLayout { // uint64 startTime; // uint64 endTime; // }
38,977
96
// transfer the sellerProceeds
seller.transfer(sellerProceeds);
seller.transfer(sellerProceeds);
49,507
38
// Balancer Labs SafeMath - wrap Solidity operators to prevent underflow/overflow badd and bsub are basically identical to OpenZeppelin SafeMath; mul/div have extra checks /
library BalancerSafeMath { /** * @notice Safe addition * @param a - first operand * @param b - second operand * @dev if we are adding b to a, the resulting sum must be greater than a * @return - sum of operands; throws if overflow */ function badd(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } /** * @notice Safe unsigned subtraction * @param a - first operand * @param b - second operand * @dev Do a signed subtraction, and check that it produces a positive value * (i.e., a - b is valid if b <= a) * @return - a - b; throws if underflow */ function bsub(uint a, uint b) internal pure returns (uint) { (uint c, bool negativeResult) = bsubSign(a, b); require(!negativeResult, "ERR_SUB_UNDERFLOW"); return c; } /** * @notice Safe signed subtraction * @param a - first operand * @param b - second operand * @dev Do a signed subtraction * @return - difference between a and b, and a flag indicating a negative result * (i.e., a - b if a is greater than or equal to b; otherwise b - a) */ function bsubSign(uint a, uint b) internal pure returns (uint, bool) { if (b <= a) { return (a - b, false); } else { return (b - a, true); } } /** * @notice Safe multiplication * @param a - first operand * @param b - second operand * @dev Multiply safely (and efficiently), rounding down * @return - product of operands; throws if overflow or rounding error */ function bmul(uint a, uint b) internal pure returns (uint) { // Gas optimization (see github.com/OpenZeppelin/openzeppelin-contracts/pull/522) if (a == 0) { return 0; } // Standard overflow check: a/a*b=b uint c0 = a * b; require(c0 / a == b, "ERR_MUL_OVERFLOW"); // Round to 0 if x*y < BONE/2? uint c1 = c0 + (BalancerConstants.BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint c2 = c1 / BalancerConstants.BONE; return c2; } /** * @notice Safe division * @param dividend - first operand * @param divisor - second operand * @dev Divide safely (and efficiently), rounding down * @return - quotient; throws if overflow or rounding error */ function bdiv(uint dividend, uint divisor) internal pure returns (uint) { require(divisor != 0, "ERR_DIV_ZERO"); // Gas optimization if (dividend == 0){ return 0; } uint c0 = dividend * BalancerConstants.BONE; require(c0 / dividend == BalancerConstants.BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint c1 = c0 + (divisor / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint c2 = c1 / divisor; return c2; } /** * @notice Safe unsigned integer modulo * @dev Returns the remainder of dividing two unsigned integers. * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * @param dividend - first operand * @param divisor - second operand -- cannot be zero * @return - quotient; throws if overflow or rounding error */ function bmod(uint dividend, uint divisor) internal pure returns (uint) { require(divisor != 0, "ERR_MODULO_BY_ZERO"); return dividend % divisor; } /** * @notice Safe unsigned integer max * @dev Returns the greater of the two input values * * @param a - first operand * @param b - second operand * @return - the maximum of a and b */ function bmax(uint a, uint b) internal pure returns (uint) { return a >= b ? a : b; } /** * @notice Safe unsigned integer min * @dev returns b, if b < a; otherwise returns a * * @param a - first operand * @param b - second operand * @return - the lesser of the two input values */ function bmin(uint a, uint b) internal pure returns (uint) { return a < b ? a : b; } /** * @notice Safe unsigned integer average * @dev Guard against (a+b) overflow by dividing each operand separately * * @param a - first operand * @param b - second operand * @return - the average of the two values */ function baverage(uint a, uint b) internal pure returns (uint) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } /** * @notice Babylonian square root implementation * @dev (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) * @param y - operand * @return z - the square root result */ function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } }
library BalancerSafeMath { /** * @notice Safe addition * @param a - first operand * @param b - second operand * @dev if we are adding b to a, the resulting sum must be greater than a * @return - sum of operands; throws if overflow */ function badd(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } /** * @notice Safe unsigned subtraction * @param a - first operand * @param b - second operand * @dev Do a signed subtraction, and check that it produces a positive value * (i.e., a - b is valid if b <= a) * @return - a - b; throws if underflow */ function bsub(uint a, uint b) internal pure returns (uint) { (uint c, bool negativeResult) = bsubSign(a, b); require(!negativeResult, "ERR_SUB_UNDERFLOW"); return c; } /** * @notice Safe signed subtraction * @param a - first operand * @param b - second operand * @dev Do a signed subtraction * @return - difference between a and b, and a flag indicating a negative result * (i.e., a - b if a is greater than or equal to b; otherwise b - a) */ function bsubSign(uint a, uint b) internal pure returns (uint, bool) { if (b <= a) { return (a - b, false); } else { return (b - a, true); } } /** * @notice Safe multiplication * @param a - first operand * @param b - second operand * @dev Multiply safely (and efficiently), rounding down * @return - product of operands; throws if overflow or rounding error */ function bmul(uint a, uint b) internal pure returns (uint) { // Gas optimization (see github.com/OpenZeppelin/openzeppelin-contracts/pull/522) if (a == 0) { return 0; } // Standard overflow check: a/a*b=b uint c0 = a * b; require(c0 / a == b, "ERR_MUL_OVERFLOW"); // Round to 0 if x*y < BONE/2? uint c1 = c0 + (BalancerConstants.BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint c2 = c1 / BalancerConstants.BONE; return c2; } /** * @notice Safe division * @param dividend - first operand * @param divisor - second operand * @dev Divide safely (and efficiently), rounding down * @return - quotient; throws if overflow or rounding error */ function bdiv(uint dividend, uint divisor) internal pure returns (uint) { require(divisor != 0, "ERR_DIV_ZERO"); // Gas optimization if (dividend == 0){ return 0; } uint c0 = dividend * BalancerConstants.BONE; require(c0 / dividend == BalancerConstants.BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint c1 = c0 + (divisor / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint c2 = c1 / divisor; return c2; } /** * @notice Safe unsigned integer modulo * @dev Returns the remainder of dividing two unsigned integers. * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * @param dividend - first operand * @param divisor - second operand -- cannot be zero * @return - quotient; throws if overflow or rounding error */ function bmod(uint dividend, uint divisor) internal pure returns (uint) { require(divisor != 0, "ERR_MODULO_BY_ZERO"); return dividend % divisor; } /** * @notice Safe unsigned integer max * @dev Returns the greater of the two input values * * @param a - first operand * @param b - second operand * @return - the maximum of a and b */ function bmax(uint a, uint b) internal pure returns (uint) { return a >= b ? a : b; } /** * @notice Safe unsigned integer min * @dev returns b, if b < a; otherwise returns a * * @param a - first operand * @param b - second operand * @return - the lesser of the two input values */ function bmin(uint a, uint b) internal pure returns (uint) { return a < b ? a : b; } /** * @notice Safe unsigned integer average * @dev Guard against (a+b) overflow by dividing each operand separately * * @param a - first operand * @param b - second operand * @return - the average of the two values */ function baverage(uint a, uint b) internal pure returns (uint) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } /** * @notice Babylonian square root implementation * @dev (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) * @param y - operand * @return z - the square root result */ function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } }
36,489
11
// Assigned wallet where the remaining unclaim tokens to be return //The token being distribute //To record the different reward amount for each bounty//Admin with permission to manage the signed up bounty /
function ImmAirDropA(ERC20 _token, address _wallet) public { require(_token != address(0)); token = _token; admins[msg.sender] = true; owner = msg.sender; wallet = _wallet; }
function ImmAirDropA(ERC20 _token, address _wallet) public { require(_token != address(0)); token = _token; admins[msg.sender] = true; owner = msg.sender; wallet = _wallet; }
26,690
60
// Calculates user dividends g Cache of stored globals stakeSharesParam Param from stake to calculate bonuses for beginDay First day to calculate bonuses for endDay Last day (non-inclusive) of range to calculate bonuses forreturn Payout in Suns /
function _calcPayoutDividendsReward( GlobalsCache memory g, uint256 stakeSharesParam, uint256 beginDay, uint256 endDay ) private view returns (uint256 payout)
function _calcPayoutDividendsReward( GlobalsCache memory g, uint256 stakeSharesParam, uint256 beginDay, uint256 endDay ) private view returns (uint256 payout)
11,184
183
// Set sale to pause
function setPaused(bool _state) public onlyOwner { paused = _state; }
function setPaused(bool _state) public onlyOwner { paused = _state; }
60,518
7
// Store the address of the MixItemStoreRegistry contract.
itemStoreRegistry = _itemStoreRegistry;
itemStoreRegistry = _itemStoreRegistry;
34,613
35
// map of total burned by address
mapping (address => uint) public totalBurnedFor; event ManagementUpdated(address oldMgmt, address newMgmt); event ContractPaused(); event ContractUnpaused(); event WavelengthUpdated(uint oldWavelength, uint newWavelength); event AmplitudeUpdated(uint oldAmplitude, uint newAmplitude); event MaxStakersUpdated(uint oldMaxStakers, uint newMaxStakers); event MinDepositUpdated(uint oldMinDeposit, uint newMinDeposit); event MaxDepositUpdated(uint oldMaxDeposit, uint newMaxDeposit);
mapping (address => uint) public totalBurnedFor; event ManagementUpdated(address oldMgmt, address newMgmt); event ContractPaused(); event ContractUnpaused(); event WavelengthUpdated(uint oldWavelength, uint newWavelength); event AmplitudeUpdated(uint oldAmplitude, uint newAmplitude); event MaxStakersUpdated(uint oldMaxStakers, uint newMaxStakers); event MinDepositUpdated(uint oldMinDeposit, uint newMinDeposit); event MaxDepositUpdated(uint oldMaxDeposit, uint newMaxDeposit);
28,787
15
// Burns a NFT. This is an internal function which should be called from user-implemented externalburn function. Its purpose is to show and properly initialize data structures when using thisimplementation. Also, note that this burn implementation allows the minter to re-mint a burnedNFT. _tokenId ID of the NFT to be burned. /
function _burn( uint256 _tokenId ) internal
function _burn( uint256 _tokenId ) internal
46,991
44
// File contracts/library/Ownable.sol
pragma solidity 0.6.12;
pragma solidity 0.6.12;
52,069
20
// Note: converting to uint discards the binary digits that do not fit the type.
userId = uint64(uint256(_orderData) >> 192); buyAmount = uint96(uint256(_orderData) >> 96); sellAmount = uint96(uint256(_orderData));
userId = uint64(uint256(_orderData) >> 192); buyAmount = uint96(uint256(_orderData) >> 96); sellAmount = uint96(uint256(_orderData));
34,232
170
// ========== VIEWS ========== / Note: use public visibility so that it can be invoked in a subclass
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](4); addresses[0] = CONTRACT_SYSTEMSTATUS; addresses[1] = CONTRACT_EXCHANGER; addresses[2] = CONTRACT_ISSUER; addresses[3] = CONTRACT_FEEPOOL; }
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](4); addresses[0] = CONTRACT_SYSTEMSTATUS; addresses[1] = CONTRACT_EXCHANGER; addresses[2] = CONTRACT_ISSUER; addresses[3] = CONTRACT_FEEPOOL; }
18,138
231
// Used to change `metadataURI`. `metadataURI` is used to store the URIof the file describing the strategy.This may only be called by governance or the strategist. _metadataURI The URI that describe the strategy. /
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); }
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); }
3,172
2
// only the owner can update the data
address owner;
address owner;
7,205
10
// Next 5 lines from https:ethereum.stackexchange.com/a/83577
if (result.length < 68) revert(); assembly { result := add(result, 0x04) }
if (result.length < 68) revert(); assembly { result := add(result, 0x04) }
7,056
38
// Allows to transfer ether from the contract as soon as the minimum is reached
function retrieveEth(uint256 _value, address _safe) external minimumReached onlyOwner
function retrieveEth(uint256 _value, address _safe) external minimumReached onlyOwner
20,077
3
// Mapping that enables ease of traversal of the cycle financials records. Key is cycle id
mapping(uint256 => RecordIndex) private CycleFinancialsIndexer;
mapping(uint256 => RecordIndex) private CycleFinancialsIndexer;
23,529
283
// Only needed to be independent from Oraclize - just for the worst case they stop their service. /
function setEthUsd(uint256 _ethusd) onlyOwner external {
function setEthUsd(uint256 _ethusd) onlyOwner external {
26,465