Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
11
// Dividend Calculating Variables/
uint256 public totalKReceipts; uint256 public payoutsTotal; mapping (address => uint256) paymentsFromAddress; mapping(address => uint256) payoutsToAddress;
uint256 public totalKReceipts; uint256 public payoutsTotal; mapping (address => uint256) paymentsFromAddress; mapping(address => uint256) payoutsToAddress;
29,938
7
// Constructor function Initializes contract /
function OysterShell() public { director = msg.sender; name = "Oyster Shell"; symbol = "SHL"; decimals = 18; directorLock = false; totalSupply = 98592692 * 10 ** uint256(decimals); lockedSupply = 0;
function OysterShell() public { director = msg.sender; name = "Oyster Shell"; symbol = "SHL"; decimals = 18; directorLock = false; totalSupply = 98592692 * 10 ** uint256(decimals); lockedSupply = 0;
60,583
44
// Moves `amount` tokens from the caller's account to `to`. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. /
function transfer(address to, uint256 amount) external returns (bool);
function transfer(address to, uint256 amount) external returns (bool);
13,471
223
// This is invoked once for every pre-ICO address, set pricePerToken/to 0 to disable/preicoAddress PresaleFundCollector address/pricePerToken How many weis one token cost for pre-ico investors
function setPreicoAddress(address preicoAddress, uint pricePerToken) public onlyOwner
function setPreicoAddress(address preicoAddress, uint pricePerToken) public onlyOwner
36,659
19
// divide wei sent into distribution wallets
badgerAmount = (5 * weiAmount)/100; buyoutAmount = (25 * weiAmount)/100; investAmount = (70 * weiAmount)/100;
badgerAmount = (5 * weiAmount)/100; buyoutAmount = (25 * weiAmount)/100; investAmount = (70 * weiAmount)/100;
16,159
52
// Interface of the ERC777TokensRecipient standard as defined in the EIP.
* Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; }
* Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; }
28,004
56
// 19 IN DATA / SET DATA / GET DATA / STRING / PUBLIC / ONLY OWNER / CONSTANT
string inPI_edit_19 = " une première phrase " ;
string inPI_edit_19 = " une première phrase " ;
69,735
52
// decimals of the token
_decimals = 8;
_decimals = 8;
15,795
112
// Decrease the size of the array by one.
array.length--; return true;
array.length--; return true;
15,398
14
// ============ View Functions ============
function getBSWAPPool(address baseToken, address quoteToken) external view returns (address[] memory machines)
function getBSWAPPool(address baseToken, address quoteToken) external view returns (address[] memory machines)
36,556
4
// Calldata version of {processProof} _Available since v4.7._ /
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); }
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); }
7,098
131
// view function to calculate amount of DYP pending to be allocated since `lastDisburseTime`
function getPendingDisbursement() public view returns (uint) { uint timeDiff; uint _now = now; uint _stakingEndTime = contractDeployTime.add(disburseDuration); if (_now > _stakingEndTime) { _now = _stakingEndTime; } if (lastDisburseTime >= _now) { timeDiff = 0; } else { timeDiff = _now.sub(lastDisburseTime); } uint pendingDisburse = disburseAmount .mul(disbursePercentX100) .mul(timeDiff) .div(disburseDuration) .div(10000); return pendingDisburse; }
function getPendingDisbursement() public view returns (uint) { uint timeDiff; uint _now = now; uint _stakingEndTime = contractDeployTime.add(disburseDuration); if (_now > _stakingEndTime) { _now = _stakingEndTime; } if (lastDisburseTime >= _now) { timeDiff = 0; } else { timeDiff = _now.sub(lastDisburseTime); } uint pendingDisburse = disburseAmount .mul(disbursePercentX100) .mul(timeDiff) .div(disburseDuration) .div(10000); return pendingDisburse; }
26,781
41
// Constructor to set the owner, tokenName, decimals and symbol
function Fee( address[] _owners, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public notEmpty(_tokenName) notEmpty(_tokenSymbol)
function Fee( address[] _owners, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public notEmpty(_tokenName) notEmpty(_tokenSymbol)
14
9
// Checks the availability of a token IdReverts if the Id is previously minted, revoked, or burntid The token Id /
function vacant(uint256 id) public view returns (bool) { require(!_exists(id), "tokenId already minted"); require(id >= idFloor, "tokenId below floor"); require(!revokedIds[id], "tokenId revoked or burnt"); return true; }
function vacant(uint256 id) public view returns (bool) { require(!_exists(id), "tokenId already minted"); require(id >= idFloor, "tokenId below floor"); require(!revokedIds[id], "tokenId revoked or burnt"); return true; }
242
588
// Wrappers over Solidity's uintXX casting operators with added overflowchecks. Downcasting from uint256 in Solidity does not revert on overflow. This caneasily result in undesired exploitation or bugs, since developers usuallyassume that overflows raise errors. `SafeCast` restores this intuition byreverting the transaction when such an operation overflows. Using this library instead of the unchecked operations eliminates an entireclass of bugs, so it's recommended to use it always.
* Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } }
* Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } }
34,294
65
// not a current token owner.Check whether they are on the original contract.
if (devcon2Token.isTokenOwner(_owner)) {
if (devcon2Token.isTokenOwner(_owner)) {
33,391
14
// In this context, 'permission to call a function' means 'being a relayer for a function'.
_authenticateCaller();
_authenticateCaller();
31,379
4
// the owner can access all functions
address payable public owner;
address payable public owner;
47,569
151
// unstake needed amount
_withdraw((Math.min(balanceStaked, _amountNeeded - balanceWant)));
_withdraw((Math.min(balanceStaked, _amountNeeded - balanceWant)));
19,889
101
// get index of a token in Curve pool contract /
function getCurveIndex(address token) internal view returns (int128) { // to avoid 'stack too deep' compiler issue return curveIndex[token] - 1; }
function getCurveIndex(address token) internal view returns (int128) { // to avoid 'stack too deep' compiler issue return curveIndex[token] - 1; }
50,447
57
// clone the vault
newVaults[i] = _createVault(_assetId, _maturities[i], _amounts[i], _depositBytes); emit Deposited(msg.sender, _assetId, _amounts[i], _maturities[i]);
newVaults[i] = _createVault(_assetId, _maturities[i], _amounts[i], _depositBytes); emit Deposited(msg.sender, _assetId, _amounts[i], _maturities[i]);
21,649
603
// Registers a new contract. Only authorized contract creators can call this method. parties an array of addresses who become parties in the contract. contractAddress defines the address of the deployed contract. /
function registerContract(address[] calldata parties, address contractAddress) external;
function registerContract(address[] calldata parties, address contractAddress) external;
10,064
31
// 获取用户信息
function getUserInfo(address userAddr) public view returns (address superOne, uint256 first){ return (userInfo[userAddr].superUser, userInfo[userAddr].levelOne.length); }
function getUserInfo(address userAddr) public view returns (address superOne, uint256 first){ return (userInfo[userAddr].superUser, userInfo[userAddr].levelOne.length); }
18,200
83
// // Sets In Token contract address, in case if proxy contract address changes_tokenAddress - New In Token contract address/
function setInToken ( address _tokenAddress ) public onlyOwner
function setInToken ( address _tokenAddress ) public onlyOwner
29,850
1
// useful to know the row count in contracts index
function getContractCount() public returns(uint contractCount)
function getContractCount() public returns(uint contractCount)
8,457
60
// Changes authorised address for generating quote off chain.
function changeAuthQuoteEngine(address _add) external onlyInternal { authQuoteEngine = _add; }
function changeAuthQuoteEngine(address _add) external onlyInternal { authQuoteEngine = _add; }
28,426
61
// getter function for etherRaised
return presaleEtherRaised;
return presaleEtherRaised;
29,777
97
// Collection of functions related to array types. /
library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } }
library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } }
26,648
42
// the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
uint128 currentLiquidityRate;
8,650
776
// Exchanger.settle() ensures synth is active
(, , uint numEntriesSettled) = exchanger().settle(from, currencyKey);
(, , uint numEntriesSettled) = exchanger().settle(from, currencyKey);
34,370
49
// Loop Through harvest group
for (uint256 i = 0; i < subStrategies.length; i++) { address subStrategy = subStrategies[i].subStrategy;
for (uint256 i = 0; i < subStrategies.length; i++) { address subStrategy = subStrategies[i].subStrategy;
7,346
136
// function withdraws stuck tokens on farmfarmAddress - function will operate onfarm with this address _erc20 - address of token that is stuck _amount - how many was deposited _beneficiary - address of userthat deposited by mistake /
function withdrawTokensIfStuckOnSpecificFarm( address farmAddress, address _erc20, uint256 _amount, address _beneficiary ) external onlyTokensFarmCongress
function withdrawTokensIfStuckOnSpecificFarm( address farmAddress, address _erc20, uint256 _amount, address _beneficiary ) external onlyTokensFarmCongress
50,500
41
// initial number of monitors
uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6;
uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6;
55,061
34
// register mints a new Non-Fungible Identity token/only callable by the REGISTRAR_ROLE/to address of the recipient of the token/label a unique label to attach to the token, can pass an empty string to skip labeling/registrationData data to store in the tokenURI/tokenId unique uint256 identifier for the newly created token
function register(address to, string calldata label, string calldata registrationData, uint256 tokenId) external virtual { require(hasRole(REGISTRAR_ROLE, _msgSender()), "NonFungibleRegistry: must have registrar role to register."); _createLabeledToken(to, label, registrationData, tokenId); }
function register(address to, string calldata label, string calldata registrationData, uint256 tokenId) external virtual { require(hasRole(REGISTRAR_ROLE, _msgSender()), "NonFungibleRegistry: must have registrar role to register."); _createLabeledToken(to, label, registrationData, tokenId); }
25,545
117
// Allow refund to investors. Available to the owner of the contract.
function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); }
function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); }
80,378
17
// Return a boolean indicating whether expected and located value match.
return result != expected;
return result != expected;
32,737
4
// Revert with an error if the mint quantity exceeds the max token supply. /
error MintQuantityExceedsMaxSupply(uint256 total, uint256 maxSupply);
error MintQuantityExceedsMaxSupply(uint256 total, uint256 maxSupply);
30,735
10
// sending rewards to the investing, team and marketing contracts
function payfee() public { require(fee_balance > 0); uint val = fee_balance; RNDInvestor rinv = RNDInvestor(inv_contract); rinv.takeEther.value( percent(val, 25) )(); rtm_contract.transfer( percent(val, 74) ); fee_balance = 0; emit PayFee(inv_contract, percent(val, 25) ); emit PayFee(rtm_contract, percent(val, 74) ); }
function payfee() public { require(fee_balance > 0); uint val = fee_balance; RNDInvestor rinv = RNDInvestor(inv_contract); rinv.takeEther.value( percent(val, 25) )(); rtm_contract.transfer( percent(val, 74) ); fee_balance = 0; emit PayFee(inv_contract, percent(val, 25) ); emit PayFee(rtm_contract, percent(val, 74) ); }
45,025
87
// _target {address} of receipt_mintedAmount {uint} amount of tokens to be minted return{bool} true if successful
function mint(address _target, uint256 _mintedAmount) public onlyAuthorized() returns(bool) { assert(totalSupply.add(_mintedAmount) <= 1975e23); // ensure that max amount ever minted should not exceed 197.5 million tokens with 18 decimals balances[_target] = balances[_target].add(_mintedAmount); totalSupply = totalSupply.add(_mintedAmount); Transfer(0, _target, _mintedAmount); return true; }
function mint(address _target, uint256 _mintedAmount) public onlyAuthorized() returns(bool) { assert(totalSupply.add(_mintedAmount) <= 1975e23); // ensure that max amount ever minted should not exceed 197.5 million tokens with 18 decimals balances[_target] = balances[_target].add(_mintedAmount); totalSupply = totalSupply.add(_mintedAmount); Transfer(0, _target, _mintedAmount); return true; }
35,661
232
// Deduct gold.
addressToGoldDeposit[_ownerOfToken] -= requiredGold;
addressToGoldDeposit[_ownerOfToken] -= requiredGold;
2,172
265
// If `beforeOrAtTimestamp` is greater than `_target`, then we keep searching lower. To the left of the current index.
if (!targetAtOrAfter) { rightSide = currentIndex - 1; } else {
if (!targetAtOrAfter) { rightSide = currentIndex - 1; } else {
15,449
9
// Memory: [ A.length ] [ A.data[ : -1] ] [ B.length ][ B.data ] ^ creationCodeA^ creationCodeB
_creationCodeContractB = CodeDeployer.deploy(creationCodeB);
_creationCodeContractB = CodeDeployer.deploy(creationCodeB);
18,001
0
// Initialize manager as _msgSender()
manager = _msgSender(); emit ManagerTransferred(address(0), manager);
manager = _msgSender(); emit ManagerTransferred(address(0), manager);
5,105
122
// Returns the current pendingRegistryAdmin/
function pendingRegistryAdmin() public view returns (address) { return _pendingRegistryAdmin; }
function pendingRegistryAdmin() public view returns (address) { return _pendingRegistryAdmin; }
60,137
252
// Set base token uri for tokens with no extension /
function _setBaseTokenURI(string memory uri) internal { _extensionBaseURI[address(this)] = uri; }
function _setBaseTokenURI(string memory uri) internal { _extensionBaseURI[address(this)] = uri; }
23,705
190
// set new cache
function setCache(address _cacheAddr) public payable virtual returns (bool);
function setCache(address _cacheAddr) public payable virtual returns (bool);
3,849
44
// Send `_value` token to `_to` from `_from` on the condition it is approved by `_from`_from The address of the sender _to The address of the recipient _value The amount of token to be transferredreturn Whether the transfer was successful or not /
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { // Unable to transfer while still locked if (locked) { throw; } // Check if the sender has enough if (balances[_from] < _value) { throw; } // Check for overflows if (balances[_to] + _value < balances[_to]) { throw; } // Check allowance if (_value > allowed[_from][msg.sender]) { throw; } // Transfer tokens balances[_to] += _value; balances[_from] -= _value; // Update allowance allowed[_from][msg.sender] -= _value; // Notify listners Transfer(_from, _to, _value); balancesPerIcoPeriod[_to][getCurrentIcoNumber()] = balances[_to]; balancesPerIcoPeriod[_from][getCurrentIcoNumber()] = balances[_from]; return true; }
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { // Unable to transfer while still locked if (locked) { throw; } // Check if the sender has enough if (balances[_from] < _value) { throw; } // Check for overflows if (balances[_to] + _value < balances[_to]) { throw; } // Check allowance if (_value > allowed[_from][msg.sender]) { throw; } // Transfer tokens balances[_to] += _value; balances[_from] -= _value; // Update allowance allowed[_from][msg.sender] -= _value; // Notify listners Transfer(_from, _to, _value); balancesPerIcoPeriod[_to][getCurrentIcoNumber()] = balances[_to]; balancesPerIcoPeriod[_from][getCurrentIcoNumber()] = balances[_from]; return true; }
19,077
5
// Allows the owner to set a string with their contact information. info The contact information to attach to the contract. /
function setContactInformation(string info) onlyOwner public { contactInformation = info; }
function setContactInformation(string info) onlyOwner public { contactInformation = info; }
42,391
158
// delegate call to an internal function
_stake(msg.sender, _amount, _lockUntil);
_stake(msg.sender, _amount, _lockUntil);
12,268
4
// Set oracle information for the given list of token addresses.
function setOracles(address[] memory tokens, Oracle[] memory info) external onlyGov { require(tokens.length == info.length, 'inconsistent length'); for (uint idx = 0; idx < tokens.length; idx++) { require(info[idx].borrowFactor >= 10000, 'borrow factor must be at least 100%'); require(info[idx].collateralFactor <= 10000, 'collateral factor must be at most 100%'); require(info[idx].liqIncentive >= 10000, 'incentive must be at least 100%'); require(info[idx].liqIncentive <= 20000, 'incentive must be at most 200%'); oracles[tokens[idx]] = info[idx]; emit SetOracle(tokens[idx], info[idx]); } }
function setOracles(address[] memory tokens, Oracle[] memory info) external onlyGov { require(tokens.length == info.length, 'inconsistent length'); for (uint idx = 0; idx < tokens.length; idx++) { require(info[idx].borrowFactor >= 10000, 'borrow factor must be at least 100%'); require(info[idx].collateralFactor <= 10000, 'collateral factor must be at most 100%'); require(info[idx].liqIncentive >= 10000, 'incentive must be at least 100%'); require(info[idx].liqIncentive <= 20000, 'incentive must be at most 200%'); oracles[tokens[idx]] = info[idx]; emit SetOracle(tokens[idx], info[idx]); } }
34,770
61
// Wallets
marketingWallet = address(0x871Dd18307B740475A7f0bF3409272fcc13dD6D2); devWallet = address(0x819aada462b886CA6d9789f7275C3c9bEbDE88a6);
marketingWallet = address(0x871Dd18307B740475A7f0bF3409272fcc13dD6D2); devWallet = address(0x819aada462b886CA6d9789f7275C3c9bEbDE88a6);
10,634
32
// malicious token can reenter here external call to untrusted contract what sort of boundary can we trust
token.createAgreement( _getPoolMemberHash(msgSender, pool),
token.createAgreement( _getPoolMemberHash(msgSender, pool),
10,692
345
// caculate amount of shares available on this schedule if (now - start) < duration sharesLocked = shares - (shares(now - start) / duration) else sharesLocked = 0
uint256 currentSharesLocked = 0; if (timestamp.sub(schedule.start) < schedule.duration) { currentSharesLocked = schedule.shares.sub( schedule.shares.mul(timestamp.sub(schedule.start)).div(schedule.duration) ); }
uint256 currentSharesLocked = 0; if (timestamp.sub(schedule.start) < schedule.duration) { currentSharesLocked = schedule.shares.sub( schedule.shares.mul(timestamp.sub(schedule.start)).div(schedule.duration) ); }
46,049
7
// Returns if user is on the premint allowList
function isAllowListed(bytes memory signature) internal view returns (bool) { bytes32 result = keccak256(abi.encodePacked(msg.sender)); bytes32 hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", result)); return signer.isValidSignatureNow(hash, signature); }
function isAllowListed(bytes memory signature) internal view returns (bool) { bytes32 result = keccak256(abi.encodePacked(msg.sender)); bytes32 hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", result)); return signer.isValidSignatureNow(hash, signature); }
28,115
22
// Honorary mint
function honoraryMint(address to, uint256 quantity) public virtual onlyOwner
function honoraryMint(address to, uint256 quantity) public virtual onlyOwner
46,055
6
// Mapping of current stored asset => underlying Chainlink aggregator
mapping (address => address) public aggregatorsOfAssets; event AggregatorUpdated(address token, address aggregator); uint256 public constant REVISION = 1;
mapping (address => address) public aggregatorsOfAssets; event AggregatorUpdated(address token, address aggregator); uint256 public constant REVISION = 1;
39,113
4
// overridden: Crowdsale.buyTokens(address beneficiary) payable
function buyTokens(address beneficiary) public payable
function buyTokens(address beneficiary) public payable
50,850
301
// Rolls the vault's funds into a new short position. /
function rollToNextOption() external onlyManager nonReentrant { require( block.timestamp >= nextOptionReadyAt, "Cannot roll before delay" ); address newOption = nextOption; require(newOption != address(0), "No found option"); currentOption = newOption; nextOption = address(0); uint256 currentBalance = IERC20(asset).balanceOf(address(this)); uint256 shortAmount = wmul(currentBalance, lockedRatio); lockedAmount = shortAmount; OtokenInterface otoken = OtokenInterface(newOption); ProtocolAdapterTypes.OptionTerms memory optionTerms = ProtocolAdapterTypes.OptionTerms( otoken.underlyingAsset(), USDC, otoken.collateralAsset(), otoken.expiryTimestamp(), otoken.strikePrice().mul(10**10), // scale back to 10**18 isPut ? ProtocolAdapterTypes.OptionType.Put : ProtocolAdapterTypes.OptionType.Call, // isPut address(0) ); uint256 shortBalance = adapter.delegateCreateShort(optionTerms, shortAmount); IERC20 optionToken = IERC20(newOption); optionToken.safeApprove(address(SWAP_CONTRACT), shortBalance); emit OpenShort(newOption, shortAmount, msg.sender); }
function rollToNextOption() external onlyManager nonReentrant { require( block.timestamp >= nextOptionReadyAt, "Cannot roll before delay" ); address newOption = nextOption; require(newOption != address(0), "No found option"); currentOption = newOption; nextOption = address(0); uint256 currentBalance = IERC20(asset).balanceOf(address(this)); uint256 shortAmount = wmul(currentBalance, lockedRatio); lockedAmount = shortAmount; OtokenInterface otoken = OtokenInterface(newOption); ProtocolAdapterTypes.OptionTerms memory optionTerms = ProtocolAdapterTypes.OptionTerms( otoken.underlyingAsset(), USDC, otoken.collateralAsset(), otoken.expiryTimestamp(), otoken.strikePrice().mul(10**10), // scale back to 10**18 isPut ? ProtocolAdapterTypes.OptionType.Put : ProtocolAdapterTypes.OptionType.Call, // isPut address(0) ); uint256 shortBalance = adapter.delegateCreateShort(optionTerms, shortAmount); IERC20 optionToken = IERC20(newOption); optionToken.safeApprove(address(SWAP_CONTRACT), shortBalance); emit OpenShort(newOption, shortAmount, msg.sender); }
63,620
30
// Note: Solidity reverts on underflow, so we decrement here
len -= 1; s.output[s.outcnt++] = s.input[s.incnt++];
len -= 1; s.output[s.outcnt++] = s.input[s.incnt++];
9,217
12
// Allows user to send a bribe with a value specified and a petId of their desired pet.petId the id of the pet, a uint between 0 and 15 inclusive.amount the value attached to the bribe - anything less than 1 ether is refused. return string indicated the bribe was received successfully./
function bribe (uint256 amount, uint petId) public payable returns (string memory){ //A bribe of 1 ether or less is not considered sufficient. require (amount >= 1 ether); require (petId >= 0 && petId <= 15); //only going to have 15 pets or fewer for sale. breeder.transfer(amount); emit bribeEvent(msg.sender, amount, petId); return "Bribe accepted"; }
function bribe (uint256 amount, uint petId) public payable returns (string memory){ //A bribe of 1 ether or less is not considered sufficient. require (amount >= 1 ether); require (petId >= 0 && petId <= 15); //only going to have 15 pets or fewer for sale. breeder.transfer(amount); emit bribeEvent(msg.sender, amount, petId); return "Bribe accepted"; }
39,808
9
// -------- Events -------- / Donation
event event_donationMadeToBank_ThankYou(uint256 donationAmount); event event_getBankDonationsBalance(uint256 donationBalance); event event_bankDonationsWithdrawn(uint256 donationsAmount);
event event_donationMadeToBank_ThankYou(uint256 donationAmount); event event_getBankDonationsBalance(uint256 donationBalance); event event_bankDonationsWithdrawn(uint256 donationsAmount);
26,357
10
// rounds to zero if xy < RAY / 2
function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; }
function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; }
20,047
35
// Mints multiple tokens, one for each of the given list of addresses.Only the edition owner can use this operation and it is intended fo partial giveaways. recipients list of addresses to send the newly minted tokens to /
function mintAndTransfer(address[] memory recipients) external override returns (uint256) { require(_isAllowedToMint(), "Minting not allowed"); if (owner() != msg.sender && !_isPublicAllowed()) { require(allowedMinters[msg.sender] >= recipients.length, "Allowance exceeded"); allowedMinters[msg.sender] = allowedMinters[msg.sender] - uint16(recipients.length); } return _mintEditions(recipients); }
function mintAndTransfer(address[] memory recipients) external override returns (uint256) { require(_isAllowedToMint(), "Minting not allowed"); if (owner() != msg.sender && !_isPublicAllowed()) { require(allowedMinters[msg.sender] >= recipients.length, "Allowance exceeded"); allowedMinters[msg.sender] = allowedMinters[msg.sender] - uint16(recipients.length); } return _mintEditions(recipients); }
40,935
117
// Change Governance of the contract to a new account (`newGovernor`). _newGovernor Address of the new Governor /
function _changeGovernor(address _newGovernor) internal { require(_newGovernor != address(0), "New Governor is address(0)"); emit GovernorshipTransferred(_governor(), _newGovernor); _setGovernor(_newGovernor); }
function _changeGovernor(address _newGovernor) internal { require(_newGovernor != address(0), "New Governor is address(0)"); emit GovernorshipTransferred(_governor(), _newGovernor); _setGovernor(_newGovernor); }
37,242
0
// BProtocol contracts
interface IScoringConfig { function getUserScore(address user, address token) external view returns (uint256); function getGlobalScore(address token) external view returns (uint256); }
interface IScoringConfig { function getUserScore(address user, address token) external view returns (uint256); function getGlobalScore(address token) external view returns (uint256); }
13,388
26
// Prop contract implements all elements related to ERC721 NFT Property alias Prop Royalties: Only some addresses are allowed to transfer these tokens. Token owner can't resell is token outside an authorized Marketplace as OpenSea or our future Marketplace. Jerome Caporossi, Stéphane Chaunard, Alexandre Gautier /
contract PropContract is ERC721Enumerable, AccessControl, Ownable, IERC2981 { /// @dev structure used to store property's attribute struct Property { // edition number uint16 edition; // id of the cell of board uint8 land; // rarity level (as a power of 10, i.e rarity = 1 means 10^1 = 10 versions) uint8 rarity; // serial number uint32 serial; } bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; BoardContract private immutable Board; mapping(uint256 => Property) private props; /// @dev Number of minted properties for each (edition, land, rarity) tuple mapping(uint16 => mapping(uint8 => mapping(uint8 => uint16))) numOfProps; /// @dev store all allowed operators to sell NFT Prop and to redistribute royalties mapping(address => bool) public isOperatorAllowed; mapping(uint256 => uint96) private royaltiesValuesByTokenId; string private baseTokenURI; uint96 public defaultRoyaltyPercentageBasisPoints = 500; // 5% /** Event emitted when the royalty percentage is set * @param tokenId Prop token ID * @param royaltyPercentageBasisPoints percentage*/ event RoyaltySet(uint256 tokenId, uint256 royaltyPercentageBasisPoints); /** @dev Constructor * @param BoardAddress address * @param _name name * @param _symbol symbol * @param _baseTokenURI base token uri * @dev ADMIN_ROLE, MINTER_ROLE are given to deployer*/ constructor( address BoardAddress, string memory _name, string memory _symbol, string memory _baseTokenURI ) ERC721(_name, _symbol) { baseTokenURI = _baseTokenURI; _setupRole(ADMIN_ROLE, msg.sender); _setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE); _setupRole(MINTER_ROLE, msg.sender); _setRoleAdmin(MINTER_ROLE, ADMIN_ROLE); Board = BoardContract(BoardAddress); } /** Retrieve validity of a Prop * @param edition board edition * @param land land id * @param rarity rarity * @return bool value*/ function isValidProp( uint16 edition, uint8 land, uint8 rarity ) public view returns (bool) { return (edition <= Board.getMaxEdition()) && (land <= Board.getNbLands(edition)) && (Board.isPurchasable(edition, land)) && (rarity <= Board.getRarityLevel(edition)); } /** @dev get contract's baseURI * @return string value*/ function _baseURI() internal view override returns (string memory) { return baseTokenURI; } /** get token URI relative to a Prop * @param _id Prop ID * @return string value*/ function tokenURI(uint256 _id) public view override returns (string memory) { string memory uri = super.tokenURI(_id); string memory ext = ".json"; return string(abi.encodePacked(uri, ext)); } /** Mint NFT token and set royalties default value * @notice #### requirements :<br /> * @notice - Property must be valid * @param _to buyer address * @param _edition board edition * @param _land land id * @param _rarity rarity*/ function mint( address _to, uint16 _edition, uint8 _land, uint8 _rarity ) external onlyRole(MINTER_ROLE) returns (uint256 id_) { require(isValidProp(_edition, _land, _rarity), "PROP cannot be minted"); id_ = generateID(_edition, _land, _rarity); _safeMint(_to, id_); _setRoyalties(id_); } /** get property struct for a Prop * @param _id Prop ID * @return p_ property struct*/ function get(uint256 _id) public view returns (Property memory p_) { require(exists(_id), "This property does not exist"); p_ = props[_id]; } /** get existence of a Prop i.e if Prop has been minted or not. * @param _id Prop ID * @return bool*/ function exists(uint256 _id) public view returns (bool) { return ( (props[_id].land == 0) && (props[_id].edition == 0) && (props[_id].rarity == 0) && (props[_id].serial == 0) ? false : true ); } /** get number of Props by * @param _edition board edition * @param _land land id * @param _rarity rarity * @return amount_ quantity*/ function getNbOfProps( uint16 _edition, uint8 _land, uint8 _rarity ) public view returns (uint32 amount_) { require(isValidProp(_edition, _land, _rarity), "PROP does not exist"); return numOfProps[_edition][_land][_rarity]; } /** is contract support interface * @param _interfaceId interface ID * @return bool*/ function supportsInterface(bytes4 _interfaceId) public view override(ERC721Enumerable, AccessControl, IERC165) returns (bool) { if (_interfaceId == _INTERFACE_ID_ERC2981) { return true; } return super.supportsInterface(_interfaceId); } /** @dev generate an ID for a Prop * @param _edition board edition * @param _land land id * @param _rarity rarity * @return id_ the Prop ID*/ function generateID( uint16 _edition, uint8 _land, uint8 _rarity ) internal returns (uint256 id_) { uint32 serial = numOfProps[_edition][_land][_rarity]; require(serial < 10**_rarity, "all properties already minted"); numOfProps[_edition][_land][_rarity] += 1; id_ = uint256(keccak256(abi.encode(_edition, _land, _rarity, serial))); props[id_] = Property(_edition, _land, _rarity, serial); } /** Set default royalties percentage basis point. Can be only made by admin role. * @param _percentageBasisPoints royalties percentage basis point i.e. 500 = 5%*/ function setDefaultRoyaltyPercentageBasisPoints(uint96 _percentageBasisPoints) public onlyRole(ADMIN_ROLE) { defaultRoyaltyPercentageBasisPoints = _percentageBasisPoints; } /** Set royalties for a NFT token id at percentage basis point. Can be only made by admin role. * @param _tokenId NFT token id * @param _percentageBasisPoints royalties percentage basis point i.e. 500 = 5%*/ function setRoyalties(uint256 _tokenId, uint96 _percentageBasisPoints) public onlyRole(ADMIN_ROLE) { _setRoyalties(_tokenId, _percentageBasisPoints); } /** @dev Set royalties for a NFT token id at default percentage basis point. * @dev default value should be set with this.setDefaultRoyaltyPercentageBasisPoints() * @param _tokenId NFT token id * @dev See this._setRoyalties(uint256 _tokenId, uint96 _percentageBasisPoints)*/ function _setRoyalties(uint256 _tokenId) internal { _setRoyalties(_tokenId, defaultRoyaltyPercentageBasisPoints); } /** Set royalties for a NFT token id at a percentage basis point. Assuming that royalties receiver is contract's owner * @param _tokenId NFT token id * @param _percentageBasisPoints royalties percentage basis point i.e. 500 = 5%*/ function _setRoyalties(uint256 _tokenId, uint96 _percentageBasisPoints) internal { require(_percentageBasisPoints < 10000, "Royalty value should be < 10000"); royaltiesValuesByTokenId[_tokenId] = _percentageBasisPoints; emit RoyaltySet(_tokenId, _percentageBasisPoints); } /** Return royalties information as describe at EIP-2981: NFT Royalty Standard * @notice Return nul address and value if there is no royalty to pay. * @param _tokenId NFT token id * @param _salePrice sale price * @return receiver royalty receiver address * @return royaltyAmount royalty amount to pay to receiver * @dev Override isApprovedForAll to auto-approve confident operator contracts * See {ERC721-isApprovedForAll} * See https://docs.opensea.io/docs/polygon-basic-integration#overriding-isapprovedforall-to-reduce-trading-friction * @inheritdoc IERC2981*/ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { uint96 royaltyValue = royaltiesValuesByTokenId[_tokenId]; if (royaltyValue > 0) { return (this.owner(), (_salePrice * royaltyValue) / 10000); } return (address(0), 0); } /** Return true only for allowed operators, see: isOperatorAllowed * @param _owner owner address * @param _operator operator address * @return bool*/ function isApprovedForAll(address _owner, address _operator) public view override returns (bool) { if (isOperatorAllowed[_operator]) { return true; } // silent warning _owner; return false; } /** Admin role can allowed un operator * @param _address operator address * @param value true / false*/ function setIsOperatorAllowed(address _address, bool value) external onlyRole(ADMIN_ROLE) { isOperatorAllowed[_address] = value; } /** @dev Override _isApprovedOrOwner to limit approval to confident operators only. * @dev See {IERC721-_isApprovedOrOwner}.*/ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view override returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return isApprovedForAll(owner, spender); // limit allowed operator as spender } }
contract PropContract is ERC721Enumerable, AccessControl, Ownable, IERC2981 { /// @dev structure used to store property's attribute struct Property { // edition number uint16 edition; // id of the cell of board uint8 land; // rarity level (as a power of 10, i.e rarity = 1 means 10^1 = 10 versions) uint8 rarity; // serial number uint32 serial; } bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; BoardContract private immutable Board; mapping(uint256 => Property) private props; /// @dev Number of minted properties for each (edition, land, rarity) tuple mapping(uint16 => mapping(uint8 => mapping(uint8 => uint16))) numOfProps; /// @dev store all allowed operators to sell NFT Prop and to redistribute royalties mapping(address => bool) public isOperatorAllowed; mapping(uint256 => uint96) private royaltiesValuesByTokenId; string private baseTokenURI; uint96 public defaultRoyaltyPercentageBasisPoints = 500; // 5% /** Event emitted when the royalty percentage is set * @param tokenId Prop token ID * @param royaltyPercentageBasisPoints percentage*/ event RoyaltySet(uint256 tokenId, uint256 royaltyPercentageBasisPoints); /** @dev Constructor * @param BoardAddress address * @param _name name * @param _symbol symbol * @param _baseTokenURI base token uri * @dev ADMIN_ROLE, MINTER_ROLE are given to deployer*/ constructor( address BoardAddress, string memory _name, string memory _symbol, string memory _baseTokenURI ) ERC721(_name, _symbol) { baseTokenURI = _baseTokenURI; _setupRole(ADMIN_ROLE, msg.sender); _setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE); _setupRole(MINTER_ROLE, msg.sender); _setRoleAdmin(MINTER_ROLE, ADMIN_ROLE); Board = BoardContract(BoardAddress); } /** Retrieve validity of a Prop * @param edition board edition * @param land land id * @param rarity rarity * @return bool value*/ function isValidProp( uint16 edition, uint8 land, uint8 rarity ) public view returns (bool) { return (edition <= Board.getMaxEdition()) && (land <= Board.getNbLands(edition)) && (Board.isPurchasable(edition, land)) && (rarity <= Board.getRarityLevel(edition)); } /** @dev get contract's baseURI * @return string value*/ function _baseURI() internal view override returns (string memory) { return baseTokenURI; } /** get token URI relative to a Prop * @param _id Prop ID * @return string value*/ function tokenURI(uint256 _id) public view override returns (string memory) { string memory uri = super.tokenURI(_id); string memory ext = ".json"; return string(abi.encodePacked(uri, ext)); } /** Mint NFT token and set royalties default value * @notice #### requirements :<br /> * @notice - Property must be valid * @param _to buyer address * @param _edition board edition * @param _land land id * @param _rarity rarity*/ function mint( address _to, uint16 _edition, uint8 _land, uint8 _rarity ) external onlyRole(MINTER_ROLE) returns (uint256 id_) { require(isValidProp(_edition, _land, _rarity), "PROP cannot be minted"); id_ = generateID(_edition, _land, _rarity); _safeMint(_to, id_); _setRoyalties(id_); } /** get property struct for a Prop * @param _id Prop ID * @return p_ property struct*/ function get(uint256 _id) public view returns (Property memory p_) { require(exists(_id), "This property does not exist"); p_ = props[_id]; } /** get existence of a Prop i.e if Prop has been minted or not. * @param _id Prop ID * @return bool*/ function exists(uint256 _id) public view returns (bool) { return ( (props[_id].land == 0) && (props[_id].edition == 0) && (props[_id].rarity == 0) && (props[_id].serial == 0) ? false : true ); } /** get number of Props by * @param _edition board edition * @param _land land id * @param _rarity rarity * @return amount_ quantity*/ function getNbOfProps( uint16 _edition, uint8 _land, uint8 _rarity ) public view returns (uint32 amount_) { require(isValidProp(_edition, _land, _rarity), "PROP does not exist"); return numOfProps[_edition][_land][_rarity]; } /** is contract support interface * @param _interfaceId interface ID * @return bool*/ function supportsInterface(bytes4 _interfaceId) public view override(ERC721Enumerable, AccessControl, IERC165) returns (bool) { if (_interfaceId == _INTERFACE_ID_ERC2981) { return true; } return super.supportsInterface(_interfaceId); } /** @dev generate an ID for a Prop * @param _edition board edition * @param _land land id * @param _rarity rarity * @return id_ the Prop ID*/ function generateID( uint16 _edition, uint8 _land, uint8 _rarity ) internal returns (uint256 id_) { uint32 serial = numOfProps[_edition][_land][_rarity]; require(serial < 10**_rarity, "all properties already minted"); numOfProps[_edition][_land][_rarity] += 1; id_ = uint256(keccak256(abi.encode(_edition, _land, _rarity, serial))); props[id_] = Property(_edition, _land, _rarity, serial); } /** Set default royalties percentage basis point. Can be only made by admin role. * @param _percentageBasisPoints royalties percentage basis point i.e. 500 = 5%*/ function setDefaultRoyaltyPercentageBasisPoints(uint96 _percentageBasisPoints) public onlyRole(ADMIN_ROLE) { defaultRoyaltyPercentageBasisPoints = _percentageBasisPoints; } /** Set royalties for a NFT token id at percentage basis point. Can be only made by admin role. * @param _tokenId NFT token id * @param _percentageBasisPoints royalties percentage basis point i.e. 500 = 5%*/ function setRoyalties(uint256 _tokenId, uint96 _percentageBasisPoints) public onlyRole(ADMIN_ROLE) { _setRoyalties(_tokenId, _percentageBasisPoints); } /** @dev Set royalties for a NFT token id at default percentage basis point. * @dev default value should be set with this.setDefaultRoyaltyPercentageBasisPoints() * @param _tokenId NFT token id * @dev See this._setRoyalties(uint256 _tokenId, uint96 _percentageBasisPoints)*/ function _setRoyalties(uint256 _tokenId) internal { _setRoyalties(_tokenId, defaultRoyaltyPercentageBasisPoints); } /** Set royalties for a NFT token id at a percentage basis point. Assuming that royalties receiver is contract's owner * @param _tokenId NFT token id * @param _percentageBasisPoints royalties percentage basis point i.e. 500 = 5%*/ function _setRoyalties(uint256 _tokenId, uint96 _percentageBasisPoints) internal { require(_percentageBasisPoints < 10000, "Royalty value should be < 10000"); royaltiesValuesByTokenId[_tokenId] = _percentageBasisPoints; emit RoyaltySet(_tokenId, _percentageBasisPoints); } /** Return royalties information as describe at EIP-2981: NFT Royalty Standard * @notice Return nul address and value if there is no royalty to pay. * @param _tokenId NFT token id * @param _salePrice sale price * @return receiver royalty receiver address * @return royaltyAmount royalty amount to pay to receiver * @dev Override isApprovedForAll to auto-approve confident operator contracts * See {ERC721-isApprovedForAll} * See https://docs.opensea.io/docs/polygon-basic-integration#overriding-isapprovedforall-to-reduce-trading-friction * @inheritdoc IERC2981*/ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { uint96 royaltyValue = royaltiesValuesByTokenId[_tokenId]; if (royaltyValue > 0) { return (this.owner(), (_salePrice * royaltyValue) / 10000); } return (address(0), 0); } /** Return true only for allowed operators, see: isOperatorAllowed * @param _owner owner address * @param _operator operator address * @return bool*/ function isApprovedForAll(address _owner, address _operator) public view override returns (bool) { if (isOperatorAllowed[_operator]) { return true; } // silent warning _owner; return false; } /** Admin role can allowed un operator * @param _address operator address * @param value true / false*/ function setIsOperatorAllowed(address _address, bool value) external onlyRole(ADMIN_ROLE) { isOperatorAllowed[_address] = value; } /** @dev Override _isApprovedOrOwner to limit approval to confident operators only. * @dev See {IERC721-_isApprovedOrOwner}.*/ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view override returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return isApprovedForAll(owner, spender); // limit allowed operator as spender } }
17,413
7
// return The address of the implementation. /
function implementation() external ifAdmin returns (address) { return _implementation(); }
function implementation() external ifAdmin returns (address) { return _implementation(); }
1,952
97
// Transfer `_value` tokens from `_from` to `_to` if `msg.sender` is allowed./Restriction: An account can only use this function to send to itself/Allows for an approved third party to transfer tokens from one/ address to another. Returns success./_from Address from where tokens are withdrawn./_to Address to where tokens are sent./_value Number of tokens to transfer./ return Returns success of function call.
function transferFrom(address _from, address _to, uint _value) public returns (bool)
function transferFrom(address _from, address _to, uint _value) public returns (bool)
24,997
13
// New admin event
event AdminChanged(address indexed oldAdmin, address indexed newAdmin);
event AdminChanged(address indexed oldAdmin, address indexed newAdmin);
43,702
5
// Function that sets minting active or inactive/only callable from the contract owner
function toggleMintActive() external onlyOwner { isMintActive = !isMintActive; }
function toggleMintActive() external onlyOwner { isMintActive = !isMintActive; }
39,436
194
// Calculate the dy of withdrawing in one token self Swap struct to read from tokenIndex which token will be withdrawn tokenAmount the amount to withdraw in the pools precisionreturn the d and the new y after withdrawing one token /
function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount
function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount
19,616
11
// HOLDER SETTERS[.√.] sets: email for a given `_tokenId`
function setEmail(uint _tokenId, string memory _email) public onlyHolder(_tokenId) { // checks: tokenId exists // require(_exists(_tokenId), 'URI query for non-existent token.'); // gets: `tokenInfo` from claim by tokenId // Holders storage token = holderInfo[_tokenId]; // sets: `email` to _email // token.email = _email; }
function setEmail(uint _tokenId, string memory _email) public onlyHolder(_tokenId) { // checks: tokenId exists // require(_exists(_tokenId), 'URI query for non-existent token.'); // gets: `tokenInfo` from claim by tokenId // Holders storage token = holderInfo[_tokenId]; // sets: `email` to _email // token.email = _email; }
22,355
40
// verify that the new contract-registry is pointing to a non-zero contract-registry
require(newRegistry.addressOf(CONTRACT_REGISTRY) != address(0), "ERR_INVALID_REGISTRY");
require(newRegistry.addressOf(CONTRACT_REGISTRY) != address(0), "ERR_INVALID_REGISTRY");
18,284
101
// Transfers the token into the market to repay.
uint256 _actualRepayAmount = _doTransferIn( _payer, _repayAmount > _accountBorrows ? _accountBorrows : _repayAmount );
uint256 _actualRepayAmount = _doTransferIn( _payer, _repayAmount > _accountBorrows ? _accountBorrows : _repayAmount );
71,430
26
// External //Starts accruing UBI for a registered submission. _human The submission ID./
function startAccruing(address _human) external { require(proofOfHumanity.isRegistered(_human), "The submission is not registered in Proof Of Humanity."); require(accruedSince[_human] == 0, "The submission is already accruing UBI."); accruedSince[_human] = block.timestamp; }
function startAccruing(address _human) external { require(proofOfHumanity.isRegistered(_human), "The submission is not registered in Proof Of Humanity."); require(accruedSince[_human] == 0, "The submission is already accruing UBI."); accruedSince[_human] = block.timestamp; }
41,848
99
// Router Information
mapping (address => bool) public isMarketPair; IUniswapV2Router02 public uniswapV2Router; address public uniswapPair;
mapping (address => bool) public isMarketPair; IUniswapV2Router02 public uniswapV2Router; address public uniswapPair;
23,082
8
// never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
8,356
297
// Validates a stable borrow rate rebalance action reserve The reserve state on which the user is getting rebalanced reserveAddress The address of the reserve stableDebtToken The stable debt token instance variableDebtToken The variable debt token instance aTokenAddress The address of the aToken contract /
function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, address reserveAddress, IERC20 stableDebtToken, IERC20 variableDebtToken, address aTokenAddress
function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, address reserveAddress, IERC20 stableDebtToken, IERC20 variableDebtToken, address aTokenAddress
39,883
9
// new offer should be created
uint256 id = _createLimitOffer( _sellToken, remainingSellAmount_, _buyToken, remainingBuyAmount_, _feeSchedule, _notify, _notifyData );
uint256 id = _createLimitOffer( _sellToken, remainingSellAmount_, _buyToken, remainingBuyAmount_, _feeSchedule, _notify, _notifyData );
15,239
140
// overrides transfer function to meet tokenomics of SOLAR
function _transfer(address sender, address recipient, uint256 amount) internal virtual override antiWhale(sender, recipient, amount) { // swap and liquify if ( swapAndLiquifyEnabled == true && _inSwapAndLiquify == false && address(solarSwapRouter) != address(0) && solarSwapPair != address(0) && sender != solarSwapPair && sender != owner() && _excludedFromAntiWhale[sender]==false && _excludedFromAntiWhale[recipient]==false ) { swapAndLiquify(); } if (recipient == BURN_ADDRESS || transferTaxRate == 0 || _excludedFromAntiWhale[sender] || _excludedFromAntiWhale[recipient]) { super._transfer(sender, recipient, amount); } else { // default tax is 9% of every transfer uint256 taxAmount = amount.mul(transferTaxRate).div(10000); uint256 burnAmount = taxAmount.mul(burnRate).div(100); uint256 liquidityAmount = taxAmount.sub(burnAmount); require(taxAmount == burnAmount + liquidityAmount, "SOLAR::transfer: Burn value invalid"); // default 91% of transfer sent to recipient uint256 sendAmount = amount.sub(taxAmount); require(amount == sendAmount + taxAmount, "SOLAR::transfer: Tax value invalid"); super._transfer(sender, BURN_ADDRESS, burnAmount); super._transfer(sender, address(this), liquidityAmount); super._transfer(sender, recipient, sendAmount); amount = sendAmount; } }
function _transfer(address sender, address recipient, uint256 amount) internal virtual override antiWhale(sender, recipient, amount) { // swap and liquify if ( swapAndLiquifyEnabled == true && _inSwapAndLiquify == false && address(solarSwapRouter) != address(0) && solarSwapPair != address(0) && sender != solarSwapPair && sender != owner() && _excludedFromAntiWhale[sender]==false && _excludedFromAntiWhale[recipient]==false ) { swapAndLiquify(); } if (recipient == BURN_ADDRESS || transferTaxRate == 0 || _excludedFromAntiWhale[sender] || _excludedFromAntiWhale[recipient]) { super._transfer(sender, recipient, amount); } else { // default tax is 9% of every transfer uint256 taxAmount = amount.mul(transferTaxRate).div(10000); uint256 burnAmount = taxAmount.mul(burnRate).div(100); uint256 liquidityAmount = taxAmount.sub(burnAmount); require(taxAmount == burnAmount + liquidityAmount, "SOLAR::transfer: Burn value invalid"); // default 91% of transfer sent to recipient uint256 sendAmount = amount.sub(taxAmount); require(amount == sendAmount + taxAmount, "SOLAR::transfer: Tax value invalid"); super._transfer(sender, BURN_ADDRESS, burnAmount); super._transfer(sender, address(this), liquidityAmount); super._transfer(sender, recipient, sendAmount); amount = sendAmount; } }
22,791
79
// Not found
self._len = 0;
self._len = 0;
1,795
16
// SafeMintPlease Refer FAQ in the APPif Aggregated It uses MATIC Else It uses ERC20 TOKEN like USDT /
function safeMint(string memory dna, uint8 lvl) public payable virtual { //Don't send Ether when it's not Aggredated with Matic Price. Storage storage s = getStorage(); //Fetch Token Info require( lvl <= getSettings().max_expansion && lvl >= 0, "Expansion Level Invalid" ); require(_exists(s.tokenId[dna]), NOT_FOUND); uint256 iToken = s.tokenId[dna]; //Ref DNA Token ID uint256 price = getPrice(lvl); //Get Price if (isAggregated()) require(msg.value == price, PAY_NOT_MATCH); //Price Check else require(msg.value == 0, "Use App to Pay."); require(msg.sender != _ownerOf(iToken), NOT_ALLOWED); //Same Account Purchase Not Allowed require( s.info[iToken].keys != getMatrix() + s.info[iToken].expand_level, "Already Unlocked" ); //Matrix Limit require(s.info[iToken].expiry > block.timestamp, "Time LimitExpired"); //Expiry Check IERC20 currency = getERC20(); uint256 amount = (isAggregated()) ? msg.value : price; //Payment Type Check if (!isAggregated()) { require( currency.allowance(msg.sender, address(this)) >= msg.value, NO_ALLOWANCE ); require(currency.balanceOf(msg.sender) >= price, NO_BALANCE); currency.transferFrom(msg.sender, address(this), price); } uint256 new_token = getCounter(); _counterUp(); //Set to new Counter address[] memory addr = s.chain_addr[iToken]; string memory _dna = string( abi.encodePacked(randomString(7), "-", uint2str(new_token)) ); s.info[new_token] = NFT({ dna: _dna, creator: addr[getMatrix() - 1], //Set Permanent Royalty as Inviter keys: 0, lock: true, expiry: block.timestamp + getOffset(), imageUri: getPicsumUri(dna), admired: 0, can_admire_after: block.timestamp + 86400, taskId: 0, expand_level: lvl }); //Copy Chain Array order for matrix update. uint8 ilvl = s.info[iToken].expand_level; s.chain_addr[new_token] = s.chain_addr[iToken]; s.root_tokenId[new_token] = s.root_tokenId[iToken]; //Adjust chain for New token if (ilvl > 0) { for (uint8 i = 0; i < ilvl; i++) { if (s.chain_addr[new_token].length > getMatrix()) s.chain_addr[new_token].pop(); s.root_tokenId[new_token].pop(); } } s.tokenId[_dna] = new_token; //Set dna token id emit NewMint(msg.sender, new_token, iToken, dna); //Update Matrix updateMatrix(new_token, s.tokenId[dna]); //Estimate Royalty & Split in half uint256 royalty = getPercentOf(getCommonRate(), amount, getDecimals()) / 2; uint256 keys_creator_royalty = getPercentOf( getPermaRate(), amount, getDecimals() ); //Selects Root & creator from inviter's metadata address[] memory root = s.chain_addr[iToken]; if (isAggregated()) { //Pay the Royalty payable(root[0]).transfer(royalty); //Selects from Inviter's Metadata payable(s.info[iToken].creator).transfer(keys_creator_royalty); } else { //Pay the Royalty currency.transfer(root[0], royalty); //Pay Permanent Creator Royalty which selects creator from Inviter's Metadata currency.transfer(s.info[iToken].creator, keys_creator_royalty); } //Add 50% to Pending uint256[] memory rootToken = s.root_tokenId[iToken]; uint256 token = rootToken[getMatrix() - 1]; //Update Pending Balance s.token_balance[address(currency)][token] += royalty; s.info[iToken].keys += 1; if (s.info[iToken].keys == getMatrix()) s.info[iToken].lock = false; //Update Contract Balance _updateContractBalance( getPercentOf( 100 - (uint256((getCommonRate() / 2) + getPermaRate())), amount, getDecimals() ) ); //Finally Mint Token _safeMint(msg.sender, new_token); }
function safeMint(string memory dna, uint8 lvl) public payable virtual { //Don't send Ether when it's not Aggredated with Matic Price. Storage storage s = getStorage(); //Fetch Token Info require( lvl <= getSettings().max_expansion && lvl >= 0, "Expansion Level Invalid" ); require(_exists(s.tokenId[dna]), NOT_FOUND); uint256 iToken = s.tokenId[dna]; //Ref DNA Token ID uint256 price = getPrice(lvl); //Get Price if (isAggregated()) require(msg.value == price, PAY_NOT_MATCH); //Price Check else require(msg.value == 0, "Use App to Pay."); require(msg.sender != _ownerOf(iToken), NOT_ALLOWED); //Same Account Purchase Not Allowed require( s.info[iToken].keys != getMatrix() + s.info[iToken].expand_level, "Already Unlocked" ); //Matrix Limit require(s.info[iToken].expiry > block.timestamp, "Time LimitExpired"); //Expiry Check IERC20 currency = getERC20(); uint256 amount = (isAggregated()) ? msg.value : price; //Payment Type Check if (!isAggregated()) { require( currency.allowance(msg.sender, address(this)) >= msg.value, NO_ALLOWANCE ); require(currency.balanceOf(msg.sender) >= price, NO_BALANCE); currency.transferFrom(msg.sender, address(this), price); } uint256 new_token = getCounter(); _counterUp(); //Set to new Counter address[] memory addr = s.chain_addr[iToken]; string memory _dna = string( abi.encodePacked(randomString(7), "-", uint2str(new_token)) ); s.info[new_token] = NFT({ dna: _dna, creator: addr[getMatrix() - 1], //Set Permanent Royalty as Inviter keys: 0, lock: true, expiry: block.timestamp + getOffset(), imageUri: getPicsumUri(dna), admired: 0, can_admire_after: block.timestamp + 86400, taskId: 0, expand_level: lvl }); //Copy Chain Array order for matrix update. uint8 ilvl = s.info[iToken].expand_level; s.chain_addr[new_token] = s.chain_addr[iToken]; s.root_tokenId[new_token] = s.root_tokenId[iToken]; //Adjust chain for New token if (ilvl > 0) { for (uint8 i = 0; i < ilvl; i++) { if (s.chain_addr[new_token].length > getMatrix()) s.chain_addr[new_token].pop(); s.root_tokenId[new_token].pop(); } } s.tokenId[_dna] = new_token; //Set dna token id emit NewMint(msg.sender, new_token, iToken, dna); //Update Matrix updateMatrix(new_token, s.tokenId[dna]); //Estimate Royalty & Split in half uint256 royalty = getPercentOf(getCommonRate(), amount, getDecimals()) / 2; uint256 keys_creator_royalty = getPercentOf( getPermaRate(), amount, getDecimals() ); //Selects Root & creator from inviter's metadata address[] memory root = s.chain_addr[iToken]; if (isAggregated()) { //Pay the Royalty payable(root[0]).transfer(royalty); //Selects from Inviter's Metadata payable(s.info[iToken].creator).transfer(keys_creator_royalty); } else { //Pay the Royalty currency.transfer(root[0], royalty); //Pay Permanent Creator Royalty which selects creator from Inviter's Metadata currency.transfer(s.info[iToken].creator, keys_creator_royalty); } //Add 50% to Pending uint256[] memory rootToken = s.root_tokenId[iToken]; uint256 token = rootToken[getMatrix() - 1]; //Update Pending Balance s.token_balance[address(currency)][token] += royalty; s.info[iToken].keys += 1; if (s.info[iToken].keys == getMatrix()) s.info[iToken].lock = false; //Update Contract Balance _updateContractBalance( getPercentOf( 100 - (uint256((getCommonRate() / 2) + getPermaRate())), amount, getDecimals() ) ); //Finally Mint Token _safeMint(msg.sender, new_token); }
1,218
555
// import {IERC20} from "openzeppelin-contracts/token/ERC20/IERC20.sol"; // import {SafeERC20} from "openzeppelin-contracts/token/ERC20/utils/SafeERC20.sol"; // import {YAMGovernanceToken} from "./YAMGovernanceToken.sol"; / Modifiers
modifier onlyGov() { require(msg.sender == gov); _; }
modifier onlyGov() { require(msg.sender == gov); _; }
7,985
23
// Utilized to toggle whether contract should be stopped return result tru or false depending on wheter the contract is active or not
function toggleContractActive() onlyAdmin public returns (bool result) { stopped = !stopped; return stopped; }
function toggleContractActive() onlyAdmin public returns (bool result) { stopped = !stopped; return stopped; }
4,021
120
// Send Based Gold to the owner of the token ID
_mint(tokenOwner, BasedGoldPerTokenId);
_mint(tokenOwner, BasedGoldPerTokenId);
3,578
47
// Global accounting state
uint256 public totalLockedShares = 0; uint256 public totalStakingShares = 0; uint256 private _totalStakingShareSeconds = 0; uint256 private _lastAccountingTimestampSec = now; uint256 private _maxUnlockSchedules = 0; uint256 private _initialSharesPerToken = 0; mapping(address => bool) public whitelistedSenders; address public SwingyToken;
uint256 public totalLockedShares = 0; uint256 public totalStakingShares = 0; uint256 private _totalStakingShareSeconds = 0; uint256 private _lastAccountingTimestampSec = now; uint256 private _maxUnlockSchedules = 0; uint256 private _initialSharesPerToken = 0; mapping(address => bool) public whitelistedSenders; address public SwingyToken;
12,458
172
// return true and 0 if now is pay day, false if now is not pay day and the time until next pay day Pay Day is the first day of each month, starting from the second month. After program ends, every day is Pay Day. /
function isPayDay() public view returns (bool, uint256)
function isPayDay() public view returns (bool, uint256)
79,601
59
// Interface for Curve.Fi CRV staking Gauge contract. See original implementation in official repository: /
interface ICurveFi_Gauge { function lp_token() external view returns(address); function crv_token() external view returns(address); function balanceOf(address addr) external view returns (uint256); function deposit(uint256 _value) external; function withdraw(uint256 _value) external; function claimable_tokens(address addr) external returns (uint256); function minter() external view returns(address); //use minter().mint(gauge_addr) to claim CRV function integrate_fraction(address _for) external view returns(uint256); function user_checkpoint(address _for) external returns(bool); }
interface ICurveFi_Gauge { function lp_token() external view returns(address); function crv_token() external view returns(address); function balanceOf(address addr) external view returns (uint256); function deposit(uint256 _value) external; function withdraw(uint256 _value) external; function claimable_tokens(address addr) external returns (uint256); function minter() external view returns(address); //use minter().mint(gauge_addr) to claim CRV function integrate_fraction(address _for) external view returns(uint256); function user_checkpoint(address _for) external returns(bool); }
66,269
55
// PauserRole Contract/Only administrators can update the pauser roles/Keeps track of pausers and can check if an account is authorized
contract PauserRole is OwnerRole { event PauserAdded(address indexed addedPauser, address indexed addedBy); event PauserRemoved( address indexed removedPauser, address indexed removedBy ); Role private _pausers; /// @dev Modifier to make a function callable only when the caller is a pauser modifier onlyPauser() { require( isPauser(msg.sender), "PauserRole: caller does not have the Pauser role" ); _; } /// @dev Public function returns `true` if `account` has been granted a pauser role function isPauser(address account) public view returns (bool) { return _has(_pausers, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a pauser /// @param account The address that is guaranteed pauser authorization function _addPauser(address account) internal { _add(_pausers, account); emit PauserAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a pauser /// @param account The address removed as a pauser function _removePauser(address account) internal { _remove(_pausers, account); emit PauserRemoved(account, msg.sender); } /// @dev Public function that adds an address as a pauser /// @param account The address that is guaranteed pauser authorization function addPauser(address account) external onlyOwner { _addPauser(account); } /// @dev Public function that removes an account from being a pauser /// @param account The address removed as a pauser function removePauser(address account) external onlyOwner { _removePauser(account); } uint256[49] private __gap; }
contract PauserRole is OwnerRole { event PauserAdded(address indexed addedPauser, address indexed addedBy); event PauserRemoved( address indexed removedPauser, address indexed removedBy ); Role private _pausers; /// @dev Modifier to make a function callable only when the caller is a pauser modifier onlyPauser() { require( isPauser(msg.sender), "PauserRole: caller does not have the Pauser role" ); _; } /// @dev Public function returns `true` if `account` has been granted a pauser role function isPauser(address account) public view returns (bool) { return _has(_pausers, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a pauser /// @param account The address that is guaranteed pauser authorization function _addPauser(address account) internal { _add(_pausers, account); emit PauserAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a pauser /// @param account The address removed as a pauser function _removePauser(address account) internal { _remove(_pausers, account); emit PauserRemoved(account, msg.sender); } /// @dev Public function that adds an address as a pauser /// @param account The address that is guaranteed pauser authorization function addPauser(address account) external onlyOwner { _addPauser(account); } /// @dev Public function that removes an account from being a pauser /// @param account The address removed as a pauser function removePauser(address account) external onlyOwner { _removePauser(account); } uint256[49] private __gap; }
18,182
35
// A token receives a child tokenparam The address that caused the transfer _from The owner of the child token _childTokenId The token that is being transferred to the parent _data Up to the first 32 bytes contains an integer which is the receiving parent tokenIdreturn the selector of this method /
function onERC721Received( address, address _from, uint256 _childTokenId, bytes calldata _data
function onERC721Received( address, address _from, uint256 _childTokenId, bytes calldata _data
47,669
156
// Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,non-reverting calls are assumed to be successful. /
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value)); } }
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value)); } }
32,193
23
// Emit the transfer event's details
TransferDetails(msg.sender, _to, _value,true,msg.gas); return true;
TransferDetails(msg.sender, _to, _value,true,msg.gas); return true;
38,960
14
// Set the owner of this contract. This function can only be called by/ the current owner.//_newOwner The new owner of this contract.
function setOwner(address payable _newOwner) external onlyOwner { owner = _newOwner; }
function setOwner(address payable _newOwner) external onlyOwner { owner = _newOwner; }
46,959
63
// Custom logic in here for how much the vault allows to be borrowed Sets minimum required on-hand to keep small withdrawals cheap
function available() public view returns (uint) { return token.balanceOf(address(this)).mul(min).div(max); }
function available() public view returns (uint) { return token.balanceOf(address(this)).mul(min).div(max); }
3,114
158
// Not allow transfer owner /
function transferOwnership(address) public pure override { revert("Not Allow Transfer Ownership."); }
function transferOwnership(address) public pure override { revert("Not Allow Transfer Ownership."); }
8,916
44
// caution, check safe-to-multiply here
uint256 _numerator = numerator * 10 ** uint256(precision+1);
uint256 _numerator = numerator * 10 ** uint256(precision+1);
399
33
// start an auction note: trusts the caller to transfer collateral to the contract The starting price `top` is obtained as follows: top = valbuf / par Where `val` is the collateral's unitary value in USD, `buf` is a multiplicative factor to increase the starting price, and `par` is a reference per DAI.
function kick( uint256 tab, // Debt [rad] uint256 lot, // Collateral [wad] address usr, // Address that will receive any leftover collateral address kpr // Address that will receive incentives
function kick( uint256 tab, // Debt [rad] uint256 lot, // Collateral [wad] address usr, // Address that will receive any leftover collateral address kpr // Address that will receive incentives
13,629
60
// ---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and an initial fixed supply, added teleport method ----------------------------------------------------------------------------
contract TeleportToken is ERC20Interface, Owned, Verify { TeleportTokenFactory factory; using SafeMath for uint256; string public symbol; string public name; uint8 public decimals; uint256 public _totalSupply; uint8 public threshold; uint8 public thisChainId; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; mapping(uint64 => mapping(address => bool)) signed; mapping(uint64 => bool) public claimed; event Teleport( address indexed from, string to, uint256 tokens, uint256 chainId ); event Claimed( uint64 id, address toAddress, address tokenAddress, uint256 amount ); struct TeleportData { uint64 id; uint32 ts; uint64 fromAddr; uint256 quantity; uint64 symbolRaw; uint8 chainId; address toAddress; address tokenAddress; uint8 nativeDecimals; } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor( string memory _symbol, string memory _name, uint8 _decimals, uint256 __totalSupply, uint8 _threshold, uint8 _thisChainId ) { symbol = _symbol; name = _name; decimals = _decimals; _totalSupply = __totalSupply * 10**uint256(_decimals); balances[address(0)] = _totalSupply; threshold = _threshold; thisChainId = _thisChainId; factory = TeleportTokenFactory(payable(address(msg.sender))); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view override returns (uint256) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view override returns (uint256 balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint256 tokens) public override returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint256 tokens) public override returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom( address from, address to, uint256 tokens ) public override returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view override returns (uint256 remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall( address spender, uint256 tokens, bytes memory data ) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval( msg.sender, tokens, address(this), data ); return true; } // ------------------------------------------------------------------------ // Moves tokens to the inaccessible account and then sends event for the oracles // to monitor and issue on other chain // to : EOS address // tokens : number of tokens in satoshis // chainId : The chain id that they will be sent to // ------------------------------------------------------------------------ function teleport( string memory to, uint256 tokens, uint256 chainid ) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[address(0)] = balances[address(0)].add(tokens); emit Transfer(msg.sender, address(0), tokens); emit Teleport(msg.sender, to, tokens, chainid); return true; } // ------------------------------------------------------------------------ // Claim tokens sent using signatures supplied to the other chain // ------------------------------------------------------------------------ function stringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function verifySigData(bytes memory sigData) private returns (TeleportData memory) { TeleportData memory td; uint64 id; uint32 ts; uint64 fromAddr; uint64 quantity; uint64 symbolRaw; uint8 chainId; address toAddress; address tokenAddress; uint8 nativeDecimals; // uint64 requiredSymbolRaw; assembly { id := mload(add(add(sigData, 0x8), 0)) ts := mload(add(add(sigData, 0x4), 8)) fromAddr := mload(add(add(sigData, 0x8), 12)) quantity := mload(add(add(sigData, 0x8), 20)) symbolRaw := mload(add(add(sigData, 0x8), 29)) chainId := mload(add(add(sigData, 0x1), 36)) toAddress := mload(add(add(sigData, 0x14), 37)) tokenAddress := mload(add(add(sigData, 0x14), 70)) nativeDecimals := mload(add(add(sigData, 0x1), 90)) } td.id = Endian.reverse64(id); td.ts = Endian.reverse32(ts); td.fromAddr = Endian.reverse64(fromAddr); td.symbolRaw = Endian.reverse64(symbolRaw); td.chainId = chainId; td.toAddress = toAddress; td.tokenAddress = tokenAddress; td.nativeDecimals = nativeDecimals; td.quantity = Endian.reverse64(quantity) * 10**(decimals - nativeDecimals); // requiredSymbolRaw = uint64( // bytes8(stringToBytes32(TeleportToken.symbol)) // ); // require(requiredSymbolRaw == symbolRaw - td.chainId, "Wrong symbol"); require(address(this) == td.tokenAddress, "Invalid token address"); require(thisChainId == td.chainId, "Invalid Chain ID"); require( block.timestamp < SafeMath.add(td.ts, (60 * 60 * 24 * 30)), "Teleport has expired" ); require(!claimed[td.id], "Already Claimed"); claimed[td.id] = true; return td; } function claim(bytes memory sigData, bytes[] calldata signatures) public returns (address toAddress) { TeleportData memory td = verifySigData(sigData); // verify signatures require(sigData.length == 91, "Signature data is the wrong size"); require( signatures.length <= 10, "Maximum of 10 signatures can be provided" ); bytes32 message = keccak256(sigData); uint8 numberSigs = 0; for (uint8 i = 0; i < signatures.length; i++) { address potential = Verify.recoverSigner(message, signatures[i]); // console.log(potential); // console.log(oracles[potential]); // Check that they are an oracle and they haven't signed twice if (factory.isOracle(potential) && !signed[td.id][potential]) { signed[td.id][potential] = true; numberSigs++; if (numberSigs >= threshold) { break; } } } require( numberSigs >= threshold, "Not enough valid signatures provided" ); balances[address(0)] = balances[address(0)].sub(td.quantity); balances[td.toAddress] = balances[td.toAddress].add(td.quantity); emit Claimed(td.id, td.toAddress, td.tokenAddress, td.quantity); emit Transfer(address(0), td.toAddress, td.quantity); return td.toAddress; } function updateThreshold(uint8 newThreshold) public onlyOwner returns (bool success) { if (newThreshold > 0) { require(newThreshold <= 10, "Threshold has maximum of 10"); threshold = newThreshold; return true; } return false; } function updateChainId(uint8 newChainId) public onlyOwner returns (bool success) { if (newChainId > 0) { require(newChainId <= 100, "ChainID is too big"); thisChainId = newChainId; return true; } return false; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ receive() external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint256 tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract TeleportToken is ERC20Interface, Owned, Verify { TeleportTokenFactory factory; using SafeMath for uint256; string public symbol; string public name; uint8 public decimals; uint256 public _totalSupply; uint8 public threshold; uint8 public thisChainId; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; mapping(uint64 => mapping(address => bool)) signed; mapping(uint64 => bool) public claimed; event Teleport( address indexed from, string to, uint256 tokens, uint256 chainId ); event Claimed( uint64 id, address toAddress, address tokenAddress, uint256 amount ); struct TeleportData { uint64 id; uint32 ts; uint64 fromAddr; uint256 quantity; uint64 symbolRaw; uint8 chainId; address toAddress; address tokenAddress; uint8 nativeDecimals; } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor( string memory _symbol, string memory _name, uint8 _decimals, uint256 __totalSupply, uint8 _threshold, uint8 _thisChainId ) { symbol = _symbol; name = _name; decimals = _decimals; _totalSupply = __totalSupply * 10**uint256(_decimals); balances[address(0)] = _totalSupply; threshold = _threshold; thisChainId = _thisChainId; factory = TeleportTokenFactory(payable(address(msg.sender))); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view override returns (uint256) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view override returns (uint256 balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint256 tokens) public override returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint256 tokens) public override returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom( address from, address to, uint256 tokens ) public override returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view override returns (uint256 remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall( address spender, uint256 tokens, bytes memory data ) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval( msg.sender, tokens, address(this), data ); return true; } // ------------------------------------------------------------------------ // Moves tokens to the inaccessible account and then sends event for the oracles // to monitor and issue on other chain // to : EOS address // tokens : number of tokens in satoshis // chainId : The chain id that they will be sent to // ------------------------------------------------------------------------ function teleport( string memory to, uint256 tokens, uint256 chainid ) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[address(0)] = balances[address(0)].add(tokens); emit Transfer(msg.sender, address(0), tokens); emit Teleport(msg.sender, to, tokens, chainid); return true; } // ------------------------------------------------------------------------ // Claim tokens sent using signatures supplied to the other chain // ------------------------------------------------------------------------ function stringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function verifySigData(bytes memory sigData) private returns (TeleportData memory) { TeleportData memory td; uint64 id; uint32 ts; uint64 fromAddr; uint64 quantity; uint64 symbolRaw; uint8 chainId; address toAddress; address tokenAddress; uint8 nativeDecimals; // uint64 requiredSymbolRaw; assembly { id := mload(add(add(sigData, 0x8), 0)) ts := mload(add(add(sigData, 0x4), 8)) fromAddr := mload(add(add(sigData, 0x8), 12)) quantity := mload(add(add(sigData, 0x8), 20)) symbolRaw := mload(add(add(sigData, 0x8), 29)) chainId := mload(add(add(sigData, 0x1), 36)) toAddress := mload(add(add(sigData, 0x14), 37)) tokenAddress := mload(add(add(sigData, 0x14), 70)) nativeDecimals := mload(add(add(sigData, 0x1), 90)) } td.id = Endian.reverse64(id); td.ts = Endian.reverse32(ts); td.fromAddr = Endian.reverse64(fromAddr); td.symbolRaw = Endian.reverse64(symbolRaw); td.chainId = chainId; td.toAddress = toAddress; td.tokenAddress = tokenAddress; td.nativeDecimals = nativeDecimals; td.quantity = Endian.reverse64(quantity) * 10**(decimals - nativeDecimals); // requiredSymbolRaw = uint64( // bytes8(stringToBytes32(TeleportToken.symbol)) // ); // require(requiredSymbolRaw == symbolRaw - td.chainId, "Wrong symbol"); require(address(this) == td.tokenAddress, "Invalid token address"); require(thisChainId == td.chainId, "Invalid Chain ID"); require( block.timestamp < SafeMath.add(td.ts, (60 * 60 * 24 * 30)), "Teleport has expired" ); require(!claimed[td.id], "Already Claimed"); claimed[td.id] = true; return td; } function claim(bytes memory sigData, bytes[] calldata signatures) public returns (address toAddress) { TeleportData memory td = verifySigData(sigData); // verify signatures require(sigData.length == 91, "Signature data is the wrong size"); require( signatures.length <= 10, "Maximum of 10 signatures can be provided" ); bytes32 message = keccak256(sigData); uint8 numberSigs = 0; for (uint8 i = 0; i < signatures.length; i++) { address potential = Verify.recoverSigner(message, signatures[i]); // console.log(potential); // console.log(oracles[potential]); // Check that they are an oracle and they haven't signed twice if (factory.isOracle(potential) && !signed[td.id][potential]) { signed[td.id][potential] = true; numberSigs++; if (numberSigs >= threshold) { break; } } } require( numberSigs >= threshold, "Not enough valid signatures provided" ); balances[address(0)] = balances[address(0)].sub(td.quantity); balances[td.toAddress] = balances[td.toAddress].add(td.quantity); emit Claimed(td.id, td.toAddress, td.tokenAddress, td.quantity); emit Transfer(address(0), td.toAddress, td.quantity); return td.toAddress; } function updateThreshold(uint8 newThreshold) public onlyOwner returns (bool success) { if (newThreshold > 0) { require(newThreshold <= 10, "Threshold has maximum of 10"); threshold = newThreshold; return true; } return false; } function updateChainId(uint8 newChainId) public onlyOwner returns (bool success) { if (newChainId > 0) { require(newChainId <= 100, "ChainID is too big"); thisChainId = newChainId; return true; } return false; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ receive() external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint256 tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
27,929
37
// return the target amount and the conversion fee using the updated reserve weights
(uint256 targetAmount, , uint256 fee) = targetAmountAndFees( _sourceToken, _targetToken, sourceTokenWeight, targetTokenWeight, _amount ); return (targetAmount, fee);
(uint256 targetAmount, , uint256 fee) = targetAmountAndFees( _sourceToken, _targetToken, sourceTokenWeight, targetTokenWeight, _amount ); return (targetAmount, fee);
45,358
76
// Adds an array of strings to the request with a given key name self The initialized request key The name of the key values The array of string values to add /
function addStringArray( Request memory self, string memory key, string[] memory values
function addStringArray( Request memory self, string memory key, string[] memory values
22,556