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
17
// Ease of use function to get users pending bonus
function getPendingBonus() external view returns (uint256) { return getPendingBonus(msg.sender); }
function getPendingBonus() external view returns (uint256) { return getPendingBonus(msg.sender); }
38,688
4
// called by the owner on end of emergency, returns to normal state
function unhalt() external onlyOwner onlyInEmergency { halted = false; }
function unhalt() external onlyOwner onlyInEmergency { halted = false; }
4,711
34
// pay Funding
function payFunding (uint _payF) public { transfer (_commune, _payF); _realCrowdFunding += _payF; }
function payFunding (uint _payF) public { transfer (_commune, _payF); _realCrowdFunding += _payF; }
49,024
7
// If the specified address is not in our owner list, add them - this can be called by descendents to ensure the database is kept up to date. /
function tokenOwnerAdd(address _address) internal { if(tokenHolderAddresses[_address]) revert(); //Fail if address already possesses tokens /* They don't seem to exist, so let's add them */ allTokenHolders.length++; // Increase array size allTokenHolders[allTokenHolders.length - 1] = _address; // Add address to array position just created tokenHolderArrayPosition[_address] = allTokenHolders.length - 1; // Assign array position to token holder address/position mapping tokenHolderAddresses[_address] = true; // Set address as a valid token holder }
function tokenOwnerAdd(address _address) internal { if(tokenHolderAddresses[_address]) revert(); //Fail if address already possesses tokens /* They don't seem to exist, so let's add them */ allTokenHolders.length++; // Increase array size allTokenHolders[allTokenHolders.length - 1] = _address; // Add address to array position just created tokenHolderArrayPosition[_address] = allTokenHolders.length - 1; // Assign array position to token holder address/position mapping tokenHolderAddresses[_address] = true; // Set address as a valid token holder }
20,963
0
// Registry tracks trusted contributors: accounts and their max trust. Max trust will determine the maximum amount of tokens the account can obtain./Nelson Melina, Pavle Batuta
interface IRegistry { /// @dev Event emitted when a contributor has been added: event ContributorAdded(address adr); /// @dev Event emitted when a contributor has been removed: event ContributorRemoved(address adr); /// @notice Register a contributor and set a non-zero max trust. /// @dev Can only be called by Admin role. /// @param _adr (address) The address to register as contributor /// @param _maxTrust (uint256) The amount to set as max trust /// @param _pendingBalance (uint256) The amount to set as pending balance function registerContributor( address _adr, uint256 _maxTrust, uint256 _pendingBalance ) external; /// @notice Remove an existing contributor. /// @dev Can only be called by Admin role. /// @param _adr (address) Address to remove function removeContributor(address _adr) external; /// @notice Register a list of contributors with max trust amounts. /// @dev Can only be called by Admin role. /// @param _cnt (uint256) Number of contributors to add /// @param _adrs (address[]) Addresses to register as contributors /// @param _trusts (uint256[]) Max trust values to set to each contributor (in order) /// @param _pendingBalances (uint256[]) pending balance values to set to each contributor (in order) function registerContributors( uint256 _cnt, address[] calldata _adrs, uint256[] calldata _trusts, uint256[] calldata _pendingBalances ) external; /// @notice Return all registered contributor addresses. /// @return contributors (address[]) Adresses of all contributors function getContributors() external view returns (address[] memory contributors); /// @notice Return contributor information about all accounts in the Registry. /// @return contrubutors (address[]) Adresses of all contributors /// @return trusts (uint256[]) Max trust values for all contributors, in order. function getContributorInfo() external view returns (address[] memory contributors, uint256[] memory trusts); /// @notice Return the max trust of an address, or 0 if the address is not a contributor. /// @param _adr (address) Address to check /// @return allowed (uint256) Max trust of the address, or 0 if not a contributor. function getMaxTrust(address _adr) external view returns (uint256 maxTrust); /// @notice Return the pending balance of an address, or 0 if the address is not a contributor. /// @param _adr (address) Address to check /// @return pendingBalance (uint256) Pending balance of the address, or 0 if not a contributor. function getPendingBalance(address _adr) external view returns (uint256 pendingBalance); /// @notice Set minter contract address /// @param _minterContract (address) Address to set function setMinterContract(address _minterContract) external; /// @notice Set pending balance of an address /// @param _adr (address) Address to set /// @param _pendingBalance (uint256) Pending balance of the address function setPendingBalance(address _adr, uint256 _pendingBalance) external; /// @notice Set a list of contributors pending balances /// @dev Can only be called by Admin role. /// @param _cnt (uint256) Number of contributors to set pending balance /// @param _adrs (address[]) Addresses to set pending balance /// @param _pendingBalances (uint256[]) Pending balance values to set to each contributor (in order) function setPendingBalances( uint256 _cnt, address[] calldata _adrs, uint256[] calldata _pendingBalances ) external; /// @notice Add pending balance of an address /// @param _adr (address) Address to set /// @param _value (uint256) Value to add to pending balance of the address function addPendingBalance(address _adr, uint256 _value) external; /// @notice Add to a list of contributors' pending balances /// @dev Can only be called by Admin role. /// @param _cnt (uint256) Number of contributors to add pending balance /// @param _adrs (address[]) Addresses to add pending balance /// @param _values (uint256[]) Values to add to pending balance of each contributor (in order) function addPendingBalances( uint256 _cnt, address[] calldata _adrs, uint256[] calldata _values ) external; /// @notice Set the contibutors pending balance to zero /// @dev Can only be called by the Minter /// @param _adr (address) Contributor address function clearPendingBalance(address _adr) external; }
interface IRegistry { /// @dev Event emitted when a contributor has been added: event ContributorAdded(address adr); /// @dev Event emitted when a contributor has been removed: event ContributorRemoved(address adr); /// @notice Register a contributor and set a non-zero max trust. /// @dev Can only be called by Admin role. /// @param _adr (address) The address to register as contributor /// @param _maxTrust (uint256) The amount to set as max trust /// @param _pendingBalance (uint256) The amount to set as pending balance function registerContributor( address _adr, uint256 _maxTrust, uint256 _pendingBalance ) external; /// @notice Remove an existing contributor. /// @dev Can only be called by Admin role. /// @param _adr (address) Address to remove function removeContributor(address _adr) external; /// @notice Register a list of contributors with max trust amounts. /// @dev Can only be called by Admin role. /// @param _cnt (uint256) Number of contributors to add /// @param _adrs (address[]) Addresses to register as contributors /// @param _trusts (uint256[]) Max trust values to set to each contributor (in order) /// @param _pendingBalances (uint256[]) pending balance values to set to each contributor (in order) function registerContributors( uint256 _cnt, address[] calldata _adrs, uint256[] calldata _trusts, uint256[] calldata _pendingBalances ) external; /// @notice Return all registered contributor addresses. /// @return contributors (address[]) Adresses of all contributors function getContributors() external view returns (address[] memory contributors); /// @notice Return contributor information about all accounts in the Registry. /// @return contrubutors (address[]) Adresses of all contributors /// @return trusts (uint256[]) Max trust values for all contributors, in order. function getContributorInfo() external view returns (address[] memory contributors, uint256[] memory trusts); /// @notice Return the max trust of an address, or 0 if the address is not a contributor. /// @param _adr (address) Address to check /// @return allowed (uint256) Max trust of the address, or 0 if not a contributor. function getMaxTrust(address _adr) external view returns (uint256 maxTrust); /// @notice Return the pending balance of an address, or 0 if the address is not a contributor. /// @param _adr (address) Address to check /// @return pendingBalance (uint256) Pending balance of the address, or 0 if not a contributor. function getPendingBalance(address _adr) external view returns (uint256 pendingBalance); /// @notice Set minter contract address /// @param _minterContract (address) Address to set function setMinterContract(address _minterContract) external; /// @notice Set pending balance of an address /// @param _adr (address) Address to set /// @param _pendingBalance (uint256) Pending balance of the address function setPendingBalance(address _adr, uint256 _pendingBalance) external; /// @notice Set a list of contributors pending balances /// @dev Can only be called by Admin role. /// @param _cnt (uint256) Number of contributors to set pending balance /// @param _adrs (address[]) Addresses to set pending balance /// @param _pendingBalances (uint256[]) Pending balance values to set to each contributor (in order) function setPendingBalances( uint256 _cnt, address[] calldata _adrs, uint256[] calldata _pendingBalances ) external; /// @notice Add pending balance of an address /// @param _adr (address) Address to set /// @param _value (uint256) Value to add to pending balance of the address function addPendingBalance(address _adr, uint256 _value) external; /// @notice Add to a list of contributors' pending balances /// @dev Can only be called by Admin role. /// @param _cnt (uint256) Number of contributors to add pending balance /// @param _adrs (address[]) Addresses to add pending balance /// @param _values (uint256[]) Values to add to pending balance of each contributor (in order) function addPendingBalances( uint256 _cnt, address[] calldata _adrs, uint256[] calldata _values ) external; /// @notice Set the contibutors pending balance to zero /// @dev Can only be called by the Minter /// @param _adr (address) Contributor address function clearPendingBalance(address _adr) external; }
19,952
67
// if (!automatedMarketMakerPairs[to] && !automatedMarketMakerPairs[from]) takeFee = false;
if (takeFee) { uint256 feeAmt; if (automatedMarketMakerPairs[to]) { feeAmt = (amount * (_sellCount > _reduceTaxAt ? tax : _initialTax)) / 100; } else if (automatedMarketMakerPairs[from]) {
if (takeFee) { uint256 feeAmt; if (automatedMarketMakerPairs[to]) { feeAmt = (amount * (_sellCount > _reduceTaxAt ? tax : _initialTax)) / 100; } else if (automatedMarketMakerPairs[from]) {
34,453
150
// Increase the total Open loan count
totalOpenLoanCount = totalOpenLoanCount.add(1);
totalOpenLoanCount = totalOpenLoanCount.add(1);
35,155
104
// calculate overall value of the pools
function value(ITrueFiPool2 pool) external view returns (uint256);
function value(ITrueFiPool2 pool) external view returns (uint256);
71,597
36
// 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); }
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); }
23,874
6
// The contract that owns the token (because it was minted before this contract)
JoeHatToken hatContract;
JoeHatToken hatContract;
2,708
5
// Internal function to decode a bytes32 sample into a uint8 using an offset This function can overflow encoded The encoded value offset The offsetreturn value The decoded value /
function decodeUint8(bytes32 encoded, uint256 offset) internal pure returns (uint8 value) { assembly { value := and(shr(offset, encoded), MASK_UINT8) } }
function decodeUint8(bytes32 encoded, uint256 offset) internal pure returns (uint8 value) { assembly { value := and(shr(offset, encoded), MASK_UINT8) } }
28,728
30
// Disapproves a signer from being able to call `_selector` function on arbitrary smart contract. signer The signer to remove approval for.selector The function selector for which to remove the approval of the signer. /
function disapproveSignerForFunction(address signer, bytes4 selector) external;
function disapproveSignerForFunction(address signer, bytes4 selector) external;
35,474
22
// Module address cannot be null or sentinel.
require(address(module) != address(0) && address(module) != SENTINEL_MODULES, "Invalid module address provided");
require(address(module) != address(0) && address(module) != SENTINEL_MODULES, "Invalid module address provided");
16,193
4
// Initial cap table
createInitialFounder(cxo1, 3000); createInitialFounder(cxo2, 3000); createInitialFounder(cxo3, 3000); createInitialFounder(cdo1, 500); createInitialFounder(cdo2, 300); createInitialFounder(cdo3, 200);
createInitialFounder(cxo1, 3000); createInitialFounder(cxo2, 3000); createInitialFounder(cxo3, 3000); createInitialFounder(cdo1, 500); createInitialFounder(cdo2, 300); createInitialFounder(cdo3, 200);
37,418
186
// The price function is exp(quantities[i]/b) / sum(exp(q/b) for q in quantities) To avoid overflow, calculate with exp(quantities[i]/b - offset) / sum(exp(q/b - offset) for q in quantities)
(uint sum, , uint outcomeExpTerm) = sumExpOffset(log2N, negOutcomeTokenBalances, outcomeTokenIndex, Fixed192x64Math.EstimationMode.Midpoint); return outcomeExpTerm / (sum / ONE);
(uint sum, , uint outcomeExpTerm) = sumExpOffset(log2N, negOutcomeTokenBalances, outcomeTokenIndex, Fixed192x64Math.EstimationMode.Midpoint); return outcomeExpTerm / (sum / ONE);
49,085
134
// some functions should be available only to Value Manager address /
modifier onlyValueManager() { require(msg.sender == ValueManager, "Not Value Manager"); _;
modifier onlyValueManager() { require(msg.sender == ValueManager, "Not Value Manager"); _;
10,386
26
// require(sender == address(this), "only this contract may initiate");
address token0; address token1;
address token0; address token1;
34,768
37
// This external contract will return Tulip metadata. We are making this changable in case we need to update our current uri scheme later on./
ERC721Metadata public erc721Metadata;
ERC721Metadata public erc721Metadata;
46,911
3
// Cancels all orders below a nonce value These orders can be made active by reducing the minimum nonce minimumNonce uint256 /
function cancelUpTo(uint256 minimumNonce) external;
function cancelUpTo(uint256 minimumNonce) external;
13,938
35
// Interactions X1 - X5: OK
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); if (fromToken == pair.token0()) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); IERC20(fromToken).safeTransfer(address(pair), amountIn); pair.swap(0, amountOut, to, new bytes(0));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); if (fromToken == pair.token0()) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); IERC20(fromToken).safeTransfer(address(pair), amountIn); pair.swap(0, amountOut, to, new bytes(0));
25,357
213
// Figure out the global debt percentage delta from when they entered the system. This is a high precision integer of 27 (1e27) decimals.
uint currentDebtOwnership = state .lastDebtLedgerEntry() .divideDecimalRoundPrecise(state.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership);
uint currentDebtOwnership = state .lastDebtLedgerEntry() .divideDecimalRoundPrecise(state.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership);
62,798
133
// Set the Pool Config, initializes an instance of and start the pool._feeRecipient Number of winners in the pool /
function setFeeRecipient(address _feeRecipient) external onlyOwner { require(_feeRecipient != address(0), "Invalid address"); feeRecipient = _feeRecipient; emit FeeRecipientSet(feeRecipient); }
function setFeeRecipient(address _feeRecipient) external onlyOwner { require(_feeRecipient != address(0), "Invalid address"); feeRecipient = _feeRecipient; emit FeeRecipientSet(feeRecipient); }
29,739
63
// Returns true if the sender of this transaction is a basic account.
function isBasicAccount(address _who) internal constant returns (bool) { uint senderCodeSize; assembly { senderCodeSize := extcodesize(_who) }
function isBasicAccount(address _who) internal constant returns (bool) { uint senderCodeSize; assembly { senderCodeSize := extcodesize(_who) }
50,308
6
// int8[3] minAttack; = [int8(100), 50, 10];int8[3] attackRndLimits; = [int8(20), 10, 5];
32,514
123
// parts are stored sequentially
function deedByIndex(uint256 _index) external view returns (uint256 _deedId){ return _index; }
function deedByIndex(uint256 _index) external view returns (uint256 _deedId){ return _index; }
9,520
200
// IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.sender`, and use {_msgSender} instead. /
function _msgSender() internal view returns (address payable) { if (msg.sender != _relayHub) { return msg.sender; } else {
function _msgSender() internal view returns (address payable) { if (msg.sender != _relayHub) { return msg.sender; } else {
3,474
100
// Contract that handles metadata related methods. Methods assume a deterministic generation of URI based on token IDs. Methods also assume that URI uses hex representation of token IDs. /
contract ERC1155Metadata { // URI's default URI prefix string internal baseMetadataURI; event URI(string _uri, uint256 indexed _id); /***********************************| | Metadata Public Function s | |__________________________________*/ /** * @notice A distinct Uniform Resource Identifier (URI) for a given token. * @dev URIs are defined in RFC 3986. * URIs are assumed to be deterministically generated based on token ID * Token IDs are assumed to be represented in their hex format in URIs * @return URI string */ function uri(uint256 _id) public view returns (string memory) { return string(abi.encodePacked(baseMetadataURI, _uint2str(_id), ".json")); } /***********************************| | Metadata Internal Functions | |__________________________________*/ /** * @notice Will emit default URI log event for corresponding token _id * @param _tokenIDs Array of IDs of tokens to log default URI */ function _logURIs(uint256[] memory _tokenIDs) internal { string memory baseURL = baseMetadataURI; string memory tokenURI; for (uint256 i = 0; i < _tokenIDs.length; i++) { tokenURI = string(abi.encodePacked(baseURL, _uint2str(_tokenIDs[i]), ".json")); emit URI(tokenURI, _tokenIDs[i]); } } /** * @notice Will emit a specific URI log event for corresponding token * @param _tokenIDs IDs of the token corresponding to the _uris logged * @param _URIs The URIs of the specified _tokenIDs */ function _logURIs(uint256[] memory _tokenIDs, string[] memory _URIs) internal { require(_tokenIDs.length == _URIs.length, "ERC1155Metadata#_logURIs: INVALID_ARRAYS_LENGTH"); for (uint256 i = 0; i < _tokenIDs.length; i++) { emit URI(_URIs[i], _tokenIDs[i]); } } /** * @notice Will update the base URL of token's URI * @param _newBaseMetadataURI New base URL of token's URI */ function _setBaseMetadataURI(string memory _newBaseMetadataURI) internal { baseMetadataURI = _newBaseMetadataURI; } /***********************************| | Utility Internal Functions | |__________________________________*/ /** * @notice Convert uint256 to string * @param _i Unsigned integer to convert to string */ function _uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 ii = _i; uint256 len; // Get number of bytes while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; // Get each individual ASCII while (ii != 0) { bstr[k--] = byte(uint8(48 + ii % 10)); ii /= 10; } // Convert to string return string(bstr); } }
contract ERC1155Metadata { // URI's default URI prefix string internal baseMetadataURI; event URI(string _uri, uint256 indexed _id); /***********************************| | Metadata Public Function s | |__________________________________*/ /** * @notice A distinct Uniform Resource Identifier (URI) for a given token. * @dev URIs are defined in RFC 3986. * URIs are assumed to be deterministically generated based on token ID * Token IDs are assumed to be represented in their hex format in URIs * @return URI string */ function uri(uint256 _id) public view returns (string memory) { return string(abi.encodePacked(baseMetadataURI, _uint2str(_id), ".json")); } /***********************************| | Metadata Internal Functions | |__________________________________*/ /** * @notice Will emit default URI log event for corresponding token _id * @param _tokenIDs Array of IDs of tokens to log default URI */ function _logURIs(uint256[] memory _tokenIDs) internal { string memory baseURL = baseMetadataURI; string memory tokenURI; for (uint256 i = 0; i < _tokenIDs.length; i++) { tokenURI = string(abi.encodePacked(baseURL, _uint2str(_tokenIDs[i]), ".json")); emit URI(tokenURI, _tokenIDs[i]); } } /** * @notice Will emit a specific URI log event for corresponding token * @param _tokenIDs IDs of the token corresponding to the _uris logged * @param _URIs The URIs of the specified _tokenIDs */ function _logURIs(uint256[] memory _tokenIDs, string[] memory _URIs) internal { require(_tokenIDs.length == _URIs.length, "ERC1155Metadata#_logURIs: INVALID_ARRAYS_LENGTH"); for (uint256 i = 0; i < _tokenIDs.length; i++) { emit URI(_URIs[i], _tokenIDs[i]); } } /** * @notice Will update the base URL of token's URI * @param _newBaseMetadataURI New base URL of token's URI */ function _setBaseMetadataURI(string memory _newBaseMetadataURI) internal { baseMetadataURI = _newBaseMetadataURI; } /***********************************| | Utility Internal Functions | |__________________________________*/ /** * @notice Convert uint256 to string * @param _i Unsigned integer to convert to string */ function _uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 ii = _i; uint256 len; // Get number of bytes while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; // Get each individual ASCII while (ii != 0) { bstr[k--] = byte(uint8(48 + ii % 10)); ii /= 10; } // Convert to string return string(bstr); } }
7,796
2
// _walletLogic address of wallet implementation _usd address of token to use as base e.g cUSD for CELO, USDC for ethereum, BUSD for BSC /
function initialize(address _walletLogic, address _usd) public initializer { __Ownable_init(); __Pausable_init(); walletLogic = _walletLogic; usdToken = _usd; }
function initialize(address _walletLogic, address _usd) public initializer { __Ownable_init(); __Pausable_init(); walletLogic = _walletLogic; usdToken = _usd; }
21,607
12
// Internal ApeCoin amount for distributing staking reward claims
IERC20 public immutable apeCoin; uint256 private constant APE_COIN_PRECISION = 1e18; uint256 private constant MIN_DEPOSIT = 1 * APE_COIN_PRECISION; uint256 private constant SECONDS_PER_HOUR = 3600; uint256 private constant SECONDS_PER_MINUTE = 60; uint256 constant APECOIN_POOL_ID = 0; uint256 constant BAYC_POOL_ID = 1; uint256 constant MAYC_POOL_ID = 2; uint256 constant BAKC_POOL_ID = 3;
IERC20 public immutable apeCoin; uint256 private constant APE_COIN_PRECISION = 1e18; uint256 private constant MIN_DEPOSIT = 1 * APE_COIN_PRECISION; uint256 private constant SECONDS_PER_HOUR = 3600; uint256 private constant SECONDS_PER_MINUTE = 60; uint256 constant APECOIN_POOL_ID = 0; uint256 constant BAYC_POOL_ID = 1; uint256 constant MAYC_POOL_ID = 2; uint256 constant BAKC_POOL_ID = 3;
22,468
362
// Updates the internal accounting to track a drawdown as of current block timestamp.Does not move any money amount The amount in USDC that has been drawndown /
function drawdown(uint256 amount) external onlyAdmin { require(amount.add(balance) <= currentLimit, "Cannot drawdown more than the limit"); require(amount > 0, "Invalid drawdown amount"); uint256 timestamp = currentTime(); if (balance == 0) { setInterestAccruedAsOf(timestamp); setLastFullPaymentTime(timestamp); setTotalInterestAccrued(0); setTermEndTime(timestamp.add(SECONDS_PER_DAY.mul(termInDays))); } (uint256 _interestOwed, uint256 _principalOwed) = _updateAndGetInterestAndPrincipalOwedAsOf(timestamp); balance = balance.add(amount); updateCreditLineAccounting(balance, _interestOwed, _principalOwed); require(!_isLate(timestamp), "Cannot drawdown when payments are past due"); }
function drawdown(uint256 amount) external onlyAdmin { require(amount.add(balance) <= currentLimit, "Cannot drawdown more than the limit"); require(amount > 0, "Invalid drawdown amount"); uint256 timestamp = currentTime(); if (balance == 0) { setInterestAccruedAsOf(timestamp); setLastFullPaymentTime(timestamp); setTotalInterestAccrued(0); setTermEndTime(timestamp.add(SECONDS_PER_DAY.mul(termInDays))); } (uint256 _interestOwed, uint256 _principalOwed) = _updateAndGetInterestAndPrincipalOwedAsOf(timestamp); balance = balance.add(amount); updateCreditLineAccounting(balance, _interestOwed, _principalOwed); require(!_isLate(timestamp), "Cannot drawdown when payments are past due"); }
53,853
175
// rate = (1 + weekly rate) ^ num of weeks
uint effectiveCompoundRate = SafeDecimalMath.unit().add(TERMINAL_SUPPLY_RATE_ANNUAL.div(52)).powDecimal(numOfWeeks);
uint effectiveCompoundRate = SafeDecimalMath.unit().add(TERMINAL_SUPPLY_RATE_ANNUAL.div(52)).powDecimal(numOfWeeks);
4,882
2,308
// 1155
entry "unglimpsed" : ENG_ADJECTIVE
entry "unglimpsed" : ENG_ADJECTIVE
17,767
22
// Destroy an empty vault. Used to recover gas costs.
function destroy(bytes12 vaultId) external auth
function destroy(bytes12 vaultId) external auth
9,427
32
// Calculate price of one share (in State token)Share price is expressed times 1e18 /
function calculateSharePriceInState() external view returns (uint256) { (uint256 totalAmountStaked, ) = tokenDistributor.userInfo(address(this)); // Adjust for pending rewards totalAmountStaked += tokenDistributor.calculatePendingRewards(address(this)); return totalShares == 0 ? PRECISION_FACTOR : (totalAmountStaked * PRECISION_FACTOR) / (totalShares); }
function calculateSharePriceInState() external view returns (uint256) { (uint256 totalAmountStaked, ) = tokenDistributor.userInfo(address(this)); // Adjust for pending rewards totalAmountStaked += tokenDistributor.calculatePendingRewards(address(this)); return totalShares == 0 ? PRECISION_FACTOR : (totalAmountStaked * PRECISION_FACTOR) / (totalShares); }
65,428
130
// Destroys `tokenId`.The approval is cleared when the token is burned. Requirements: - `tokenId` must exist.
* Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); }
* Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); }
9,680
99
// Starterpack Distributor/Attempts to deliver 1 and only 1 starterpack containing ETH, ERC20 Tokens and NFT Stickerpacks to an eligible recipient/The contract assumes Signer has verified an In-App Purchase Receipt, only 1 pack per address is allowed, unless the owner calls clearPurchases()
contract Distributor is SafeTransfer, ReentrancyGuard, TokenWithdrawer { address payable private owner; // Contract deployer can modify parameters address private signer; // Signer can only distribute Starterpacks // Defines the Starterpack parameters struct Pack { StickerMarket stickerMarket; // Sticker market contract for minting the sticker pack ids uint256 ethAmount; // The Amount of ETH to transfer to the recipient address[] tokens; // Array of ERC20 Contract Addresses uint256[] tokenAmounts; // Array of ERC20 amounts corresponding to cells in tokens[] uint256[] stickerPackIds; // Array of NFT's } Pack private defaultPack; Pack private promoPack; uint private promoAvailable; ERC20Token public sntToken; bool public pause = true; uint ineligibleVersion; mapping(bytes32 => bool) public ineligible; // Used to make addresses ineligible for subsequent starterpacks, after successful transaction event RequireApproval(address attribution); mapping(address => uint) public pendingAttributionCnt; mapping(address => uint) public attributionCnt; struct Attribution { bool enabled; uint256 ethAmount; // The Amount of ETH to transfer to the referrer address[] tokens; // Array of ERC20 Contract Addresses uint256[] tokenAmounts; // Array of ERC20 amounts corresponding to cells in tokens[] uint maxThreshold; } mapping(address => Attribution) defaultAttributionSettings; mapping(address => Attribution) promoAttributionSettings; // Modifiers -------------------------------------------------------------------------------------------- // Functions only Owner can call modifier onlyOwner { require(msg.sender == owner, "Unauthorized"); _; } // Logic ------------------------------------------------------------------------------------------------ /// @notice Check if an address is eligible for a starterpack /// @dev will return false if a transaction of distributePack for _recipient has been successfully executed /// @param _recipient The address to be checked for eligibility function eligible(address _recipient) public view returns (bool){ return !ineligible[keccak256(abi.encodePacked(ineligibleVersion, _recipient))]; } /// @notice Get the starter pack configuration /// @return stickerMarket address Stickermarket contract address /// @return ethAmount uint256 ETH amount in wei that will be sent to a recipient /// @return tokens address[] List of tokens that will be sent to a recipient /// @return tokenAmounts uint[] Amount of tokens that will be sent to a recipient /// @return stickerPackIds uint[] List of sticker packs to send to a recipient function getDefaultPack() external view returns(address stickerMarket, uint256 ethAmount, address[] memory tokens, uint[] memory tokenAmounts, uint[] memory stickerPackIds) { stickerMarket = address(defaultPack.stickerMarket); ethAmount = defaultPack.ethAmount; tokens = defaultPack.tokens; tokenAmounts = defaultPack.tokenAmounts; stickerPackIds = defaultPack.stickerPackIds; } /// @notice Get the promo pack configuration /// @return stickerMarket address Stickermarket contract address /// @return ethAmount uint256 ETH amount in wei that will be sent to a recipient /// @return tokens address[] List of tokens that will be sent to a recipient /// @return tokenAmounts uint[] Amount of tokens that will be sent to a recipient /// @return stickerPackIds uint[] List of sticker packs to send to a recipient /// @return available uint number of promo packs available function getPromoPack() external view returns(address stickerMarket, uint256 ethAmount, address[] memory tokens, uint[] memory tokenAmounts, uint[] memory stickerPackIds, uint256 available) { stickerMarket = address(promoPack.stickerMarket); ethAmount = promoPack.ethAmount; tokens = promoPack.tokens; tokenAmounts = promoPack.tokenAmounts; stickerPackIds = promoPack.stickerPackIds; available = promoAvailable; } event Distributed(address indexed recipient, address indexed attribution); /// @notice Distributes a starterpack to an eligible address. Either a promo pack or a default will be distributed depending on availability /// @dev Can only be called by signer, assumes signer has validated an IAP receipt, owner can block calling by pausing. /// @param _recipient A payable address that is sent a starterpack after being checked for eligibility /// @param _attribution A payable address who referred the starterpack purchaser function distributePack(address payable _recipient, address payable _attribution) external reentrancyGuard { require(!pause, "Paused"); require(msg.sender == signer, "Unauthorized"); require(eligible(_recipient), "Recipient is not eligible."); require(_recipient != _attribution, "Recipient should be different from Attribution address"); Pack memory pack; if(promoAvailable > 0){ pack = promoPack; promoAvailable--; } else { pack = defaultPack; } // Transfer Tokens // Iterate over tokens[] and transfer the an amount corresponding to the i cell in tokenAmounts[] for (uint256 i = 0; i < pack.tokens.length; i++) { ERC20Token token = ERC20Token(pack.tokens[i]); uint256 amount = pack.tokenAmounts[i]; _safeTransfer(token, _recipient, amount); } // NFT Sticker Packs StickerType stickerType = StickerType(pack.stickerMarket.stickerType()); for (uint256 i = 0; i < pack.stickerPackIds.length; i++) { uint256 packId = pack.stickerPackIds[i]; (, bool mintable, uint256 price,) = stickerType.getPaymentData(packId); if(mintable && price > 0){ sntToken.approve(address(pack.stickerMarket),price); pack.stickerMarket.buyToken( packId, _recipient, price ); } } // The recipient is no longer eligible for a pack, unless clearPurchases is called. ineligible[keccak256(abi.encodePacked(ineligibleVersion, _recipient))] = true; // Transfer ETH // .transfer bad post Istanbul fork :| (bool success, ) = _recipient.call.value(pack.ethAmount)(""); require(success, "ETH Transfer failed"); emit Distributed(_recipient, _attribution); if (_attribution == address(0)) return; // Determine if attribution is valid bool isPromo; Attribution memory attr; if(promoAttributionSettings[_attribution].maxThreshold > 0){ isPromo = true; promoAttributionSettings[_attribution].maxThreshold--; attr = promoAttributionSettings[_attribution]; } else { attr = defaultAttributionSettings[_attribution]; } if (!attr.enabled) { attr = defaultAttributionSettings[address(0)]; } if(!isPromo && (attributionCnt[_attribution] + 1) > attr.maxThreshold){ emit RequireApproval(_attribution); pendingAttributionCnt[_attribution]++; } else { if(!isPromo){ attributionCnt[_attribution]++; } if (attr.ethAmount != 0){ (bool success, ) = _attribution.call.value(attr.ethAmount)(""); require(success, "ETH Transfer failed"); } for (uint256 i = 0; i < attr.tokens.length; i++) { ERC20Token token = ERC20Token(attr.tokens[i]); uint256 amount = attr.tokenAmounts[i]; _safeTransfer(token, _attribution, amount); } } } function _payPendingAttributions(address _attribOwner, Attribution memory attr) internal { uint pendingAttributions = pendingAttributionCnt[_attribOwner]; if (address(this).balance == 0) return; //inject FORCED TO RECEIVE ETHERS if (attr.maxThreshold < attributionCnt[_attribOwner] + pendingAttributions) return; uint totalETHToPay = pendingAttributions * attr.ethAmount; attributionCnt[_attribOwner] += pendingAttributions; pendingAttributionCnt[_attribOwner] = 0; if (totalETHToPay != 0){ (bool success, ) = _attribOwner.call.value(totalETHToPay)(""); require(success, "ETH Transfer failed"); } for (uint256 i = 0; i < attr.tokens.length; i++) { ERC20Token token = ERC20Token(attr.tokens[i]); uint256 amount = attr.tokenAmounts[i] * pendingAttributions; _safeTransfer(token, _attribOwner, amount); } } /// @notice Get rewards for specific referrer /// @param _account The address to obtain the attribution config /// @param _isPromo Indicates if the configuration for a promo should be returned or not /// @return ethAmount Amount of ETH in wei /// @return tokenLen Number of tokens configured as part of the reward /// @return maxThreshold If isPromo == true: Number of promo bonuses still available for that address else: Max number of attributions to pay before requiring approval /// @return attribCount Number of referrals function getReferralReward(address _account, bool _isPromo) public view returns (uint ethAmount, uint tokenLen, uint maxThreshold, uint attribCount) { Attribution memory attr; if(_isPromo){ attr = promoAttributionSettings[_account]; } else { attr = defaultAttributionSettings[_account]; if (!attr.enabled) { attr = defaultAttributionSettings[address(0)]; } } ethAmount = attr.ethAmount; maxThreshold = attr.maxThreshold; attribCount = attributionCnt[_account]; tokenLen = attr.tokens.length; } /// @notice Get token rewards for specific address /// @param _account The address to obtain the attribution's token config /// @param _isPromo Indicates if the configuration for a promo should be returned or not /// @param _idx Index of token array in the attribution used to obtain the token config /// @return token ERC20 contract address /// @return tokenAmount Amount of token configured in the attribution function getReferralRewardTokens(address _account, bool _isPromo, uint _idx) public view returns (address token, uint tokenAmount) { Attribution memory attr; if(_isPromo){ attr = promoAttributionSettings[_account]; } else { attr = defaultAttributionSettings[_account]; if (!attr.enabled) { attr = defaultAttributionSettings[address(0)]; } } token = attr.tokens[_idx]; tokenAmount = attr.tokenAmounts[_idx]; } fallback() external payable { // ... } // Admin ------------------------------------------------------------------------------------------------ /// @notice Allows the Owner to allow or prohibit Signer from calling distributePack(). /// @dev setPause must be called before Signer can call distributePack() function setPause(bool _pause) external onlyOwner { pause = _pause; } /// @notice Allows the owner to clear the purchase history. Recipients will be able to receive a starter pack again function clearPurchases() external onlyOwner { ineligibleVersion++; } /// @notice Set a starter pack configuration /// @dev The Owner can change the default starterpack contents /// @param _newPack starter pack configuration function changeStarterPack(Pack memory _newPack) public onlyOwner { require(_newPack.tokens.length == _newPack.tokenAmounts.length, "Mismatch with Tokens & Amounts"); for (uint256 i = 0; i < _newPack.tokens.length; i++) { require(_newPack.tokenAmounts[i] > 0, "Amounts must be non-zero"); } defaultPack = _newPack; sntToken = ERC20Token(defaultPack.stickerMarket.snt()); } /// @notice Set a promo configuration /// @dev The Owner can change the promo pack contents /// @param _newPromoPack Promo pack configuration /// @param _numberOfPacks Max number of promo packs to be given before using the default config function changePromoPack(Pack memory _newPromoPack, uint _numberOfPacks) public onlyOwner { require(_newPromoPack.tokens.length == _newPromoPack.tokenAmounts.length, "Mismatch with Tokens & Amounts"); for (uint256 i = 0; i < _newPromoPack.tokens.length; i++) { require(_newPromoPack.tokenAmounts[i] > 0, "Amounts must be non-zero"); } promoPack = _newPromoPack; promoAvailable = _numberOfPacks; } /// @notice Safety function allowing the owner to immediately pause starterpack distribution and withdraw all balances in the the contract function withdraw(address[] calldata _tokens) external onlyOwner { pause = true; withdrawTokens(_tokens, owner); } /// @notice Changes the Signer of the contract /// @param _newSigner The new Signer of the contract function changeSigner(address _newSigner) public onlyOwner { require(_newSigner != address(0), "zero_address not allowed"); signer = _newSigner; } /// @notice Changes the owner of the contract /// @param _newOwner The new owner of the contract function changeOwner(address payable _newOwner) external onlyOwner { require(_newOwner != address(0), "zero_address not allowed"); owner = _newOwner; } /// @notice Set default/custom payout and threshold for referrals /// @param _isPromo indicates if this attribution config is a promo or default config /// @param _ethAmount Payout for referrals /// @param _thresholds Max number of referrals allowed beforee requiring approval /// @param _assignedTo Use a valid address here to set custom settings. To set the default payout and threshold, use address(0); function setPayoutAndThreshold( bool _isPromo, uint256 _ethAmount, address[] calldata _tokens, uint256[] calldata _tokenAmounts, uint256[] calldata _thresholds, address[] calldata _assignedTo ) external onlyOwner { require(_thresholds.length == _assignedTo.length, "Array length mismatch"); require(_tokens.length == _tokenAmounts.length, "Array length mismatch"); for (uint256 i = 0; i < _thresholds.length; i++) { bool enabled = _assignedTo[i] != address(0); Attribution memory attr = Attribution({ enabled: enabled, ethAmount: _ethAmount, maxThreshold: _thresholds[i], tokens: _tokens, tokenAmounts: _tokenAmounts }); if(_isPromo){ promoAttributionSettings[_assignedTo[i]] = attr; } else { if(enabled){ _payPendingAttributions(_assignedTo[i], attr); } defaultAttributionSettings[_assignedTo[i]] = attr; } } } /// @notice Remove attribution configuration for addresses /// @param _assignedTo Array of addresses with an attribution configured /// @param _isPromo Indicates if the configuration to delete is the promo or default function removePayoutAndThreshold(address[] calldata _assignedTo, bool _isPromo) external onlyOwner { if (_isPromo) { for (uint256 i = 0; i < _assignedTo.length; i++) { delete promoAttributionSettings[_assignedTo[i]]; } } else { for (uint256 i = 0; i < _assignedTo.length; i++) { delete defaultAttributionSettings[_assignedTo[i]]; } } } /// @param _signer allows the contract deployer(owner) to define the signer on construction constructor(address _signer) public { require(_signer != address(0), "zero_address not allowed"); owner = msg.sender; signer = _signer; } }
contract Distributor is SafeTransfer, ReentrancyGuard, TokenWithdrawer { address payable private owner; // Contract deployer can modify parameters address private signer; // Signer can only distribute Starterpacks // Defines the Starterpack parameters struct Pack { StickerMarket stickerMarket; // Sticker market contract for minting the sticker pack ids uint256 ethAmount; // The Amount of ETH to transfer to the recipient address[] tokens; // Array of ERC20 Contract Addresses uint256[] tokenAmounts; // Array of ERC20 amounts corresponding to cells in tokens[] uint256[] stickerPackIds; // Array of NFT's } Pack private defaultPack; Pack private promoPack; uint private promoAvailable; ERC20Token public sntToken; bool public pause = true; uint ineligibleVersion; mapping(bytes32 => bool) public ineligible; // Used to make addresses ineligible for subsequent starterpacks, after successful transaction event RequireApproval(address attribution); mapping(address => uint) public pendingAttributionCnt; mapping(address => uint) public attributionCnt; struct Attribution { bool enabled; uint256 ethAmount; // The Amount of ETH to transfer to the referrer address[] tokens; // Array of ERC20 Contract Addresses uint256[] tokenAmounts; // Array of ERC20 amounts corresponding to cells in tokens[] uint maxThreshold; } mapping(address => Attribution) defaultAttributionSettings; mapping(address => Attribution) promoAttributionSettings; // Modifiers -------------------------------------------------------------------------------------------- // Functions only Owner can call modifier onlyOwner { require(msg.sender == owner, "Unauthorized"); _; } // Logic ------------------------------------------------------------------------------------------------ /// @notice Check if an address is eligible for a starterpack /// @dev will return false if a transaction of distributePack for _recipient has been successfully executed /// @param _recipient The address to be checked for eligibility function eligible(address _recipient) public view returns (bool){ return !ineligible[keccak256(abi.encodePacked(ineligibleVersion, _recipient))]; } /// @notice Get the starter pack configuration /// @return stickerMarket address Stickermarket contract address /// @return ethAmount uint256 ETH amount in wei that will be sent to a recipient /// @return tokens address[] List of tokens that will be sent to a recipient /// @return tokenAmounts uint[] Amount of tokens that will be sent to a recipient /// @return stickerPackIds uint[] List of sticker packs to send to a recipient function getDefaultPack() external view returns(address stickerMarket, uint256 ethAmount, address[] memory tokens, uint[] memory tokenAmounts, uint[] memory stickerPackIds) { stickerMarket = address(defaultPack.stickerMarket); ethAmount = defaultPack.ethAmount; tokens = defaultPack.tokens; tokenAmounts = defaultPack.tokenAmounts; stickerPackIds = defaultPack.stickerPackIds; } /// @notice Get the promo pack configuration /// @return stickerMarket address Stickermarket contract address /// @return ethAmount uint256 ETH amount in wei that will be sent to a recipient /// @return tokens address[] List of tokens that will be sent to a recipient /// @return tokenAmounts uint[] Amount of tokens that will be sent to a recipient /// @return stickerPackIds uint[] List of sticker packs to send to a recipient /// @return available uint number of promo packs available function getPromoPack() external view returns(address stickerMarket, uint256 ethAmount, address[] memory tokens, uint[] memory tokenAmounts, uint[] memory stickerPackIds, uint256 available) { stickerMarket = address(promoPack.stickerMarket); ethAmount = promoPack.ethAmount; tokens = promoPack.tokens; tokenAmounts = promoPack.tokenAmounts; stickerPackIds = promoPack.stickerPackIds; available = promoAvailable; } event Distributed(address indexed recipient, address indexed attribution); /// @notice Distributes a starterpack to an eligible address. Either a promo pack or a default will be distributed depending on availability /// @dev Can only be called by signer, assumes signer has validated an IAP receipt, owner can block calling by pausing. /// @param _recipient A payable address that is sent a starterpack after being checked for eligibility /// @param _attribution A payable address who referred the starterpack purchaser function distributePack(address payable _recipient, address payable _attribution) external reentrancyGuard { require(!pause, "Paused"); require(msg.sender == signer, "Unauthorized"); require(eligible(_recipient), "Recipient is not eligible."); require(_recipient != _attribution, "Recipient should be different from Attribution address"); Pack memory pack; if(promoAvailable > 0){ pack = promoPack; promoAvailable--; } else { pack = defaultPack; } // Transfer Tokens // Iterate over tokens[] and transfer the an amount corresponding to the i cell in tokenAmounts[] for (uint256 i = 0; i < pack.tokens.length; i++) { ERC20Token token = ERC20Token(pack.tokens[i]); uint256 amount = pack.tokenAmounts[i]; _safeTransfer(token, _recipient, amount); } // NFT Sticker Packs StickerType stickerType = StickerType(pack.stickerMarket.stickerType()); for (uint256 i = 0; i < pack.stickerPackIds.length; i++) { uint256 packId = pack.stickerPackIds[i]; (, bool mintable, uint256 price,) = stickerType.getPaymentData(packId); if(mintable && price > 0){ sntToken.approve(address(pack.stickerMarket),price); pack.stickerMarket.buyToken( packId, _recipient, price ); } } // The recipient is no longer eligible for a pack, unless clearPurchases is called. ineligible[keccak256(abi.encodePacked(ineligibleVersion, _recipient))] = true; // Transfer ETH // .transfer bad post Istanbul fork :| (bool success, ) = _recipient.call.value(pack.ethAmount)(""); require(success, "ETH Transfer failed"); emit Distributed(_recipient, _attribution); if (_attribution == address(0)) return; // Determine if attribution is valid bool isPromo; Attribution memory attr; if(promoAttributionSettings[_attribution].maxThreshold > 0){ isPromo = true; promoAttributionSettings[_attribution].maxThreshold--; attr = promoAttributionSettings[_attribution]; } else { attr = defaultAttributionSettings[_attribution]; } if (!attr.enabled) { attr = defaultAttributionSettings[address(0)]; } if(!isPromo && (attributionCnt[_attribution] + 1) > attr.maxThreshold){ emit RequireApproval(_attribution); pendingAttributionCnt[_attribution]++; } else { if(!isPromo){ attributionCnt[_attribution]++; } if (attr.ethAmount != 0){ (bool success, ) = _attribution.call.value(attr.ethAmount)(""); require(success, "ETH Transfer failed"); } for (uint256 i = 0; i < attr.tokens.length; i++) { ERC20Token token = ERC20Token(attr.tokens[i]); uint256 amount = attr.tokenAmounts[i]; _safeTransfer(token, _attribution, amount); } } } function _payPendingAttributions(address _attribOwner, Attribution memory attr) internal { uint pendingAttributions = pendingAttributionCnt[_attribOwner]; if (address(this).balance == 0) return; //inject FORCED TO RECEIVE ETHERS if (attr.maxThreshold < attributionCnt[_attribOwner] + pendingAttributions) return; uint totalETHToPay = pendingAttributions * attr.ethAmount; attributionCnt[_attribOwner] += pendingAttributions; pendingAttributionCnt[_attribOwner] = 0; if (totalETHToPay != 0){ (bool success, ) = _attribOwner.call.value(totalETHToPay)(""); require(success, "ETH Transfer failed"); } for (uint256 i = 0; i < attr.tokens.length; i++) { ERC20Token token = ERC20Token(attr.tokens[i]); uint256 amount = attr.tokenAmounts[i] * pendingAttributions; _safeTransfer(token, _attribOwner, amount); } } /// @notice Get rewards for specific referrer /// @param _account The address to obtain the attribution config /// @param _isPromo Indicates if the configuration for a promo should be returned or not /// @return ethAmount Amount of ETH in wei /// @return tokenLen Number of tokens configured as part of the reward /// @return maxThreshold If isPromo == true: Number of promo bonuses still available for that address else: Max number of attributions to pay before requiring approval /// @return attribCount Number of referrals function getReferralReward(address _account, bool _isPromo) public view returns (uint ethAmount, uint tokenLen, uint maxThreshold, uint attribCount) { Attribution memory attr; if(_isPromo){ attr = promoAttributionSettings[_account]; } else { attr = defaultAttributionSettings[_account]; if (!attr.enabled) { attr = defaultAttributionSettings[address(0)]; } } ethAmount = attr.ethAmount; maxThreshold = attr.maxThreshold; attribCount = attributionCnt[_account]; tokenLen = attr.tokens.length; } /// @notice Get token rewards for specific address /// @param _account The address to obtain the attribution's token config /// @param _isPromo Indicates if the configuration for a promo should be returned or not /// @param _idx Index of token array in the attribution used to obtain the token config /// @return token ERC20 contract address /// @return tokenAmount Amount of token configured in the attribution function getReferralRewardTokens(address _account, bool _isPromo, uint _idx) public view returns (address token, uint tokenAmount) { Attribution memory attr; if(_isPromo){ attr = promoAttributionSettings[_account]; } else { attr = defaultAttributionSettings[_account]; if (!attr.enabled) { attr = defaultAttributionSettings[address(0)]; } } token = attr.tokens[_idx]; tokenAmount = attr.tokenAmounts[_idx]; } fallback() external payable { // ... } // Admin ------------------------------------------------------------------------------------------------ /// @notice Allows the Owner to allow or prohibit Signer from calling distributePack(). /// @dev setPause must be called before Signer can call distributePack() function setPause(bool _pause) external onlyOwner { pause = _pause; } /// @notice Allows the owner to clear the purchase history. Recipients will be able to receive a starter pack again function clearPurchases() external onlyOwner { ineligibleVersion++; } /// @notice Set a starter pack configuration /// @dev The Owner can change the default starterpack contents /// @param _newPack starter pack configuration function changeStarterPack(Pack memory _newPack) public onlyOwner { require(_newPack.tokens.length == _newPack.tokenAmounts.length, "Mismatch with Tokens & Amounts"); for (uint256 i = 0; i < _newPack.tokens.length; i++) { require(_newPack.tokenAmounts[i] > 0, "Amounts must be non-zero"); } defaultPack = _newPack; sntToken = ERC20Token(defaultPack.stickerMarket.snt()); } /// @notice Set a promo configuration /// @dev The Owner can change the promo pack contents /// @param _newPromoPack Promo pack configuration /// @param _numberOfPacks Max number of promo packs to be given before using the default config function changePromoPack(Pack memory _newPromoPack, uint _numberOfPacks) public onlyOwner { require(_newPromoPack.tokens.length == _newPromoPack.tokenAmounts.length, "Mismatch with Tokens & Amounts"); for (uint256 i = 0; i < _newPromoPack.tokens.length; i++) { require(_newPromoPack.tokenAmounts[i] > 0, "Amounts must be non-zero"); } promoPack = _newPromoPack; promoAvailable = _numberOfPacks; } /// @notice Safety function allowing the owner to immediately pause starterpack distribution and withdraw all balances in the the contract function withdraw(address[] calldata _tokens) external onlyOwner { pause = true; withdrawTokens(_tokens, owner); } /// @notice Changes the Signer of the contract /// @param _newSigner The new Signer of the contract function changeSigner(address _newSigner) public onlyOwner { require(_newSigner != address(0), "zero_address not allowed"); signer = _newSigner; } /// @notice Changes the owner of the contract /// @param _newOwner The new owner of the contract function changeOwner(address payable _newOwner) external onlyOwner { require(_newOwner != address(0), "zero_address not allowed"); owner = _newOwner; } /// @notice Set default/custom payout and threshold for referrals /// @param _isPromo indicates if this attribution config is a promo or default config /// @param _ethAmount Payout for referrals /// @param _thresholds Max number of referrals allowed beforee requiring approval /// @param _assignedTo Use a valid address here to set custom settings. To set the default payout and threshold, use address(0); function setPayoutAndThreshold( bool _isPromo, uint256 _ethAmount, address[] calldata _tokens, uint256[] calldata _tokenAmounts, uint256[] calldata _thresholds, address[] calldata _assignedTo ) external onlyOwner { require(_thresholds.length == _assignedTo.length, "Array length mismatch"); require(_tokens.length == _tokenAmounts.length, "Array length mismatch"); for (uint256 i = 0; i < _thresholds.length; i++) { bool enabled = _assignedTo[i] != address(0); Attribution memory attr = Attribution({ enabled: enabled, ethAmount: _ethAmount, maxThreshold: _thresholds[i], tokens: _tokens, tokenAmounts: _tokenAmounts }); if(_isPromo){ promoAttributionSettings[_assignedTo[i]] = attr; } else { if(enabled){ _payPendingAttributions(_assignedTo[i], attr); } defaultAttributionSettings[_assignedTo[i]] = attr; } } } /// @notice Remove attribution configuration for addresses /// @param _assignedTo Array of addresses with an attribution configured /// @param _isPromo Indicates if the configuration to delete is the promo or default function removePayoutAndThreshold(address[] calldata _assignedTo, bool _isPromo) external onlyOwner { if (_isPromo) { for (uint256 i = 0; i < _assignedTo.length; i++) { delete promoAttributionSettings[_assignedTo[i]]; } } else { for (uint256 i = 0; i < _assignedTo.length; i++) { delete defaultAttributionSettings[_assignedTo[i]]; } } } /// @param _signer allows the contract deployer(owner) to define the signer on construction constructor(address _signer) public { require(_signer != address(0), "zero_address not allowed"); owner = msg.sender; signer = _signer; } }
4,675
4
// SafeMath library to support basic mathematical operations Used for security of the contract /
library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
1,479
2
// stores 1001 sequential digits of Pi in memory. Consecutive digits have been truncated to a single digit./ return uint8 a single digit 0-9 that corresponds to the array of Pi[PIndex] value/uint256 holds 78 digits, but to avoid the upper range we store only 77 per array sequence.
function RNG() internal returns(uint8) { uint Length = 77; uint256[] memory PI = new uint256[](13); PI[0] = 31415926535897932384626438327950284197169393751058209749459230781640628620898; PI[1] = 62803482534217067982148086513282306470938460950582317253594081284817450284102; PI[2] = 70193852105964629489549303819642810975659346128475648237867831652712019091456; PI[3] = 48569234603486104543264821393607260249141273724587060631581748152092096282925; PI[4] = 40917153643678925903601305305482046521384146951941516094305727036575959195309; PI[5] = 21861738193261793105185480746237962749567351857527248912793818301949129836736; PI[6] = 24065643086021394946395247371907021798609437027053921717629317675238467481846; PI[7] = 76940513205681271452635608278571342757896091736371787214684090124953430146549; PI[8] = 58537105079279689258923542019561212902196086403418159813629747130960518707213; PI[9] = 49837297804951059731732816096318595024594534690830264252308253468503526193181; PI[10]= 71010313783875286587532083814206171769147303598253490428754687315956286382353; PI[11]= 78759375195781857805321712680613019278761959092164201989380952572010654858632; PI[12]= 78659361538182796823030195203530185296895736259413891249721752834791315157485; //reset the PIndex PIndex = PIndex + 1; if (PIndex > 1000){ PIndex = 0; } //break the int down to a single digit uint8 line = uint8(PIndex / Length); uint8 position = uint8(PIndex % Length); uint256 number = PI[line]; uint256 divisor = 10**uint256(Length - position); //-position or else we will read the array right to left uint256 truncated = number / divisor; uint8 rng = uint8(truncated % 10); return rng; }
function RNG() internal returns(uint8) { uint Length = 77; uint256[] memory PI = new uint256[](13); PI[0] = 31415926535897932384626438327950284197169393751058209749459230781640628620898; PI[1] = 62803482534217067982148086513282306470938460950582317253594081284817450284102; PI[2] = 70193852105964629489549303819642810975659346128475648237867831652712019091456; PI[3] = 48569234603486104543264821393607260249141273724587060631581748152092096282925; PI[4] = 40917153643678925903601305305482046521384146951941516094305727036575959195309; PI[5] = 21861738193261793105185480746237962749567351857527248912793818301949129836736; PI[6] = 24065643086021394946395247371907021798609437027053921717629317675238467481846; PI[7] = 76940513205681271452635608278571342757896091736371787214684090124953430146549; PI[8] = 58537105079279689258923542019561212902196086403418159813629747130960518707213; PI[9] = 49837297804951059731732816096318595024594534690830264252308253468503526193181; PI[10]= 71010313783875286587532083814206171769147303598253490428754687315956286382353; PI[11]= 78759375195781857805321712680613019278761959092164201989380952572010654858632; PI[12]= 78659361538182796823030195203530185296895736259413891249721752834791315157485; //reset the PIndex PIndex = PIndex + 1; if (PIndex > 1000){ PIndex = 0; } //break the int down to a single digit uint8 line = uint8(PIndex / Length); uint8 position = uint8(PIndex % Length); uint256 number = PI[line]; uint256 divisor = 10**uint256(Length - position); //-position or else we will read the array right to left uint256 truncated = number / divisor; uint8 rng = uint8(truncated % 10); return rng; }
6,172
68
// NOTE - Check the edge cases here
if(amountObtained > amountGiven) { return SafeMath.div(amountToObtain, amountToGive) <= SafeMath.div(amountObtained, amountGiven); } else {
if(amountObtained > amountGiven) { return SafeMath.div(amountToObtain, amountToGive) <= SafeMath.div(amountObtained, amountGiven); } else {
72,474
27
// Converts an `address` into `address payable`. Note that this issimply a type cast: the actual underlying value is not changed. NOTE: This is a feature of the next version of OpenZeppelin Contracts. Get it via `npm install @openzeppelin/contracts@next`. /
function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); }
function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); }
6,682
54
// Update additional data for whitelisted wallet.Accept request from privilege adresses only._wallet The address of whitelisted wallet to update._data The checksum of new additional wallet data./
function updateWallet(address _wallet, string _data) onlyPrivilegeAddresses public { require(_wallet != address(0)); require(isWhitelisted(_wallet)); whitelist[_wallet].data = _data; }
function updateWallet(address _wallet, string _data) onlyPrivilegeAddresses public { require(_wallet != address(0)); require(isWhitelisted(_wallet)); whitelist[_wallet].data = _data; }
54,119
15
// Returns whether the caller is an account deployed by this factory.
function _isAccountOfFactory(address _account) internal view virtual returns (bool) { address impl = _getImplementation(_account); return _account.code.length > 0 && impl == accountImplementation; }
function _isAccountOfFactory(address _account) internal view virtual returns (bool) { address impl = _getImplementation(_account); return _account.code.length > 0 && impl == accountImplementation; }
26,884
65
// Emitted once a stake is scheduled for withdrawal
event StakeUnlocked( address indexed relayManager, address indexed owner, uint256 withdrawBlock );
event StakeUnlocked( address indexed relayManager, address indexed owner, uint256 withdrawBlock );
6,610
53
// Calculating the elapsed time since bond issuance
uint256 elapsedMonths = (bondYear * 12 + bondMonth) - 23640; uint256 currentTime; assembly { currentTime := timestamp() }
uint256 elapsedMonths = (bondYear * 12 + bondMonth) - 23640; uint256 currentTime; assembly { currentTime := timestamp() }
7,502
3
// ERC 20 token/
contract TRUEToken { address public founder = 0x0; //constructor function TRUEToken(address _founder) { founder = _founder; } /** * Change founder address (where ICO ETH is being forwarded). * * Applicable tests: * * - Test founder change by hacker * - Test founder change * - Test founder token allocation twice */ function changeFounder(address newFounder) { if (msg.sender!=founder) revert(); founder = newFounder; } // forward all eth to founder function() payable { if (!founder.call.value(msg.value)()) revert(); } }
contract TRUEToken { address public founder = 0x0; //constructor function TRUEToken(address _founder) { founder = _founder; } /** * Change founder address (where ICO ETH is being forwarded). * * Applicable tests: * * - Test founder change by hacker * - Test founder change * - Test founder token allocation twice */ function changeFounder(address newFounder) { if (msg.sender!=founder) revert(); founder = newFounder; } // forward all eth to founder function() payable { if (!founder.call.value(msg.value)()) revert(); } }
14,597
128
// 3. It swaps the {bry} token for {lpToken0} & {lpToken1}4. Adds more liquidity to the pool.5. It deposits the new LP tokens. /
function harvest() external whenNotPaused { require(!Address.isContract(msg.sender), "!contract"); IChefMaster(masterchef).depositLPToken(poolId, 0); chargeFees(); addLiquidity(); deposit(); emit StratHarvest(msg.sender); }
function harvest() external whenNotPaused { require(!Address.isContract(msg.sender), "!contract"); IChefMaster(masterchef).depositLPToken(poolId, 0); chargeFees(); addLiquidity(); deposit(); emit StratHarvest(msg.sender); }
17,444
6
// Returns the current implementation.
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); }
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); }
13,329
31
// bucket is not emptywe just need to find our neighbor in the bucket
uint96 cursor = checkPoints[bucket].head;
uint96 cursor = checkPoints[bucket].head;
5,410
178
// requestRandomness initiates a request for VRF output given _seedThe fulfillRandomness method receives the output, once it's provided by the Oracle, and verified by the vrfCoordinator.The _keyHash must already be registered with the VRFCoordinator, and the _fee must exceed the fee specified during registration of the _keyHash.The _seed parameter is vestigial, and is kept only for API compatibility with older versions. It can't hurt to mix in some of your own randomness, here, but it's not necessary because the VRF oracle will mix the hash of the block containing your request into the VRF seed it ultimately uses._keyHash ID of public
function requestRandomness( bytes32 _keyHash, uint256 _fee, uint256 _seed
function requestRandomness( bytes32 _keyHash, uint256 _fee, uint256 _seed
17,512
56
// See {ERC721A-_beforeTokenTransfers}/Overriden to block transfer while contract is paused (avoiding bugs).
function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal override whenNotPaused { super._beforeTokenTransfers(from, to, startTokenId, quantity); }
function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal override whenNotPaused { super._beforeTokenTransfers(from, to, startTokenId, quantity); }
70,207
2
// Called by the owner to lock. /
function lock() onlyOwner public { require(!unlockedOnce); if (!locked) { locked = true; emit Locked(); } }
function lock() onlyOwner public { require(!unlockedOnce); if (!locked) { locked = true; emit Locked(); } }
49,259
569
// MiniMe TokenController functions, not used right now/ Called when `_owner` sends ether to the MiniMe Token contractreturn True if the ether is accepted, false if it throws /
function proxyPayment( address /*_owner*/
function proxyPayment( address /*_owner*/
40,959
10
// Emitted when a new COMP speed is calculated for a market
event CompSpeedUpdated(CToken indexed cToken, uint newSpeed);
event CompSpeedUpdated(CToken indexed cToken, uint newSpeed);
30,264
0
// initialize izzy's address
_izzy = _msgSender();
_izzy = _msgSender();
24,161
1
// node in queue
struct Strategy { uint48 next; uint48 prev; address strategy; }
struct Strategy { uint48 next; uint48 prev; address strategy; }
33,000
72
// Token symbol
string private _symbol;
string private _symbol;
177
3
// The address of the reserve contract which recieves the funds from the staking contract
GoodReserveCDai public reserve;
GoodReserveCDai public reserve;
22,700
48
// Allocate the memory.
mstore(0x40, str)
mstore(0x40, str)
10,550
160
// Represents a stakeholder with active stakes
struct Stakeholder { address user; uint256 totalAmount; Stake[] stakes; }
struct Stakeholder { address user; uint256 totalAmount; Stake[] stakes; }
81,436
141
// diff ratio could be negative
// p2: P_{i} // p1: P_{i-1} // p0: P_{0} function calcDiffRatio(uint256 p2, uint256 p1, uint256 p0) internal pure returns (int128) { int128 _p2 = ABDKMath64x64.fromUInt(p2); int128 _p1 = ABDKMath64x64.fromUInt(p1); int128 _p0 = ABDKMath64x64.fromUInt(p0); return ABDKMath64x64.div(ABDKMath64x64.sub(_p2, _p1), _p0); }
// p2: P_{i} // p1: P_{i-1} // p0: P_{0} function calcDiffRatio(uint256 p2, uint256 p1, uint256 p0) internal pure returns (int128) { int128 _p2 = ABDKMath64x64.fromUInt(p2); int128 _p1 = ABDKMath64x64.fromUInt(p1); int128 _p0 = ABDKMath64x64.fromUInt(p0); return ABDKMath64x64.div(ABDKMath64x64.sub(_p2, _p1), _p0); }
40,186
40
// this will give us that particular reviews user is trying to like
Review storage review = reviews[productId][reviewIndex];
Review storage review = reviews[productId][reviewIndex];
14,878
264
// Calculate token amounts proportional to unused balances
amount0 = getBalance0() * shares / BPtotalSupply; amount1 = getBalance1() * shares / BPtotalSupply;
amount0 = getBalance0() * shares / BPtotalSupply; amount1 = getBalance1() * shares / BPtotalSupply;
35,985
4,764
// 2383
entry "lowminded" : ENG_ADJECTIVE
entry "lowminded" : ENG_ADJECTIVE
18,995
14
// Unstake the Sheet Fighters from this contract and transfer ownership to owner/Called on the "to" network for bridging/token Address of the ERC721 contract fot the tokens being bridged/owner Address of the owner of the Sheet Fighters being bridged/ids ERC721 token ids of the Sheet Fighters being bridged
function unstakeMany(address token, address owner, uint256[] calldata ids) external onlyPortal { for (uint256 i = 0; i < ids.length; i++) { delete sheetOwner[ids[i]]; IERC721(token).transferFrom(address(this), owner, ids[i]); } }
function unstakeMany(address token, address owner, uint256[] calldata ids) external onlyPortal { for (uint256 i = 0; i < ids.length; i++) { delete sheetOwner[ids[i]]; IERC721(token).transferFrom(address(this), owner, ids[i]); } }
33,816
100
// 该币种所拥有的质押能力
uint256 collateralAbility;
uint256 collateralAbility;
75,852
950
// 477
entry "divisim" : ENG_ADVERB
entry "divisim" : ENG_ADVERB
21,313
30
// new ticket is lower than currently lowest
if (newTicketValue < self.tickets[ordered[0]]) {
if (newTicketValue < self.tickets[ordered[0]]) {
51,176
245
// Mapping from `perpetualID` to approved address
mapping(uint256 => address) internal _perpetualApprovals;
mapping(uint256 => address) internal _perpetualApprovals;
31,150
52
// Get current highest bid amount
uint256 currentHighestBiddersAmount = editionBids[_editionNumber][currentHighestBidder]; if (currentHighestBidder != address(0) && currentHighestBiddersAmount > 0) {
uint256 currentHighestBiddersAmount = editionBids[_editionNumber][currentHighestBidder]; if (currentHighestBidder != address(0) && currentHighestBiddersAmount > 0) {
2,892
15
// store length in memory
mstore(outputCode, size)
mstore(outputCode, size)
1,464
16
// ------------------------------------------------------------------------ Stop Trade ------------------------------------------------------------------------
function stopTrade() public onlyOwner { require(_stopTrade != true); _stopTrade = true; }
function stopTrade() public onlyOwner { require(_stopTrade != true); _stopTrade = true; }
43,267
20
// Counter underflow is impossible as _burnCounter cannot be incremented more than `_currentIndex - _startTokenId()` times.
unchecked { return ERC721AStorage.layout()._currentIndex - ERC721AStorage.layout()._burnCounter - _startTokenId(); }
unchecked { return ERC721AStorage.layout()._currentIndex - ERC721AStorage.layout()._burnCounter - _startTokenId(); }
30,021
362
// File: @0x/contracts-utils/contracts/src/interfaces/IOwnable.sol
pragma solidity ^0.4.24;
pragma solidity ^0.4.24;
8,849
34
// Pause the contract. Called by owner or admin to pause the contract. /
function pause() onlyOwnerOrAdmin whenNotPaused external { paused = true; }
function pause() onlyOwnerOrAdmin whenNotPaused external { paused = true; }
15,104
31
// deposit is amount in wei , which was sent to the contract @ address - address of depositor @ uint256 - amount/
mapping(address => uint256) public deposits;
mapping(address => uint256) public deposits;
47,444
90
// Checks for uint variables in the disputeUintVars mapping based on the disputeId _disputeId is the dispute id; _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 disputeUintVars under the Dispute structreturn uint value for the bytes32 data submitted /
function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256)
function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256)
7,305
69
// Each non-fungible token owner can own more than one token at one time.Because each token is referenced by its unique ID, however,it can get difficult to keep track of the individual tokens that a user may own.To do this, the contract keeps a record of the IDs of each token that each user owns. /
mapping(address => uint[]) public ownerTokens;
mapping(address => uint[]) public ownerTokens;
41,295
117
// Adjust reputation score
reputation.adjustReputationScore( currentContract.terms.borrower, IReputation.ReasonType.BR_LATE_PAYMENT );
reputation.adjustReputationScore( currentContract.terms.borrower, IReputation.ReasonType.BR_LATE_PAYMENT );
13,712
15
// Getting verification data from offchain database
requestIsProject( _jwtToken, _jobId, _orgAddress, senderAddress, receiverAddress ); requestSenderAuthority( _jwtToken, _jobId,
requestIsProject( _jwtToken, _jobId, _orgAddress, senderAddress, receiverAddress ); requestSenderAuthority( _jwtToken, _jobId,
29,018
31
// constructor
constructor() { admin = msg.sender; }
constructor() { admin = msg.sender; }
12,798
9
// the validator must stake himselft the minimum stake
if (stakeAmount(_validator) >= getMinStake() && !isPendingValidator(_validator)) { _pendingValidatorsAdd(_validator); _setValidatorFee(_validator, DEFAULT_VALIDATOR_FEE); }
if (stakeAmount(_validator) >= getMinStake() && !isPendingValidator(_validator)) { _pendingValidatorsAdd(_validator); _setValidatorFee(_validator, DEFAULT_VALIDATOR_FEE); }
31,219
122
// verify ALI tokens are already transferred to iNFT
require(aliBalance + aliDelta <= ERC20(aliContract).balanceOf(address(this)), "ALI tokens not yet transferred");
require(aliBalance + aliDelta <= ERC20(aliContract).balanceOf(address(this)), "ALI tokens not yet transferred");
40,556
135
// token metadata
uint8 underlyingDecimals; uint8 baseDecimals;
uint8 underlyingDecimals; uint8 baseDecimals;
23,329
482
// isApprovedForAll(): returns true if _operator is anoperator for _owner
function isApprovedForAll(address _owner, address _operator) public view returns (bool result)
function isApprovedForAll(address _owner, address _operator) public view returns (bool result)
52,823
9
// EMITIR EVENTO para que lo escuche OPEN ZEPPELIN DEFENDER
emit DeliverNft(msg.sender, _id); tokensSold[_id] = true;
emit DeliverNft(msg.sender, _id); tokensSold[_id] = true;
20,925
121
// Tokens are transferred in by the pair calling router.pairTransferERC20From Total tokens taken from sender cannot exceed inputAmount because otherwise the deduction from remainingValue will fail
remainingValue -= swapList[i].pair.swapTokenForAnyNFTs( swapList[i].numItems, remainingValue, nftRecipient, true, msg.sender ); unchecked { ++i;
remainingValue -= swapList[i].pair.swapTokenForAnyNFTs( swapList[i].numItems, remainingValue, nftRecipient, true, msg.sender ); unchecked { ++i;
44,832
16
// sends to the entrypoint (msg.sender) the missing funds for this transaction.subclass MAY override this method for better funds management(e.g. send to the entryPoint more than the minimum required, so that in future transactionsit will not be required to send again) missingAccountFunds the minimum value this method should send the entrypoint. this value MAY be zero, in case there is enough deposit, or the userOp has a paymaster. /
function _payPrefund(uint256 missingAccountFunds) internal { if (missingAccountFunds != 0) { (bool success, ) = payable(msg.sender).call{value: missingAccountFunds, gas: type(uint256).max}(""); (success); //ignore failure (its EntryPoint's job to verify, not account.) } }
function _payPrefund(uint256 missingAccountFunds) internal { if (missingAccountFunds != 0) { (bool success, ) = payable(msg.sender).call{value: missingAccountFunds, gas: type(uint256).max}(""); (success); //ignore failure (its EntryPoint's job to verify, not account.) } }
5,621
149
// array of all registrations
address[] public registrations;
address[] public registrations;
20,130
6,512
// 3258
entry "tonnishly" : ENG_ADVERB
entry "tonnishly" : ENG_ADVERB
24,094
49
// Assigned platform, immutable.
Platform public platform;
Platform public platform;
4,582
0
// ForkPreIco Extends from DefaultCrowdsale /
contract ForkPreIco is DefaultCrowdsale { constructor( uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _tokenCap, uint256 _minimumContribution, uint256 _maximumContribution, address _token, address _contributions ) DefaultCrowdsale( _startTime, _endTime, _rate, _wallet, _tokenCap, _minimumContribution, _maximumContribution, _token, _contributions ) public {} }
contract ForkPreIco is DefaultCrowdsale { constructor( uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _tokenCap, uint256 _minimumContribution, uint256 _maximumContribution, address _token, address _contributions ) DefaultCrowdsale( _startTime, _endTime, _rate, _wallet, _tokenCap, _minimumContribution, _maximumContribution, _token, _contributions ) public {} }
29,802
10
// Returns if avatar of the given hash exists. /
function isExists(bytes32 avatarHash) constant returns (bool) { Avatar memory avatar = avatars[avatarHash]; if (avatar.id == 0) return false; return true; }
function isExists(bytes32 avatarHash) constant returns (bool) { Avatar memory avatar = avatars[avatarHash]; if (avatar.id == 0) return false; return true; }
38,285
109
// The next four arguments form a balance proof
bytes32 balance_hash, uint256 nonce, bytes32 additional_hash, bytes calldata closing_signature, bytes calldata non_closing_signature ) external
bytes32 balance_hash, uint256 nonce, bytes32 additional_hash, bytes calldata closing_signature, bytes calldata non_closing_signature ) external
27,771
180
// 设置每个区块产量
function setAlpacaPerBlock(uint256 _alpacaPerBlock) public onlyOwner { alpacaPerBlock = _alpacaPerBlock; }
function setAlpacaPerBlock(uint256 _alpacaPerBlock) public onlyOwner { alpacaPerBlock = _alpacaPerBlock; }
41,459
103
// ERC165 interface ID of ERC165
bytes4 internal constant ERC165_INTERFACE_ID = 0x01ffc9a7;
bytes4 internal constant ERC165_INTERFACE_ID = 0x01ffc9a7;
72,107
160
// Withdraw shares of the vault to deposit token
IVault(_vaultAddress).withdraw(shares);
IVault(_vaultAddress).withdraw(shares);
47,610
139
// check whether there are enough unpending assets to sell
maskedValue = uint256(allAsset & mask); require(addAmount <= maskedValue);
maskedValue = uint256(allAsset & mask); require(addAmount <= maskedValue);
75,589
41
// The Contract is Mongolian National MDEX Token Issue. @Author: Tim Wars @Date: 2018.8.1 @Seealso: ERC20
contract MntToken { // === Event === event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); event Burn(address indexed from, uint value); event TransferLocked(address indexed from, address indexed to, uint value, uint8 locktype); event Purchased(address indexed recipient, uint purchase, uint amount); // === Defined === using SafeMath for uint; // --- Owner Section --- address public owner; bool public frozen = false; // // --- ERC20 Token Section --- uint8 constant public decimals = 6; uint public totalSupply = 100*10**(8+uint256(decimals)); // ***** 100 * 100 Million string constant public name = "MDEX Token | Mongolia National Blockchain Digital Assets Exchange Token"; string constant public symbol = "MNT"; mapping(address => uint) ownerance; // Owner Balance mapping(address => mapping(address => uint)) public allowance; // Allower Balance // --- Locked Section --- uint8 LOCKED_TYPE_MAX = 2; // ***** Max locked type uint private constant RELEASE_BASE_TIME = 1533686888; // ***** (2018-08-08 08:08:08) Private Lock phase start datetime (UTC seconds) address[] private lockedOwner; mapping(address => uint) public lockedance; // Lockeder Balance mapping(address => uint8) public lockedtype; // Locked Type mapping(address => uint8) public unlockedstep; // Unlocked Step uint public totalCirculating; // Total circulating token amount // === Modifier === // --- Owner Section --- modifier isOwner() { require(msg.sender == owner); _; } modifier isNotFrozen() { require(!frozen); _; } // --- ERC20 Section --- modifier hasEnoughBalance(uint _amount) { require(ownerance[msg.sender] >= _amount); _; } modifier overflowDetected(address _owner, uint _amount) { require(ownerance[_owner] + _amount >= ownerance[_owner]); _; } modifier hasAllowBalance(address _owner, address _allower, uint _amount) { require(allowance[_owner][_allower] >= _amount); _; } modifier isNotEmpty(address _addr, uint _value) { require(_addr != address(0)); require(_value != 0); _; } modifier isValidAddress { assert(0x0 != msg.sender); _; } // --- Locked Section --- modifier hasntLockedBalance(address _checker) { require(lockedtype[_checker] == 0); _; } modifier checkLockedType(uint8 _locktype) { require(_locktype > 0 && _locktype <= LOCKED_TYPE_MAX); _; } // === Constructor === constructor() public { owner = msg.sender; ownerance[msg.sender] = totalSupply; totalCirculating = totalSupply; emit Transfer(address(0), msg.sender, totalSupply); } // --- ERC20 Token Section --- function approve(address _spender, uint _value) isNotFrozen isValidAddress public returns (bool success) { require(_value == 0 || allowance[msg.sender][_spender] == 0); // must spend to 0 where pre approve balance. allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function transferFrom(address _from, address _to, uint _value) isNotFrozen isValidAddress overflowDetected(_to, _value) public returns (bool success) { require(ownerance[_from] >= _value); require(allowance[_from][msg.sender] >= _value); ownerance[_to] = ownerance[_to].add(_value); ownerance[_from] = ownerance[_from].sub(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint balance) { balance = ownerance[_owner] + lockedance[_owner]; return balance; } function available(address _owner) public constant returns (uint) { return ownerance[_owner]; } function transfer(address _to, uint _value) public isNotFrozen isValidAddress isNotEmpty(_to, _value) hasEnoughBalance(_value) overflowDetected(_to, _value) returns (bool success) { ownerance[msg.sender] = ownerance[msg.sender].sub(_value); ownerance[_to] = ownerance[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } // --- Owner Section --- function transferOwner(address _newOwner) isOwner public returns (bool success) { if (_newOwner != address(0)) { owner = _newOwner; } return true; } function freeze() isOwner public returns (bool success) { frozen = true; return true; } function unfreeze() isOwner public returns (bool success) { frozen = false; return true; } function burn(uint _value) isNotFrozen isValidAddress hasEnoughBalance(_value) public returns (bool success) { ownerance[msg.sender] = ownerance[msg.sender].sub(_value); ownerance[0x0] = ownerance[0x0].add(_value); totalSupply = totalSupply.sub(_value); totalCirculating = totalCirculating.sub(_value); emit Burn(msg.sender, _value); return true; } // --- Locked Section --- function transferLocked(address _to, uint _value, uint8 _locktype) public isNotFrozen isOwner isValidAddress isNotEmpty(_to, _value) hasEnoughBalance(_value) hasntLockedBalance(_to) checkLockedType(_locktype) returns (bool success) { require(msg.sender != _to); ownerance[msg.sender] = ownerance[msg.sender].sub(_value); if (_locktype == 1) { lockedance[_to] = _value; lockedtype[_to] = _locktype; lockedOwner.push(_to); totalCirculating = totalCirculating.sub(_value); emit TransferLocked(msg.sender, _to, _value, _locktype); } else if (_locktype == 2) { uint _first = _value / 100 * 8; // prevent overflow ownerance[_to] = ownerance[_to].add(_first); lockedance[_to] = _value.sub(_first); lockedtype[_to] = _locktype; lockedOwner.push(_to); totalCirculating = totalCirculating.sub(_value.sub(_first)); emit Transfer(msg.sender, _to, _first); emit TransferLocked(msg.sender, _to, _value.sub(_first), _locktype); } return true; } // ***** // Because too many unlocking steps * accounts, it will burn lots of GAS !!!!!!!!!!!!!!!!!!!!!!!!!!! // Because too many unlocking steps * accounts, it will burn lots of GAS !!!!!!!!!!!!!!!!!!!!!!!!!!! // // LockedType 1 : after 6 monthes / release 10 % per month; 10 steps // LockedType 2 : before 0 monthes / release 8 % per month; 11 steps / 1 step has release real balance init. function unlock(address _locker, uint _delta, uint8 _locktype) private returns (bool success) { if (_locktype == 1) { if (_delta < 6 * 30 days) { return false; } uint _more1 = _delta.sub(6 * 30 days); uint _step1 = _more1 / 30 days; for(uint8 i = 0; i < 10; i++) { if (unlockedstep[_locker] == i && i < 9 && i <= _step1 ) { ownerance[_locker] = ownerance[_locker].add(lockedance[_locker] / (10 - i)); lockedance[_locker] = lockedance[_locker].sub(lockedance[_locker] / (10 - i)); unlockedstep[_locker] = i + 1; } else if (i == 9 && unlockedstep[_locker] == 9 && _step1 == 9){ ownerance[_locker] = ownerance[_locker].add(lockedance[_locker]); lockedance[_locker] = 0; unlockedstep[_locker] = 0; lockedtype[_locker] = 0; } } } else if (_locktype == 2) { if (_delta < 30 days) { return false; } uint _more2 = _delta - 30 days; uint _step2 = _more2 / 30 days; for(uint8 j = 0; j < 11; j++) { if (unlockedstep[_locker] == j && j < 10 && j <= _step2 ) { ownerance[_locker] = ownerance[_locker].add(lockedance[_locker] / (11 - j)); lockedance[_locker] = lockedance[_locker].sub(lockedance[_locker] / (11 - j)); unlockedstep[_locker] = j + 1; } else if (j == 10 && unlockedstep[_locker] == 10 && _step2 == 10){ ownerance[_locker] = ownerance[_locker].add(lockedance[_locker]); lockedance[_locker] = 0; unlockedstep[_locker] = 0; lockedtype[_locker] = 0; } } } return true; } function lockedCounts() public view returns (uint counts) { return lockedOwner.length; } function releaseLocked() public isNotFrozen returns (bool success) { require(now > RELEASE_BASE_TIME); uint delta = now - RELEASE_BASE_TIME; uint lockedAmount; for (uint i = 0; i < lockedOwner.length; i++) { if ( lockedance[lockedOwner[i]] > 0) { lockedAmount = lockedance[lockedOwner[i]]; unlock(lockedOwner[i], delta, lockedtype[lockedOwner[i]]); totalCirculating = totalCirculating.add(lockedAmount - lockedance[lockedOwner[i]]); } } return true; } }
contract MntToken { // === Event === event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); event Burn(address indexed from, uint value); event TransferLocked(address indexed from, address indexed to, uint value, uint8 locktype); event Purchased(address indexed recipient, uint purchase, uint amount); // === Defined === using SafeMath for uint; // --- Owner Section --- address public owner; bool public frozen = false; // // --- ERC20 Token Section --- uint8 constant public decimals = 6; uint public totalSupply = 100*10**(8+uint256(decimals)); // ***** 100 * 100 Million string constant public name = "MDEX Token | Mongolia National Blockchain Digital Assets Exchange Token"; string constant public symbol = "MNT"; mapping(address => uint) ownerance; // Owner Balance mapping(address => mapping(address => uint)) public allowance; // Allower Balance // --- Locked Section --- uint8 LOCKED_TYPE_MAX = 2; // ***** Max locked type uint private constant RELEASE_BASE_TIME = 1533686888; // ***** (2018-08-08 08:08:08) Private Lock phase start datetime (UTC seconds) address[] private lockedOwner; mapping(address => uint) public lockedance; // Lockeder Balance mapping(address => uint8) public lockedtype; // Locked Type mapping(address => uint8) public unlockedstep; // Unlocked Step uint public totalCirculating; // Total circulating token amount // === Modifier === // --- Owner Section --- modifier isOwner() { require(msg.sender == owner); _; } modifier isNotFrozen() { require(!frozen); _; } // --- ERC20 Section --- modifier hasEnoughBalance(uint _amount) { require(ownerance[msg.sender] >= _amount); _; } modifier overflowDetected(address _owner, uint _amount) { require(ownerance[_owner] + _amount >= ownerance[_owner]); _; } modifier hasAllowBalance(address _owner, address _allower, uint _amount) { require(allowance[_owner][_allower] >= _amount); _; } modifier isNotEmpty(address _addr, uint _value) { require(_addr != address(0)); require(_value != 0); _; } modifier isValidAddress { assert(0x0 != msg.sender); _; } // --- Locked Section --- modifier hasntLockedBalance(address _checker) { require(lockedtype[_checker] == 0); _; } modifier checkLockedType(uint8 _locktype) { require(_locktype > 0 && _locktype <= LOCKED_TYPE_MAX); _; } // === Constructor === constructor() public { owner = msg.sender; ownerance[msg.sender] = totalSupply; totalCirculating = totalSupply; emit Transfer(address(0), msg.sender, totalSupply); } // --- ERC20 Token Section --- function approve(address _spender, uint _value) isNotFrozen isValidAddress public returns (bool success) { require(_value == 0 || allowance[msg.sender][_spender] == 0); // must spend to 0 where pre approve balance. allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function transferFrom(address _from, address _to, uint _value) isNotFrozen isValidAddress overflowDetected(_to, _value) public returns (bool success) { require(ownerance[_from] >= _value); require(allowance[_from][msg.sender] >= _value); ownerance[_to] = ownerance[_to].add(_value); ownerance[_from] = ownerance[_from].sub(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint balance) { balance = ownerance[_owner] + lockedance[_owner]; return balance; } function available(address _owner) public constant returns (uint) { return ownerance[_owner]; } function transfer(address _to, uint _value) public isNotFrozen isValidAddress isNotEmpty(_to, _value) hasEnoughBalance(_value) overflowDetected(_to, _value) returns (bool success) { ownerance[msg.sender] = ownerance[msg.sender].sub(_value); ownerance[_to] = ownerance[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } // --- Owner Section --- function transferOwner(address _newOwner) isOwner public returns (bool success) { if (_newOwner != address(0)) { owner = _newOwner; } return true; } function freeze() isOwner public returns (bool success) { frozen = true; return true; } function unfreeze() isOwner public returns (bool success) { frozen = false; return true; } function burn(uint _value) isNotFrozen isValidAddress hasEnoughBalance(_value) public returns (bool success) { ownerance[msg.sender] = ownerance[msg.sender].sub(_value); ownerance[0x0] = ownerance[0x0].add(_value); totalSupply = totalSupply.sub(_value); totalCirculating = totalCirculating.sub(_value); emit Burn(msg.sender, _value); return true; } // --- Locked Section --- function transferLocked(address _to, uint _value, uint8 _locktype) public isNotFrozen isOwner isValidAddress isNotEmpty(_to, _value) hasEnoughBalance(_value) hasntLockedBalance(_to) checkLockedType(_locktype) returns (bool success) { require(msg.sender != _to); ownerance[msg.sender] = ownerance[msg.sender].sub(_value); if (_locktype == 1) { lockedance[_to] = _value; lockedtype[_to] = _locktype; lockedOwner.push(_to); totalCirculating = totalCirculating.sub(_value); emit TransferLocked(msg.sender, _to, _value, _locktype); } else if (_locktype == 2) { uint _first = _value / 100 * 8; // prevent overflow ownerance[_to] = ownerance[_to].add(_first); lockedance[_to] = _value.sub(_first); lockedtype[_to] = _locktype; lockedOwner.push(_to); totalCirculating = totalCirculating.sub(_value.sub(_first)); emit Transfer(msg.sender, _to, _first); emit TransferLocked(msg.sender, _to, _value.sub(_first), _locktype); } return true; } // ***** // Because too many unlocking steps * accounts, it will burn lots of GAS !!!!!!!!!!!!!!!!!!!!!!!!!!! // Because too many unlocking steps * accounts, it will burn lots of GAS !!!!!!!!!!!!!!!!!!!!!!!!!!! // // LockedType 1 : after 6 monthes / release 10 % per month; 10 steps // LockedType 2 : before 0 monthes / release 8 % per month; 11 steps / 1 step has release real balance init. function unlock(address _locker, uint _delta, uint8 _locktype) private returns (bool success) { if (_locktype == 1) { if (_delta < 6 * 30 days) { return false; } uint _more1 = _delta.sub(6 * 30 days); uint _step1 = _more1 / 30 days; for(uint8 i = 0; i < 10; i++) { if (unlockedstep[_locker] == i && i < 9 && i <= _step1 ) { ownerance[_locker] = ownerance[_locker].add(lockedance[_locker] / (10 - i)); lockedance[_locker] = lockedance[_locker].sub(lockedance[_locker] / (10 - i)); unlockedstep[_locker] = i + 1; } else if (i == 9 && unlockedstep[_locker] == 9 && _step1 == 9){ ownerance[_locker] = ownerance[_locker].add(lockedance[_locker]); lockedance[_locker] = 0; unlockedstep[_locker] = 0; lockedtype[_locker] = 0; } } } else if (_locktype == 2) { if (_delta < 30 days) { return false; } uint _more2 = _delta - 30 days; uint _step2 = _more2 / 30 days; for(uint8 j = 0; j < 11; j++) { if (unlockedstep[_locker] == j && j < 10 && j <= _step2 ) { ownerance[_locker] = ownerance[_locker].add(lockedance[_locker] / (11 - j)); lockedance[_locker] = lockedance[_locker].sub(lockedance[_locker] / (11 - j)); unlockedstep[_locker] = j + 1; } else if (j == 10 && unlockedstep[_locker] == 10 && _step2 == 10){ ownerance[_locker] = ownerance[_locker].add(lockedance[_locker]); lockedance[_locker] = 0; unlockedstep[_locker] = 0; lockedtype[_locker] = 0; } } } return true; } function lockedCounts() public view returns (uint counts) { return lockedOwner.length; } function releaseLocked() public isNotFrozen returns (bool success) { require(now > RELEASE_BASE_TIME); uint delta = now - RELEASE_BASE_TIME; uint lockedAmount; for (uint i = 0; i < lockedOwner.length; i++) { if ( lockedance[lockedOwner[i]] > 0) { lockedAmount = lockedance[lockedOwner[i]]; unlock(lockedOwner[i], delta, lockedtype[lockedOwner[i]]); totalCirculating = totalCirculating.add(lockedAmount - lockedance[lockedOwner[i]]); } } return true; } }
47,193
9
// Modifier only contract owner can call method. /
modifier onlyOwner(){ require(msg.sender == owner); _; }
modifier onlyOwner(){ require(msg.sender == owner); _; }
9,502
30
// Stop offering the product/
function deleteProduct(bytes32 productId) public onlyProductOwner(productId) { Product storage p = products[productId]; require(p.state == ProductState.Deployed, "error_notDeployed"); p.state = ProductState.NotDeployed; emit ProductDeleted(p.owner, productId, p.name, p.beneficiary, p.pricePerSecond, p.priceCurrency, p.minimumSubscriptionSeconds); }
function deleteProduct(bytes32 productId) public onlyProductOwner(productId) { Product storage p = products[productId]; require(p.state == ProductState.Deployed, "error_notDeployed"); p.state = ProductState.NotDeployed; emit ProductDeleted(p.owner, productId, p.name, p.beneficiary, p.pricePerSecond, p.priceCurrency, p.minimumSubscriptionSeconds); }
20,788