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 |
|---|---|---|---|---|
4 | // Set up Admin role initially | _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
PEBBLE_NFT_CONTRACT_ADDRESS = 0x0500065B7943102E06c31Dc16a8d2A7414330d7a;
| _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
PEBBLE_NFT_CONTRACT_ADDRESS = 0x0500065B7943102E06c31Dc16a8d2A7414330d7a;
| 15,420 |
176 | // cardIndex = getRandomNumber() % (52 - i); | deck[i] = unshuffled[cardIndex];
unshuffled[cardIndex] = unshuffled[52 - i - 1];
| deck[i] = unshuffled[cardIndex];
unshuffled[cardIndex] = unshuffled[52 - i - 1];
| 22,529 |
6 | // return the index of the new profile | return createdProfiles.length;
| return createdProfiles.length;
| 9,908 |
1 | // This emits when one or a set of functions are updated in a transparent contract./The message string should give a short description of the change and why/the change was made. | event CommitMessage(string message);
| event CommitMessage(string message);
| 1 |
13 | // TODO Make in nonReentrant | require(
msg.value == TOKEN_PRICE * amount,
"LS1155: Send correct price"
);
| require(
msg.value == TOKEN_PRICE * amount,
"LS1155: Send correct price"
);
| 3,549 |
82 | // 直接把剛剛賣出的價格煉金 | bool reduced = coin.reduce(tokenPrice);
require(reduced);
| bool reduced = coin.reduce(tokenPrice);
require(reduced);
| 38,574 |
55 | // Removes a depositor from the list._from the address of the depositorindexthe index of the depositor/ | function removeHolder(address _from, uint index) internal{
require(Holders.length>0 && Holders[index] == _from);
uint Len = Holders.length-1;
Holders[index] = Holders[Len];
address[] memory temp = new address[](Len);
for(uint i=0;i<Len;i++){
temp[i] = Holders[i];
}
Holders = temp;
}
| function removeHolder(address _from, uint index) internal{
require(Holders.length>0 && Holders[index] == _from);
uint Len = Holders.length-1;
Holders[index] = Holders[Len];
address[] memory temp = new address[](Len);
for(uint i=0;i<Len;i++){
temp[i] = Holders[i];
}
Holders = temp;
}
| 46,658 |
1 | // Throws if called by any account other than the owner | modifier onlyOwner() {
require(owner == msg.sender, "Ownable2Step: caller is not the owner");
_;
}
| modifier onlyOwner() {
require(owner == msg.sender, "Ownable2Step: caller is not the owner");
_;
}
| 192 |
242 | // getVotingProxy(): returns _point's current voting proxy | function getVotingProxy(uint32 _point)
view
external
returns (address voter)
| function getVotingProxy(uint32 _point)
view
external
returns (address voter)
| 2,076 |
243 | // Exit early if fees were already paid during this block. | if (lastPaymentTime == time) {
return totalPaid;
}
| if (lastPaymentTime == time) {
return totalPaid;
}
| 2,580 |
68 | // Allow users to upgrade manualy from our previous tokens.For trust issues, addresses are hardcoded.Used when a user failed to swap in time.Dev should manually verify the origin of these tokens before allowing it. _token Token the user wants to swap. / | function manualUpgradeTokens(address _token) public {
require(!hasSwapped[msg.sender], "User already swapped");
require(now >= swapStartedBlock + 1 days, "Timeframe incorrect");
require(_token == allowedSwapAddress01 || _token == allowedSwapAddress02, "Token not allowed to swap.");
uint amountToUpgrade = ERC20(_token).balanceOf(msg.sender);
require(amountToUpgrade <= ERC20(_token).allowance(msg.sender, this));
if (ERC20(_token).transferFrom(msg.sender, this, amountToUpgrade)) {
require(ERC20(_token).balanceOf(msg.sender) == 0);
if(
ERC20(allowedSwapAddress01).balanceOf(msg.sender) == 0 &&
ERC20(allowedSwapAddress02).balanceOf(msg.sender) == 0
) {
hasSwapped[msg.sender] = true;
}
tokens[_token][msg.sender] = tokens[_token][msg.sender].add(amountToUpgrade);
manualSwaps[msg.sender] = amountToUpgrade;
emit NewSwapRequest(msg.sender, amountToUpgrade);
}
}
| function manualUpgradeTokens(address _token) public {
require(!hasSwapped[msg.sender], "User already swapped");
require(now >= swapStartedBlock + 1 days, "Timeframe incorrect");
require(_token == allowedSwapAddress01 || _token == allowedSwapAddress02, "Token not allowed to swap.");
uint amountToUpgrade = ERC20(_token).balanceOf(msg.sender);
require(amountToUpgrade <= ERC20(_token).allowance(msg.sender, this));
if (ERC20(_token).transferFrom(msg.sender, this, amountToUpgrade)) {
require(ERC20(_token).balanceOf(msg.sender) == 0);
if(
ERC20(allowedSwapAddress01).balanceOf(msg.sender) == 0 &&
ERC20(allowedSwapAddress02).balanceOf(msg.sender) == 0
) {
hasSwapped[msg.sender] = true;
}
tokens[_token][msg.sender] = tokens[_token][msg.sender].add(amountToUpgrade);
manualSwaps[msg.sender] = amountToUpgrade;
emit NewSwapRequest(msg.sender, amountToUpgrade);
}
}
| 14,989 |
10 | // Stores the pendingOwner address/ return _pendingOwner The pendingOwner addresss | function pendingOwner() external view returns (address _pendingOwner);
| function pendingOwner() external view returns (address _pendingOwner);
| 505 |
11 | // Increase number of tokens locked for a specified reason _reason The reason to lock tokens _amount Number of tokens to be increased / | function increaseLockAmount(bytes32 _reason, uint256 _amount)
| function increaseLockAmount(bytes32 _reason, uint256 _amount)
| 28,538 |
77 | // Return to user sharesEscrowed that weren&39;t filled yet for all outcomes except the order outcome | if (_type == Order.Types.Bid) {
for (uint256 _i = 0; _i < _market.getNumberOfOutcomes(); ++_i) {
if (_i != _outcome) {
_market.getShareToken(_i).trustedCancelOrderTransfer(_market, _sender, _sharesEscrowed);
}
| if (_type == Order.Types.Bid) {
for (uint256 _i = 0; _i < _market.getNumberOfOutcomes(); ++_i) {
if (_i != _outcome) {
_market.getShareToken(_i).trustedCancelOrderTransfer(_market, _sender, _sharesEscrowed);
}
| 52,636 |
136 | // Returns unlockable tokens for a specified address for a specified reason _of The address to query the the unlockable token count of _reason The reason to query the unlockable tokens for / | function tokensUnlockable(address _of, bytes32 _reason)
| function tokensUnlockable(address _of, bytes32 _reason)
| 33,281 |
1 | // Max amount of token to purchase per account each time | uint public MAX_PURCHASE = 1;
| uint public MAX_PURCHASE = 1;
| 22,663 |
174 | // The GMT TOKEN! | GoldMining public gmt;
| GoldMining public gmt;
| 51,331 |
952 | // DEBT_SWAP | proxyData1 = abi.encodeWithSignature(
"changeDebt(address,address,uint256,uint256)",
shiftData.debtAddr1,
shiftData.debtAddr2,
_amount,
exchangeData.srcAmount
);
| proxyData1 = abi.encodeWithSignature(
"changeDebt(address,address,uint256,uint256)",
shiftData.debtAddr1,
shiftData.debtAddr2,
_amount,
exchangeData.srcAmount
);
| 55,165 |
1 | // is everything okey | require(
campaign.deadline < block.timestamp,
"Deadline should be date in the future"
);
campaign.owner = _owner;
campaign.title = _title;
campaign.description = _description;
campaign.target = _target;
campaign.deadline = _deadline;
campaign.amountCollected = 0;
| require(
campaign.deadline < block.timestamp,
"Deadline should be date in the future"
);
campaign.owner = _owner;
campaign.title = _title;
campaign.description = _description;
campaign.target = _target;
campaign.deadline = _deadline;
campaign.amountCollected = 0;
| 14,677 |
26 | // Emitted on mintUnbacked() reserve The address of the underlying asset of the reserve user The address initiating the supply onBehalfOf The beneficiary of the supplied assets, receiving the aTokens amount The amount of supplied assets referralCode The referral code used / | event MintUnbacked(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint16 indexed referralCode
);
| event MintUnbacked(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint16 indexed referralCode
);
| 4,385 |
25 | // Contains all logic for cancelling an unbond operation. For the given deposit, resets the unbonding timer, and reverts boosts to amount determined by lock.depositId The specified deposit to unbond from. / | function _cancelUnbonding(uint256 depositId) internal {
// Fetch stake and make sure it is withdrawable
UserStake storage s = stakes[msg.sender][depositId];
uint256 depositAmount = s.amount;
if (depositAmount == 0) revert USR_NoDeposit(depositId);
if (s.unbondTimestamp == 0) revert USR_NotUnbonding(depositId);
_updateRewardForStake(msg.sender, depositId);
// Reinstate
(uint256 boost, ) = _getBoost(s.lock);
uint256 amountWithBoost = s.amount + (s.amount * boost) / ONE;
uint256 depositAmountIncreased = amountWithBoost - s.amountWithBoost;
s.amountWithBoost = uint112(amountWithBoost);
s.unbondTimestamp = 0;
totalDepositsWithBoost += depositAmountIncreased;
emit CancelUnbond(msg.sender, depositId);
}
| function _cancelUnbonding(uint256 depositId) internal {
// Fetch stake and make sure it is withdrawable
UserStake storage s = stakes[msg.sender][depositId];
uint256 depositAmount = s.amount;
if (depositAmount == 0) revert USR_NoDeposit(depositId);
if (s.unbondTimestamp == 0) revert USR_NotUnbonding(depositId);
_updateRewardForStake(msg.sender, depositId);
// Reinstate
(uint256 boost, ) = _getBoost(s.lock);
uint256 amountWithBoost = s.amount + (s.amount * boost) / ONE;
uint256 depositAmountIncreased = amountWithBoost - s.amountWithBoost;
s.amountWithBoost = uint112(amountWithBoost);
s.unbondTimestamp = 0;
totalDepositsWithBoost += depositAmountIncreased;
emit CancelUnbond(msg.sender, depositId);
}
| 24,047 |
0 | // Get pool's balance of token0/ Gas saving to avoid a redundant extcodesize check/ in addition to the returndatasize check | function _poolBalToken0() private view returns (uint256) {
(bool success, bytes memory data) = address(token0).staticcall(
abi.encodeWithSelector(IERC20.balanceOf.selector, address(this))
);
require(success && data.length >= 32);
return abi.decode(data, (uint256));
}
| function _poolBalToken0() private view returns (uint256) {
(bool success, bytes memory data) = address(token0).staticcall(
abi.encodeWithSelector(IERC20.balanceOf.selector, address(this))
);
require(success && data.length >= 32);
return abi.decode(data, (uint256));
}
| 26,831 |
10 | // return The result of safely dividing x and y. The return value is as a roundedstandard precision decimal.y is divided after the product of x and the standard precision unitis evaluated, so the product of x and the standard precision unit mustbe less than 2256. The result is rounded to the nearest increment. / | function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
| function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
| 11,675 |
4 | // Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). Counterpart to Solidity's `-` operator. Requirements:- Subtraction cannot underflow. / | function sub(
uint256 a,
uint256 b,
string memory errorMessage
| function sub(
uint256 a,
uint256 b,
string memory errorMessage
| 4,532 |
308 | // OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol)/ This abstract contract provides getters and event emitting update functions for _Available since v4.1._ @custom:oz-upgrades-unsafe-allow delegatecall / | abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal onlyInitializing {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT =
0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(
AddressUpgradeable.isContract(newImplementation),
"ERC1967: new implementation is not a contract"
);
StorageSlotUpgradeable
.getAddressSlot(_IMPLEMENTATION_SLOT)
.value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot
storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(
_ROLLBACK_SLOT
);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(
oldImplementation == _getImplementation(),
"ERC1967Upgrade: upgrade breaks further upgrades"
);
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(
newAdmin != address(0),
"ERC1967: new admin is the zero address"
);
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT =
0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(
AddressUpgradeable.isContract(newBeacon),
"ERC1967: new beacon is not a contract"
);
require(
AddressUpgradeable.isContract(
IBeaconUpgradeable(newBeacon).implementation()
),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(
IBeaconUpgradeable(newBeacon).implementation(),
data
);
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data)
private
returns (bytes memory)
{
require(
AddressUpgradeable.isContract(target),
"Address: delegate call to non-contract"
);
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return
AddressUpgradeable.verifyCallResult(
success,
returndata,
"Address: low-level delegate call failed"
);
}
uint256[50] private __gap;
}
| abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal onlyInitializing {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT =
0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(
AddressUpgradeable.isContract(newImplementation),
"ERC1967: new implementation is not a contract"
);
StorageSlotUpgradeable
.getAddressSlot(_IMPLEMENTATION_SLOT)
.value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot
storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(
_ROLLBACK_SLOT
);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(
oldImplementation == _getImplementation(),
"ERC1967Upgrade: upgrade breaks further upgrades"
);
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(
newAdmin != address(0),
"ERC1967: new admin is the zero address"
);
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT =
0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(
AddressUpgradeable.isContract(newBeacon),
"ERC1967: new beacon is not a contract"
);
require(
AddressUpgradeable.isContract(
IBeaconUpgradeable(newBeacon).implementation()
),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(
IBeaconUpgradeable(newBeacon).implementation(),
data
);
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data)
private
returns (bytes memory)
{
require(
AddressUpgradeable.isContract(target),
"Address: delegate call to non-contract"
);
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return
AddressUpgradeable.verifyCallResult(
success,
returndata,
"Address: low-level delegate call failed"
);
}
uint256[50] private __gap;
}
| 61,227 |
48 | // Get the average price of 1 REB in Wei | function getRebEthRate() public view returns (uint256, uint256, uint32, uint256) {
(uint price0Cumulative, uint price1Cumulative, uint32 _blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(address(_eth_reb));
FixedPoint.uq112x112 memory rebEthAverage = FixedPoint.uq112x112(uint224(1e9 * (price1Cumulative - ethRebPrice1CumulativeLast) / (_blockTimestamp - ethRebBlockTimestampLast)));
return (price0Cumulative, price1Cumulative, _blockTimestamp, rebEthAverage.mul(1).decode144());
}
| function getRebEthRate() public view returns (uint256, uint256, uint32, uint256) {
(uint price0Cumulative, uint price1Cumulative, uint32 _blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(address(_eth_reb));
FixedPoint.uq112x112 memory rebEthAverage = FixedPoint.uq112x112(uint224(1e9 * (price1Cumulative - ethRebPrice1CumulativeLast) / (_blockTimestamp - ethRebBlockTimestampLast)));
return (price0Cumulative, price1Cumulative, _blockTimestamp, rebEthAverage.mul(1).decode144());
}
| 48,546 |
26 | // Change the admin address. _admin address The new admin address / | function changeAdmin(address _admin) public onlyAdmin {
// The provided address should be valid and different from the current one.
require(_admin != 0x0 && admin != _admin);
// Store the new value.
admin = _admin;
}
| function changeAdmin(address _admin) public onlyAdmin {
// The provided address should be valid and different from the current one.
require(_admin != 0x0 && admin != _admin);
// Store the new value.
admin = _admin;
}
| 34,358 |
86 | // public variables // events / | modifier onlyAllowedMultivests(address _addresss) {
require(allowedMultivests[_addresss] == true);
_;
}
| modifier onlyAllowedMultivests(address _addresss) {
require(allowedMultivests[_addresss] == true);
_;
}
| 15,921 |
5 | // Unregisters an address with the registry and removes its subscription. May be called by address itself or by EIP-173 owner.Note that this does not remove any filtered addresses or codeHashes.Also note that any subscriptions to this registrant will still be active and follow the existing filtered addresses and codehashes. / | function unregister(address addr) external;
| function unregister(address addr) external;
| 3,701 |
28 | // update status | redEnvelopInfos[redEnvelopId].remainMoney = redEnvelopInfos[redEnvelopId].remainMoney - amount;
redEnvelopInfos[redEnvelopId].remainCount = redEnvelopInfos[redEnvelopId].remainCount - 1;
redEnvelopInfos[redEnvelopId].recipientInfos[msg.sender] = amount;
| redEnvelopInfos[redEnvelopId].remainMoney = redEnvelopInfos[redEnvelopId].remainMoney - amount;
redEnvelopInfos[redEnvelopId].remainCount = redEnvelopInfos[redEnvelopId].remainCount - 1;
redEnvelopInfos[redEnvelopId].recipientInfos[msg.sender] = amount;
| 54,203 |
73 | // should send enough ether | require(msg.value >= packPrice);
| require(msg.value >= packPrice);
| 23,968 |
38 | // Convert Tokens to ETH && transfers ETH to recipient. User specifies maximum input && exact output. eth_bought Amount of ETH purchased. max_tokens Maximum Tokens sold. deadline Time after which this transaction can no longer be executed. recipient The address that receives output ETH.return Amount of Tokens sold. / | function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256);
| function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256);
| 9,001 |
9 | // Set next implementation contract address if not set yet.NextImplementation points to the next implementation contract in a chain of contracts to allow upgrading. Must not be a delegated call. Require caller to be Implementation Maintainer. Must not be zero address or self address.Emits `NextImplementationSet` event. nextImplementation Next implementation contract address. / | function setNextImplementation(VaultImplBase nextImplementation)
external
notDelegated
onlyMaintainer
| function setNextImplementation(VaultImplBase nextImplementation)
external
notDelegated
onlyMaintainer
| 17,545 |
74 | // ------------------------------------------------ Functions Setters Private ------------------------------------------------ |
function _removeZoneOwner()
private
|
function _removeZoneOwner()
private
| 41,738 |
36 | // ========== MUTATIVE FUNCTIONS ========== // Destroy the vesting information associated with an account. / | function purgeAccount(address account) external onlyOwner onlyDuringSetup {
delete vestingSchedules[account];
totalVestedBalance = totalVestedBalance.sub(totalVestedAccountBalance[account]);
delete totalVestedAccountBalance[account];
}
| function purgeAccount(address account) external onlyOwner onlyDuringSetup {
delete vestingSchedules[account];
totalVestedBalance = totalVestedBalance.sub(totalVestedAccountBalance[account]);
delete totalVestedAccountBalance[account];
}
| 44,247 |
8 | // Loan to value(ltv). 600=60% | uint256 public ltv = 600;
uint256 public installmentFrequency = 1;
TimeScale public installmentTimeScale = TimeScale.WEEKS;
| uint256 public ltv = 600;
uint256 public installmentFrequency = 1;
TimeScale public installmentTimeScale = TimeScale.WEEKS;
| 15,233 |
28 | // Called after oracle has updated flight status/ | function processFlightStatus
(
address airline,
string memory flight,
uint256 timestamp,
uint8 statusCode
)
internal
view //pure
requireIsOperational()
| function processFlightStatus
(
address airline,
string memory flight,
uint256 timestamp,
uint8 statusCode
)
internal
view //pure
requireIsOperational()
| 35,004 |
9 | // get a burn redeem corresponding to a creator contract and tokenId creatorContractAddressthe address of the creator contract tokenId the token to retrieve the burn redeem forreturnthe burn redeem instanceId and burn redeem object / | function getBurnRedeemForToken(address creatorContractAddress, uint256 tokenId) external view returns(uint256, BurnRedeem memory);
| function getBurnRedeemForToken(address creatorContractAddress, uint256 tokenId) external view returns(uint256, BurnRedeem memory);
| 19,620 |
21 | // The fee in LINK for VRF | uint256 internal _fee;
| uint256 internal _fee;
| 39,635 |
142 | // I am not a big fan ofreferencing a property on an array element that may not exist. But if it does not exist, Solidity will return 0 which is right. | return ownedTokens[_owner].length;
| return ownedTokens[_owner].length;
| 23,681 |
122 | // Checks if requested set of features is enabled globally on the contractrequired set of features to check againstreturn true if all the features requested are enabled, false otherwise / | function isFeatureEnabled(uint256 required) public view returns(bool) {
// delegate call to `__hasRole`, passing `features` property
return __hasRole(features(), required);
}
| function isFeatureEnabled(uint256 required) public view returns(bool) {
// delegate call to `__hasRole`, passing `features` property
return __hasRole(features(), required);
}
| 6,026 |
3 | // TODO: Do not use arrays in the interface for tokens and weights | (uint256 pauseWindowDuration, uint256 bufferPeriodDuration) = getPauseConfiguration();
WeightedPool2Tokens.NewPoolParams memory params = WeightedPool2Tokens.NewPoolParams({
vault: getVault(),
name: name,
symbol: symbol,
token0: tokens[0],
token1: tokens[1],
normalizedWeight0: weights[0],
normalizedWeight1: weights[1],
| (uint256 pauseWindowDuration, uint256 bufferPeriodDuration) = getPauseConfiguration();
WeightedPool2Tokens.NewPoolParams memory params = WeightedPool2Tokens.NewPoolParams({
vault: getVault(),
name: name,
symbol: symbol,
token0: tokens[0],
token1: tokens[1],
normalizedWeight0: weights[0],
normalizedWeight1: weights[1],
| 52,444 |
157 | // copy the x and y values | geomVars.trisFront[i][j][k] = tris[i][j][k];
geomVars.trisBack[i][j][k] = tris[i][j][k];
| geomVars.trisFront[i][j][k] = tris[i][j][k];
geomVars.trisBack[i][j][k] = tris[i][j][k];
| 71,971 |
3 | // Calculate quantity of strikeTokens needed to exercise quantity of optionTokens. | uint256 inputStrikes = exerciseQuantity
.mul(optionToken.getQuoteValue())
.div(optionToken.getBaseValue());
require(
IERC20(optionToken.getStrikeTokenAddress()).balanceOf(msg.sender) >=
inputStrikes,
"ERR_BAL_STRIKE"
);
IERC20(optionToken.getStrikeTokenAddress()).safeTransferFrom(
msg.sender,
| uint256 inputStrikes = exerciseQuantity
.mul(optionToken.getQuoteValue())
.div(optionToken.getBaseValue());
require(
IERC20(optionToken.getStrikeTokenAddress()).balanceOf(msg.sender) >=
inputStrikes,
"ERR_BAL_STRIKE"
);
IERC20(optionToken.getStrikeTokenAddress()).safeTransferFrom(
msg.sender,
| 13,245 |
59 | // check that minimum number of people voted for the proposal. | if (proposal.votes < _minProposalVotes) {
return false;
}
| if (proposal.votes < _minProposalVotes) {
return false;
}
| 12,612 |
87 | // Return to caller all posted chai if there is no debt, converted to dai, plus any dai remaining in the contract. | function withdrawAssets(IFYDai fyDai) internal {
if (controller.debtFYDai(CHAI, fyDai.maturity(), msg.sender) == 0) {
controller.withdraw(CHAI, msg.sender, address(this), controller.posted(CHAI, msg.sender));
chai.exit(address(this), chai.balanceOf(address(this)));
}
require(dai.transfer(msg.sender, dai.balanceOf(address(this))), "YieldProxy: Dai Transfer Failed");
}
| function withdrawAssets(IFYDai fyDai) internal {
if (controller.debtFYDai(CHAI, fyDai.maturity(), msg.sender) == 0) {
controller.withdraw(CHAI, msg.sender, address(this), controller.posted(CHAI, msg.sender));
chai.exit(address(this), chai.balanceOf(address(this)));
}
require(dai.transfer(msg.sender, dai.balanceOf(address(this))), "YieldProxy: Dai Transfer Failed");
}
| 8,999 |
9 | // Apply a new entry to the TCR. The applicant must stake token at least `min_deposit`./ Application will get auto-approved if no challenge happens in `apply_stage_length` seconds. | function applyEntry(address proposer, uint256 stake, bytes32 data)
public
requireToken(token, proposer, stake)
entryMustNotExist(data)
| function applyEntry(address proposer, uint256 stake, bytes32 data)
public
requireToken(token, proposer, stake)
entryMustNotExist(data)
| 14,364 |
189 | // return a SemVer-compliant version of the hub contract | function versionHub() external view returns (string memory);
| function versionHub() external view returns (string memory);
| 11,230 |
160 | // Check if an extension can mint / | function _checkMintPermissions(address to, uint256 tokenId) internal {
if (_extensionPermissions[msg.sender] != address(0x0)) {
IERC721CreatorMintPermissions(_extensionPermissions[msg.sender]).approveMint(msg.sender, to, tokenId);
}
}
| function _checkMintPermissions(address to, uint256 tokenId) internal {
if (_extensionPermissions[msg.sender] != address(0x0)) {
IERC721CreatorMintPermissions(_extensionPermissions[msg.sender]).approveMint(msg.sender, to, tokenId);
}
}
| 25,062 |
93 | // unstake while applying GYSR token for boosted rewards amount number of tokens to unstake gysr number of GYSR tokens to apply for boost / | function unstake(
| function unstake(
| 38,093 |
8 | // update cliente | function editCustomer(uint32 id, Customer memory newCustomer) public {
//take actual data, and update
Customer memory oldCustomer = customers[id];
if(bytes(oldCustomer.name).length == 0) return;
if (bytes(newCustomer.name).length > 0 && !compareStrings(oldCustomer.name, newCustomer.name))
oldCustomer.name = newCustomer.name;
customers[id] = oldCustomer;
}
| function editCustomer(uint32 id, Customer memory newCustomer) public {
//take actual data, and update
Customer memory oldCustomer = customers[id];
if(bytes(oldCustomer.name).length == 0) return;
if (bytes(newCustomer.name).length > 0 && !compareStrings(oldCustomer.name, newCustomer.name))
oldCustomer.name = newCustomer.name;
customers[id] = oldCustomer;
}
| 33,066 |
77 | // How much is enough? | uint public constant dust = 100 finney;
| uint public constant dust = 100 finney;
| 55,070 |
1,244 | // These will be populated within the scope below. | FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
| FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
| 9,626 |
45 | // Failsafe, but if you find a way go for it. | return 1000000 ether;
| return 1000000 ether;
| 21,403 |
10 | // solhint-disable avoid-low-level-calls | (bool success, ) = _recipients[i].recipient.call(payload);
if (!success) {
| (bool success, ) = _recipients[i].recipient.call(payload);
if (!success) {
| 18,243 |
11 | // The `phAddr` is the address of the PriceHandler contract. / | address private phAddr;
| address private phAddr;
| 359 |
241 | // Uses WETH to buy back BIOS which is sent to the Kernel | function biosBuyBack() external;
| function biosBuyBack() external;
| 22,628 |
51 | // Uses collateral to generate debt on TCAP Tokens which are minted and assigend to caller _amount of tokens to mint _amount should be higher than 0 requires to have a vault ratio above the minimum ratio if reward handler is set stake to earn rewards / | function mint(uint256 _amount)
external
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
| function mint(uint256 _amount)
external
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
| 7,004 |
2 | // Does whatever work or queries will yield the most up-to-date price, and returns it.return value in wei / | function get(bytes32 base, bytes32 quote, uint256 amount) external returns (uint256 value, uint256 updateTime);
| function get(bytes32 base, bytes32 quote, uint256 amount) external returns (uint256 value, uint256 updateTime);
| 35,326 |
77 | // Base URI for computing {tokenURI}. / | function _setBaseURI(string memory baseURI_) internal {
_baseURI = baseURI_;
}
| function _setBaseURI(string memory baseURI_) internal {
_baseURI = baseURI_;
}
| 27,347 |
0 | // Solution 1: use transfer() to send ether | function withdraw1(uint amount) external {
require(balances[msg.sender] >= amount);
msg.sender.transfer(amount);
balances[msg.sender]--;
}
| function withdraw1(uint amount) external {
require(balances[msg.sender] >= amount);
msg.sender.transfer(amount);
balances[msg.sender]--;
}
| 47,910 |
263 | // Holds number & validity of tokens locked for a given reason for a specified address / | mapping(address => mapping(bytes32 => LockToken)) public locked;
| mapping(address => mapping(bytes32 => LockToken)) public locked;
| 82,102 |
4 | // Withdraw the requested amount of the underlying tokens to address(this)./amount The requested amount we want to withdraw. | function _withdraw(uint256 amount) internal virtual {}
| function _withdraw(uint256 amount) internal virtual {}
| 30,780 |
6 | // register interfaces | _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
| _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
| 22,067 |
372 | // Send the amount to the simple address using call instead of transfer | (bool success,) = splitter.call{value: amountToSend}("");
| (bool success,) = splitter.call{value: amountToSend}("");
| 23,237 |
12 | // Gets the bit at the given position in the given integer. 31 is the leftmost bit, 0 is the rightmost bit.For example: bitAt(2, 0) == 0, because the rightmost bit of 10 is 0bitAt(2, 1) == 1, because the second to last bit of 10 is 1 / | function bitAt(uint integer, uint pos) external pure returns (uint) {
require(pos <= 31, "pos > 31");
return (integer & (1 << pos)) >> pos;
}
| function bitAt(uint integer, uint pos) external pure returns (uint) {
require(pos <= 31, "pos > 31");
return (integer & (1 << pos)) >> pos;
}
| 22,015 |
51 | // Executing all transfers | for (uint256 i = 0; i < nTransfer; i++) {
| for (uint256 i = 0; i < nTransfer; i++) {
| 11,005 |
11 | // Check if the implementation of liquidity pool target is compatible with the implementation base. Being compatible means having larger compatibility.targetVersionKeyThe key of the version to be upgraded to. baseVersionKeyThe key of the version to be upgraded from.returnisCompatibleTrue if the target version is compatible with the base version. / | function isVersionCompatible(bytes32 targetVersionKey, bytes32 baseVersionKey)
public
view
override
returns (bool isCompatible)
| function isVersionCompatible(bytes32 targetVersionKey, bytes32 baseVersionKey)
public
view
override
returns (bool isCompatible)
| 8,521 |
3 | // Lookup risks from risk IDs | mapping (bytes32 => Risk) public risks;
| mapping (bytes32 => Risk) public risks;
| 3,485 |
430 | // Make sure the result is less than 2256 - also prevents denominator == 0. | require(denominator > prod1);
| require(denominator > prod1);
| 37,663 |
0 | // Sets up `role` for `account` | function _setupRole(bytes32 role, address account) internal override {
super._setupRole(role, account);
_addMember(role, account);
}
| function _setupRole(bytes32 role, address account) internal override {
super._setupRole(role, account);
_addMember(role, account);
}
| 916 |
3 | // Cross-chain Functions// Finalize a bridge from L2 to L1, and credit funds to the recipient's balance of theL1 ETH token. Since only the xDomainMessenger can call this function, it will never be calledbefore the bridge is finalized. _from L2 address initiating the transfer. _to L1 address to credit the ERC20 to. _amount Amount of the ERC20 to bridge. _localGasLimit Minimum gas limit for the reverse bridge message on this domain. _remoteGasLimit Minimum gas limit for the bridge message on the other domain. _data Optional data to forward to L2. This data is provided solely as a convenience for external contracts. | function finalizeETHBridge(
| function finalizeETHBridge(
| 23,011 |
4 | // The circuit itself (compressed with zip, please) | bytes m_zip_provkey ;
| bytes m_zip_provkey ;
| 23,286 |
406 | // Read the transfer | Transfer memory transfer;
readTx(data, offset, transfer);
TransferAuxiliaryData memory auxData = abi.decode(auxiliaryData, (TransferAuxiliaryData));
| Transfer memory transfer;
readTx(data, offset, transfer);
TransferAuxiliaryData memory auxData = abi.decode(auxiliaryData, (TransferAuxiliaryData));
| 53,234 |
13 | // set pause limit _pauseLimit pause limit / | function setPauseLimit(uint256 _pauseLimit) public onlyOwner {
pauseLimit = _pauseLimit;
}
| function setPauseLimit(uint256 _pauseLimit) public onlyOwner {
pauseLimit = _pauseLimit;
}
| 4,867 |
5 | // Require that the caller must be an EOA account to avoid flash loans. / | modifier onlyEOA() {
require(msg.sender == tx.origin, "Not EOA");
_;
}
| modifier onlyEOA() {
require(msg.sender == tx.origin, "Not EOA");
_;
}
| 28,155 |
4 | // Set the address of the Value Instrument currency governed by this DAO to `_viCoinAddress`/ | function setVICoinAddress(address _viCoinAddress)
external
auth(SETCOINADDRESS)
| function setVICoinAddress(address _viCoinAddress)
external
auth(SETCOINADDRESS)
| 11,857 |
43 | // Crowdsale Crowdsale is a base contract for managing a token crowdsale.Crowdsales have a start and end timestamps, where investors can maketoken purchases. Funds collected are forwarded to a walletas they arrive. / | contract Crowdsale is Ownable {
using SafeMath for uint256;
// address where funds are collected
address public wallet;
// amount of raised money in wei
uint256 public weiRaised;
uint256 public tokenAllocated;
uint256 public hardWeiCap = 119000 * (10 ** 18);
function Crowdsale(
address _wallet
)
public
{
require(_wallet != address(0));
wallet = _wallet;
}
}
| contract Crowdsale is Ownable {
using SafeMath for uint256;
// address where funds are collected
address public wallet;
// amount of raised money in wei
uint256 public weiRaised;
uint256 public tokenAllocated;
uint256 public hardWeiCap = 119000 * (10 ** 18);
function Crowdsale(
address _wallet
)
public
{
require(_wallet != address(0));
wallet = _wallet;
}
}
| 16,829 |
68 | // The current total principal + total base interest, total (estimate) debtor specific risk premium interest owed by all debtors.Note the (total principal + total base interest) portion is up to date. However the (debtor specific risk premium interest) portion is likely stale. The `estimatedTotalRiskPremiumInterest` is only updated when each debtor checkpoints, so it's going to be out of date. For more up to date current totals, off-chain aggregation of balanceOf() will be required - eg via subgraph./ | function currentTotalDebt() external override view returns (
DebtOwed memory debtOwed
| function currentTotalDebt() external override view returns (
DebtOwed memory debtOwed
| 18,975 |
216 | // 要投入的token0、token1数量 | uint amount0Max;
uint amount1Max;
| uint amount0Max;
uint amount1Max;
| 26,003 |
1 | // multiply by 4/3 rounded up | uint256 encodedLen = 4 * ((data.length + 2) / 3);
| uint256 encodedLen = 4 * ((data.length + 2) / 3);
| 7,557 |
2 | // Interface to Status ICO Contract | contract StatusContribution {
uint256 public maxGasPrice;
uint256 public startBlock;
uint256 public totalNormalCollected;
uint256 public finalizedBlock;
function proxyPayment(address _th) payable returns (bool);
}
| contract StatusContribution {
uint256 public maxGasPrice;
uint256 public startBlock;
uint256 public totalNormalCollected;
uint256 public finalizedBlock;
function proxyPayment(address _th) payable returns (bool);
}
| 8,582 |
15 | // Permanently burn tokens/self Stored token from token contract/_amount Amount of tokens to burn/ return True if completed | function burnToken(TokenStorage storage self, uint256 _amount) returns (bool) {
uint256 _newBalance;
bool err;
(err, _newBalance) = self.balances[msg.sender].minus(_amount);
require(!err);
self.balances[msg.sender] = _newBalance;
self.totalSupply = self.totalSupply - _amount;
Burn(msg.sender, _amount);
Transfer(msg.sender, 0x0, _amount);
return true;
}
| function burnToken(TokenStorage storage self, uint256 _amount) returns (bool) {
uint256 _newBalance;
bool err;
(err, _newBalance) = self.balances[msg.sender].minus(_amount);
require(!err);
self.balances[msg.sender] = _newBalance;
self.totalSupply = self.totalSupply - _amount;
Burn(msg.sender, _amount);
Transfer(msg.sender, 0x0, _amount);
return true;
}
| 17,009 |
238 | // Trying something new, please no DMCA or crap, reachout first thanks! | string constant ArtLicense = "All rights reserved to token owner";
address constant publicKey = 0x045BF88F67846F6C06DF5cf4895de431522d2189;
| string constant ArtLicense = "All rights reserved to token owner";
address constant publicKey = 0x045BF88F67846F6C06DF5cf4895de431522d2189;
| 85,097 |
94 | // View function to see pending Reward on frontend. | function pendingReward(address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[_user];
if(pool.lastRewardTimestamp == 21799615){
return 0;
}
uint256 accTokensPerShare = pool.accTokensPerShare;
uint256 lpSupply = totalStaked;
if (block.timestamp > pool.lastRewardTimestamp && lpSupply != 0) {
uint256 tokenReward = calculateNewRewards().mul(pool.allocPoint).div(totalAllocPoint);
accTokensPerShare = accTokensPerShare.add(tokenReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accTokensPerShare).div(1e12).sub(user.rewardDebt);
}
| function pendingReward(address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[_user];
if(pool.lastRewardTimestamp == 21799615){
return 0;
}
uint256 accTokensPerShare = pool.accTokensPerShare;
uint256 lpSupply = totalStaked;
if (block.timestamp > pool.lastRewardTimestamp && lpSupply != 0) {
uint256 tokenReward = calculateNewRewards().mul(pool.allocPoint).div(totalAllocPoint);
accTokensPerShare = accTokensPerShare.add(tokenReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accTokensPerShare).div(1e12).sub(user.rewardDebt);
}
| 5,020 |
167 | // Maximum total weight | uint public constant MAX_TOTAL_WEIGHT = BONE * 50;
| uint public constant MAX_TOTAL_WEIGHT = BONE * 50;
| 8,537 |
164 | // https:github.com/iearn-finance/vaults/blob/master/contracts/vaults/yVault.sol | contract MMVault is ReentrancyGuard, ERC20Permit {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
IERC20 public token;
IChiToken public constant chi = IChiToken(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c);
uint256 public min = 9500;
uint256 public constant max = 10000;
uint256 public loanFee = 1;
uint256 public loanFeeMax = 10000;
bool public loanEnabled = true;
address public governance;
address public timelock;
address public controller;
mapping(address => bool) public keepers;
mapping(address => bool) public reentrancyWhitelist;
uint256 public DAY_SECONDS = 86400;
uint256 public lockWindowBuffer = DAY_SECONDS/4;
uint256 public lockStartTime;
uint256 public lockWindow;
uint256 public withdrawWindow;
uint256 public earnedTimestamp;
bool public lockEnabled = false;
bool public earnOnceEnabled = false;
event FlashLoan(address _token, address _receiver, uint256 _amount, uint256 _loanFee);
modifier discountCHI() {
uint256 gasStart = gasleft();
_;
uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length;
if(chi.balanceOf(msg.sender) > 0) {
chi.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41947);
}
}
modifier onlyKeepers {
require(
keepers[msg.sender] ||
msg.sender == governance,
"!keepers"
);
_;
}
modifier onlyGovernance(){
require(msg.sender == governance, "!governance");
_;
}
modifier canEarn {
if(lockEnabled){
require(
block.timestamp > lockStartTime,
"!earnTime"
);
if(earnOnceEnabled){
require(
block.timestamp.sub(earnedTimestamp) > lockWindow,
"!earnTwice");
if(earnedTimestamp != 0){
lockStartTime = getLockCycleEndTime();
}
earnedTimestamp = block.timestamp;
}
}
_;
}
modifier canWithdraw(uint256 _shares) {
if(lockEnabled){
//withdraw locker not work when withdraw amount less than available balance
if(!withdrawableWithoutLock(_shares)){
uint256 withdrawStartTimestamp = lockStartTime.add(lockWindow);
require(
block.timestamp > withdrawStartTimestamp &&
block.timestamp < withdrawStartTimestamp.add(withdrawWindow),
"!withdrawTime"
);
}
}
_;
}
modifier nonReentrantWithWhitelist() {
// only check if NOT in whitelist
if (!reentrancyWhitelist[msg.sender]){
// On the first call to nonReentrantWithWhitelist, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrantWithWhitelist after this point will fail
_status = _ENTERED;
}
_;
if (!reentrancyWhitelist[msg.sender]){
// By storing the original value once again, a refund is triggered (see https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
constructor(address _token, address _governance, address _timelock, address _controller)
public
ERC20Permit(
string(abi.encodePacked("mushrooming ", ERC20(_token).name())),
string(abi.encodePacked("m", ERC20(_token).symbol()))
)
{
_setupDecimals(ERC20(_token).decimals());
token = IERC20(_token);
governance = _governance;
timelock = _timelock;
controller = _controller;
//time line: [lockStartTime]|----lockWindow----|----withdrawWindow----|[lockStartTime]|----lockWindow---|........
lockWindow = (14 * DAY_SECONDS) + lockWindowBuffer;
withdrawWindow = DAY_SECONDS/2;
lockStartTime = block.timestamp.add(withdrawWindow);
}
function getName() public pure returns(string memory){
return "mmVaultV2";
}
function balance() public view returns (uint256) {
return token.balanceOf(address(this)).add(IController(controller).balanceOf(address(token)));
}
function setMin(uint256 _min) external onlyGovernance{
min = _min;
}
function setGovernance(address _governance) public onlyGovernance{
governance = _governance;
}
function setTimelock(address _timelock) public {
require(msg.sender == timelock, "!timelock");
timelock = _timelock;
}
function setController(address _controller) public {
require(msg.sender == timelock, "!timelock");
controller = _controller;
}
function setLoanFee(uint256 _loanFee) public onlyGovernance{
loanFee = _loanFee;
}
function setLoanEnabled(bool _loanEnabled) public onlyGovernance{
loanEnabled = _loanEnabled;
}
function addKeeper(address _keeper) public onlyGovernance{
keepers[_keeper] = true;
}
function removeKeeper(address _keeper) public onlyGovernance{
keepers[_keeper] = false;
}
function addReentrancyWhitelist(address _whitelist) public onlyGovernance{
reentrancyWhitelist[_whitelist] = true;
}
function removeReentrancyWhitelist(address _whitelist) public onlyGovernance{
reentrancyWhitelist[_whitelist] = false;
}
function setLockWindow(uint256 _lockWindow) public onlyGovernance {
lockWindow = _lockWindow.add(lockWindowBuffer);
}
function setWithdrawWindow(uint256 _withdrawWindow) public onlyGovernance {
withdrawWindow = _withdrawWindow;
}
function setLockEnabled(bool _enabled) public onlyGovernance {
lockEnabled = _enabled;
}
function setEarnOnceEnabled(bool _earnOnce) public onlyGovernance {
earnOnceEnabled = _earnOnce;
}
function resetLockStartTime(uint256 _lockStartTime) public onlyGovernance{
require(lockEnabled, "!lockEnabled");
uint256 withdrawEndTime = getLockCycleEndTime();
require(block.timestamp >= withdrawEndTime, "Last lock cycle not end");
require(_lockStartTime > block.timestamp, "!_lockStartTime");
lockStartTime = _lockStartTime;
}
function getLockCycleEndTime() public view returns (uint256){
return lockStartTime.add(lockWindow).add(withdrawWindow);
}
function withdrawableWithoutLock(uint256 _shares) public view returns(bool){
uint256 _withdrawAmount = (balance().mul(_shares)).div(totalSupply());
return _withdrawAmount <= token.balanceOf(address(this));
}
// Custom logic in here for how much the vaults allows to be borrowed
// Sets minimum required on-hand to keep small withdrawals cheap
function available() public view returns (uint256) {
return token.balanceOf(address(this)).mul(min).div(max);
}
function earn() public nonReentrant onlyKeepers canEarn {
uint256 _bal = available();
token.safeTransfer(controller, _bal);
IController(controller).earn(address(token), _bal);
}
function depositAll() external {
deposit(token.balanceOf(msg.sender));
}
function deposit(uint256 _approveAmount, uint256 _amount, uint256 _deadline, uint8 v, bytes32 r, bytes32 s) public {
require(_approveAmount >= _amount, "!_approveAmount");
IERC2612(address(token)).permit(msg.sender, address(this), _approveAmount, _deadline, v, r, s);
deposit(_amount);
}
function deposit(uint256 _amount) public nonReentrant {
uint256 _pool = balance();
uint256 _before = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), _amount);
uint256 _after = token.balanceOf(address(this));
_amount = _after.sub(_before); // Additional check for deflationary tokens
uint256 shares = 0;
if (totalSupply() == 0) {
shares = _amount;
} else {
shares = (_amount.mul(totalSupply())).div(_pool);
}
_mint(msg.sender, shares);
}
function withdrawAll() external {
withdraw(balanceOf(msg.sender));
}
// Used to swap any borrowed reserve over the debt limit to liquidate to 'token'
function harvest(address reserve, uint256 amount) external nonReentrant {
require(msg.sender == controller, "!controller");
require(reserve != address(token), "token");
IERC20(reserve).safeTransfer(controller, amount);
}
// No rebalance implementation for lower fees and faster swaps
function withdraw(uint256 _shares) public nonReentrant canWithdraw(_shares) {
uint256 r = (balance().mul(_shares)).div(totalSupply());
_burn(msg.sender, _shares);
// Check balance
uint256 b = token.balanceOf(address(this));
if (b < r) {
uint256 _withdraw = r.sub(b);
IController(controller).withdraw(address(token), _withdraw);
uint256 _after = token.balanceOf(address(this));
uint256 _diff = _after.sub(b);
if (_diff < _withdraw) {
r = b.add(_diff);
}
}
token.safeTransfer(msg.sender, r);
}
function getRatio() public view returns (uint256) {
return balance().mul(1e18).div(totalSupply());
}
function flashLoan(address _receiver, uint256 _amount, bytes memory _data) public nonReentrantWithWhitelist discountCHI{
require(loanEnabled == true, "!loanEnabled");
require(_amount > 0, "amount too small!");
uint256 beforeBalance = token.balanceOf(address(this));
require(beforeBalance > _amount, "balance not enough!");
//loanFee
uint256 _fee = _amount.mul(loanFee).div(loanFeeMax);
require(_fee > 0, "fee too small");
//transfer token to _receiver
token.safeTransfer(_receiver, _amount);
//execute user's logic
IFlashLoanReceiver(_receiver).mushroomsFlashloan(address(token), _amount, _fee, _data);
uint256 afterBalance = token.balanceOf(address(this));
require(afterBalance == beforeBalance.add(_fee), "payback amount incorrect!");
emit FlashLoan(address(token), _receiver, _amount, _fee);
}
} | contract MMVault is ReentrancyGuard, ERC20Permit {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
IERC20 public token;
IChiToken public constant chi = IChiToken(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c);
uint256 public min = 9500;
uint256 public constant max = 10000;
uint256 public loanFee = 1;
uint256 public loanFeeMax = 10000;
bool public loanEnabled = true;
address public governance;
address public timelock;
address public controller;
mapping(address => bool) public keepers;
mapping(address => bool) public reentrancyWhitelist;
uint256 public DAY_SECONDS = 86400;
uint256 public lockWindowBuffer = DAY_SECONDS/4;
uint256 public lockStartTime;
uint256 public lockWindow;
uint256 public withdrawWindow;
uint256 public earnedTimestamp;
bool public lockEnabled = false;
bool public earnOnceEnabled = false;
event FlashLoan(address _token, address _receiver, uint256 _amount, uint256 _loanFee);
modifier discountCHI() {
uint256 gasStart = gasleft();
_;
uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length;
if(chi.balanceOf(msg.sender) > 0) {
chi.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41947);
}
}
modifier onlyKeepers {
require(
keepers[msg.sender] ||
msg.sender == governance,
"!keepers"
);
_;
}
modifier onlyGovernance(){
require(msg.sender == governance, "!governance");
_;
}
modifier canEarn {
if(lockEnabled){
require(
block.timestamp > lockStartTime,
"!earnTime"
);
if(earnOnceEnabled){
require(
block.timestamp.sub(earnedTimestamp) > lockWindow,
"!earnTwice");
if(earnedTimestamp != 0){
lockStartTime = getLockCycleEndTime();
}
earnedTimestamp = block.timestamp;
}
}
_;
}
modifier canWithdraw(uint256 _shares) {
if(lockEnabled){
//withdraw locker not work when withdraw amount less than available balance
if(!withdrawableWithoutLock(_shares)){
uint256 withdrawStartTimestamp = lockStartTime.add(lockWindow);
require(
block.timestamp > withdrawStartTimestamp &&
block.timestamp < withdrawStartTimestamp.add(withdrawWindow),
"!withdrawTime"
);
}
}
_;
}
modifier nonReentrantWithWhitelist() {
// only check if NOT in whitelist
if (!reentrancyWhitelist[msg.sender]){
// On the first call to nonReentrantWithWhitelist, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrantWithWhitelist after this point will fail
_status = _ENTERED;
}
_;
if (!reentrancyWhitelist[msg.sender]){
// By storing the original value once again, a refund is triggered (see https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
constructor(address _token, address _governance, address _timelock, address _controller)
public
ERC20Permit(
string(abi.encodePacked("mushrooming ", ERC20(_token).name())),
string(abi.encodePacked("m", ERC20(_token).symbol()))
)
{
_setupDecimals(ERC20(_token).decimals());
token = IERC20(_token);
governance = _governance;
timelock = _timelock;
controller = _controller;
//time line: [lockStartTime]|----lockWindow----|----withdrawWindow----|[lockStartTime]|----lockWindow---|........
lockWindow = (14 * DAY_SECONDS) + lockWindowBuffer;
withdrawWindow = DAY_SECONDS/2;
lockStartTime = block.timestamp.add(withdrawWindow);
}
function getName() public pure returns(string memory){
return "mmVaultV2";
}
function balance() public view returns (uint256) {
return token.balanceOf(address(this)).add(IController(controller).balanceOf(address(token)));
}
function setMin(uint256 _min) external onlyGovernance{
min = _min;
}
function setGovernance(address _governance) public onlyGovernance{
governance = _governance;
}
function setTimelock(address _timelock) public {
require(msg.sender == timelock, "!timelock");
timelock = _timelock;
}
function setController(address _controller) public {
require(msg.sender == timelock, "!timelock");
controller = _controller;
}
function setLoanFee(uint256 _loanFee) public onlyGovernance{
loanFee = _loanFee;
}
function setLoanEnabled(bool _loanEnabled) public onlyGovernance{
loanEnabled = _loanEnabled;
}
function addKeeper(address _keeper) public onlyGovernance{
keepers[_keeper] = true;
}
function removeKeeper(address _keeper) public onlyGovernance{
keepers[_keeper] = false;
}
function addReentrancyWhitelist(address _whitelist) public onlyGovernance{
reentrancyWhitelist[_whitelist] = true;
}
function removeReentrancyWhitelist(address _whitelist) public onlyGovernance{
reentrancyWhitelist[_whitelist] = false;
}
function setLockWindow(uint256 _lockWindow) public onlyGovernance {
lockWindow = _lockWindow.add(lockWindowBuffer);
}
function setWithdrawWindow(uint256 _withdrawWindow) public onlyGovernance {
withdrawWindow = _withdrawWindow;
}
function setLockEnabled(bool _enabled) public onlyGovernance {
lockEnabled = _enabled;
}
function setEarnOnceEnabled(bool _earnOnce) public onlyGovernance {
earnOnceEnabled = _earnOnce;
}
function resetLockStartTime(uint256 _lockStartTime) public onlyGovernance{
require(lockEnabled, "!lockEnabled");
uint256 withdrawEndTime = getLockCycleEndTime();
require(block.timestamp >= withdrawEndTime, "Last lock cycle not end");
require(_lockStartTime > block.timestamp, "!_lockStartTime");
lockStartTime = _lockStartTime;
}
function getLockCycleEndTime() public view returns (uint256){
return lockStartTime.add(lockWindow).add(withdrawWindow);
}
function withdrawableWithoutLock(uint256 _shares) public view returns(bool){
uint256 _withdrawAmount = (balance().mul(_shares)).div(totalSupply());
return _withdrawAmount <= token.balanceOf(address(this));
}
// Custom logic in here for how much the vaults allows to be borrowed
// Sets minimum required on-hand to keep small withdrawals cheap
function available() public view returns (uint256) {
return token.balanceOf(address(this)).mul(min).div(max);
}
function earn() public nonReentrant onlyKeepers canEarn {
uint256 _bal = available();
token.safeTransfer(controller, _bal);
IController(controller).earn(address(token), _bal);
}
function depositAll() external {
deposit(token.balanceOf(msg.sender));
}
function deposit(uint256 _approveAmount, uint256 _amount, uint256 _deadline, uint8 v, bytes32 r, bytes32 s) public {
require(_approveAmount >= _amount, "!_approveAmount");
IERC2612(address(token)).permit(msg.sender, address(this), _approveAmount, _deadline, v, r, s);
deposit(_amount);
}
function deposit(uint256 _amount) public nonReentrant {
uint256 _pool = balance();
uint256 _before = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), _amount);
uint256 _after = token.balanceOf(address(this));
_amount = _after.sub(_before); // Additional check for deflationary tokens
uint256 shares = 0;
if (totalSupply() == 0) {
shares = _amount;
} else {
shares = (_amount.mul(totalSupply())).div(_pool);
}
_mint(msg.sender, shares);
}
function withdrawAll() external {
withdraw(balanceOf(msg.sender));
}
// Used to swap any borrowed reserve over the debt limit to liquidate to 'token'
function harvest(address reserve, uint256 amount) external nonReentrant {
require(msg.sender == controller, "!controller");
require(reserve != address(token), "token");
IERC20(reserve).safeTransfer(controller, amount);
}
// No rebalance implementation for lower fees and faster swaps
function withdraw(uint256 _shares) public nonReentrant canWithdraw(_shares) {
uint256 r = (balance().mul(_shares)).div(totalSupply());
_burn(msg.sender, _shares);
// Check balance
uint256 b = token.balanceOf(address(this));
if (b < r) {
uint256 _withdraw = r.sub(b);
IController(controller).withdraw(address(token), _withdraw);
uint256 _after = token.balanceOf(address(this));
uint256 _diff = _after.sub(b);
if (_diff < _withdraw) {
r = b.add(_diff);
}
}
token.safeTransfer(msg.sender, r);
}
function getRatio() public view returns (uint256) {
return balance().mul(1e18).div(totalSupply());
}
function flashLoan(address _receiver, uint256 _amount, bytes memory _data) public nonReentrantWithWhitelist discountCHI{
require(loanEnabled == true, "!loanEnabled");
require(_amount > 0, "amount too small!");
uint256 beforeBalance = token.balanceOf(address(this));
require(beforeBalance > _amount, "balance not enough!");
//loanFee
uint256 _fee = _amount.mul(loanFee).div(loanFeeMax);
require(_fee > 0, "fee too small");
//transfer token to _receiver
token.safeTransfer(_receiver, _amount);
//execute user's logic
IFlashLoanReceiver(_receiver).mushroomsFlashloan(address(token), _amount, _fee, _data);
uint256 afterBalance = token.balanceOf(address(this));
require(afterBalance == beforeBalance.add(_fee), "payback amount incorrect!");
emit FlashLoan(address(token), _receiver, _amount, _fee);
}
} | 59,563 |
5 | // ============================== Ops Constants ================================ |
uint256 private constant _DEFAULT_COLLAT_TARGET_MARGIN = 0.02 ether;
uint256 private constant _DEFAULT_COLLAT_MAX_MARGIN = 0.005 ether;
uint256 private constant _LIQUIDATION_WARNING_THRESHOLD = 0.01 ether;
uint256 private constant _BPS_WAD_RATIO = 1e14;
uint256 private constant _COLLATERAL_RATIO_PRECISION = 1 ether;
uint16 private constant _referral = 0;
|
uint256 private constant _DEFAULT_COLLAT_TARGET_MARGIN = 0.02 ether;
uint256 private constant _DEFAULT_COLLAT_MAX_MARGIN = 0.005 ether;
uint256 private constant _LIQUIDATION_WARNING_THRESHOLD = 0.01 ether;
uint256 private constant _BPS_WAD_RATIO = 1e14;
uint256 private constant _COLLATERAL_RATIO_PRECISION = 1 ether;
uint16 private constant _referral = 0;
| 19,758 |
47 | // Validate the caller is already part of the whitelist. | require(
whitelistedAddresses[_addressToRemove],
"Error: Sender is not whitelisted"
);
| require(
whitelistedAddresses[_addressToRemove],
"Error: Sender is not whitelisted"
);
| 15,124 |
333 | // this is a transfer or burn event, make sure it is at least 1 block later from deposit to prevent flash loan this will cause a small issue that if a user minted some tokens before, and then mint some more and withdraw (burn) or transfer previously minted tokens in the same block, this will fail. But it should not be a issue for majority of users and it does prevent flash loan | require(block.number > dt[_from], "!block");
| require(block.number > dt[_from], "!block");
| 69,627 |
41 | // / | contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/**
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
| contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/**
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
| 3,764 |
21 | // multiply by 4/3 rounded up | uint256 encodedLen = 4 * ((len + 2) / 3);
| uint256 encodedLen = 4 * ((len + 2) / 3);
| 3,396 |
36 | // Ensure that the buyer has already started the transaction | require(buyerStatus[product_id][address(msg.sender)] == PurchaseState.Confirmed);
| require(buyerStatus[product_id][address(msg.sender)] == PurchaseState.Confirmed);
| 1,210 |
80 | // isClosed / | function isClosed() public view returns (bool) {
return currentTime() > endAt || closed;
}
| function isClosed() public view returns (bool) {
return currentTime() > endAt || closed;
}
| 29,362 |
14 | // Returns the key of the median element in the list. list A storage pointer to the underlying list.return The key of the median element in the list. / | function getMedian(SortedLinkedListWithMedian.List storage list) external view returns (address) {
return toAddress(list.getMedian());
}
| function getMedian(SortedLinkedListWithMedian.List storage list) external view returns (address) {
return toAddress(list.getMedian());
}
| 19,259 |
30 | // Update entry | _heap.entries[newInd] = can;
| _heap.entries[newInd] = can;
| 35,839 |
1 | // Owner sets guard or guard modifies guard/The newGuard can not be zero address/ Throws if `tokenId` is not valid NFT/tokenId The NFT to get the guard address for/newGuard The new guard address of the NFT | function changeGuard(uint256 tokenId, address newGuard) public virtual{
_updateGuard(tokenId, newGuard, false);
}
| function changeGuard(uint256 tokenId, address newGuard) public virtual{
_updateGuard(tokenId, newGuard, false);
}
| 23,780 |
157 | // Event fired when a digital media's collection is | event DigitalMediaCollectionCreateEvent(
uint256 id,
address storeContractAddress,
address creator,
string metadataPath);
| event DigitalMediaCollectionCreateEvent(
uint256 id,
address storeContractAddress,
address creator,
string metadataPath);
| 6,644 |
485 | // Sets the stored oracle and LINK token contracts with the addresses resolved by ENS Accounts for subnodes having different resolvers ensAddress The address of the ENS contract node The ENS node hash / | function useChainlinkWithENS(address ensAddress, bytes32 node) internal {
s_ens = ENSInterface(ensAddress);
s_ensNode = node;
bytes32 linkSubnode = keccak256(abi.encodePacked(s_ensNode, ENS_TOKEN_SUBNAME));
ENSResolver resolver = ENSResolver(s_ens.resolver(linkSubnode));
setChainlinkToken(resolver.addr(linkSubnode));
updateChainlinkOracleWithENS();
}
| function useChainlinkWithENS(address ensAddress, bytes32 node) internal {
s_ens = ENSInterface(ensAddress);
s_ensNode = node;
bytes32 linkSubnode = keccak256(abi.encodePacked(s_ensNode, ENS_TOKEN_SUBNAME));
ENSResolver resolver = ENSResolver(s_ens.resolver(linkSubnode));
setChainlinkToken(resolver.addr(linkSubnode));
updateChainlinkOracleWithENS();
}
| 12,821 |
29 | // Lets an account with MINTER_ROLE mint an NFT./ add onlyRole(MINTER_ROLE) after external in mintTo function | function mintTo(address _to, string calldata _uri)
external
returns (uint256)
| function mintTo(address _to, string calldata _uri)
external
returns (uint256)
| 9,537 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.