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 |
|---|---|---|---|---|
1 | // Informs third-party platforms that NFT metadata should be updated/This event comes from https:eips.ethereum.org/EIPS/eip-4906/tokenId the id of the token that should have its metadata updated | event MetadataUpdate(uint256 tokenId);
function initialize(string memory nftName, string memory nftSymbol) external; // initializer;
function triggerMetadataUpdate(uint256 tokenId) external;
| event MetadataUpdate(uint256 tokenId);
function initialize(string memory nftName, string memory nftSymbol) external; // initializer;
function triggerMetadataUpdate(uint256 tokenId) external;
| 34,060 |
19 | // Tells the address of the current implementation return address of the current implementation/ | function implementation() public view returns (address) {
return _implementation;
}
| function implementation() public view returns (address) {
return _implementation;
}
| 12,115 |
32 | // See {ICreatorCore-setMintPermissions}. / | function setMintPermissions(address extension, address permissions)
external
override
adminRequired
{
_setMintPermissions(extension, permissions);
}
| function setMintPermissions(address extension, address permissions)
external
override
adminRequired
{
_setMintPermissions(extension, permissions);
}
| 17,161 |
10 | // perform Export / | public isValidPerformer(_batchNo,'EXPORTER') returns(bool) {
/* Call Storage Contract */
bool status = supplyChainStorage.setExporterData(_batchNo, _quantity, _destinationAddress, _shipName,_shipNo, _estimateDateTime,_exporterId);
emit DoneExporting(msg.sender, _batchNo);
return (status);
}
| public isValidPerformer(_batchNo,'EXPORTER') returns(bool) {
/* Call Storage Contract */
bool status = supplyChainStorage.setExporterData(_batchNo, _quantity, _destinationAddress, _shipName,_shipNo, _estimateDateTime,_exporterId);
emit DoneExporting(msg.sender, _batchNo);
return (status);
}
| 4,771 |
171 | // Internal Functions |
function _transferOwnership(
address __owner
)
|
function _transferOwnership(
address __owner
)
| 22,045 |
28 | // Internal object that represents a token | struct Token {
address tokenAddress;
bool hasTransferFee;
int256 decimals;
TokenType tokenType;
uint256 maxCollateralBalance;
}
| struct Token {
address tokenAddress;
bool hasTransferFee;
int256 decimals;
TokenType tokenType;
uint256 maxCollateralBalance;
}
| 44,022 |
3 | // Event for token purchase logging purchaser who paid for the tokens beneficiary who got the tokens value weis paid for purchase tokenId the token id purchased / | event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 tokenId
);
| event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 tokenId
);
| 17,888 |
15 | // First of all, we need to see if the operator has grant delegated. If not, we don't need to bother about checking grantee or managed grantee and we just return false. | if (!hasGrantDelegated(self, operator)) {
return false;
}
| if (!hasGrantDelegated(self, operator)) {
return false;
}
| 25,268 |
67 | // Restrict by the allowance that `sender` has to this contract NOTE: No need for allowance check if `sender` is this contract | if (sender != address(this)) {
availableShares = Math.min(availableShares, vaults[id].allowance(sender, address(this)));
}
| if (sender != address(this)) {
availableShares = Math.min(availableShares, vaults[id].allowance(sender, address(this)));
}
| 85,594 |
26 | // mint a specific `amount` of tokens to the `target` | function _mint(address _target, uint256 _amount) internal {
uint256 __gonsPerFragment = _gonsPerFragment;
// the gonbalances of the sender is in gons, therefore we must multiply the deposit amount, which is in fragments, by gonsperfragment
_gonBalances[_target] += _amount * __gonsPerFragment;
// total supply is in fragments, and so we add amount
_totalSupply += _amount;
// and totalgons of course is in gons, and so we multiply amount by gonsperfragment to get the amount of gons we must add to totalGons
_totalGons += _amount * __gonsPerFragment;
// emit both a mint and transfer event
emit Transfer(address(0), _target, _amount);
emit Mint(_target, _amount);
}
| function _mint(address _target, uint256 _amount) internal {
uint256 __gonsPerFragment = _gonsPerFragment;
// the gonbalances of the sender is in gons, therefore we must multiply the deposit amount, which is in fragments, by gonsperfragment
_gonBalances[_target] += _amount * __gonsPerFragment;
// total supply is in fragments, and so we add amount
_totalSupply += _amount;
// and totalgons of course is in gons, and so we multiply amount by gonsperfragment to get the amount of gons we must add to totalGons
_totalGons += _amount * __gonsPerFragment;
// emit both a mint and transfer event
emit Transfer(address(0), _target, _amount);
emit Mint(_target, _amount);
}
| 7,697 |
14 | // Transfers a specific NFT (`tokenId`) from one account (`from`) toanother (`to`). Requirements:- `from`, `to` cannot be zero.- `tokenId` must be owned by `from`.- If the caller is not `from`, it must be have been allowed to move thisNFT by either `approve` or `setApproveForAll`. / | function safeTransferFrom(address from, address to, uint256 tokenId) public;
| function safeTransferFrom(address from, address to, uint256 tokenId) public;
| 10,515 |
157 | // Deposits a given amount of StakingToken from sender _amount Units of StakingToken / | function _stakeRaw(address _beneficiary, uint256 _amount) internal nonReentrant {
_rawBalances[_beneficiary] += _amount;
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
}
| function _stakeRaw(address _beneficiary, uint256 _amount) internal nonReentrant {
_rawBalances[_beneficiary] += _amount;
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
}
| 49,989 |
106 | // returns bool isProfit, uint profitOrLoss the position's profit/loss denominated in positionToken | function getProfitOrLoss(
address positionTokenAddress,
address loanTokenAddress,
uint positionTokenAmount,
uint loanTokenAmount)
public
view
returns (bool isProfit, uint profitOrLoss)
| function getProfitOrLoss(
address positionTokenAddress,
address loanTokenAddress,
uint positionTokenAmount,
uint loanTokenAmount)
public
view
returns (bool isProfit, uint profitOrLoss)
| 4,802 |
0 | // Grammer: using A(library) for B(type, struct data type) | using Counters for Counters.Counter;
Counters.Counter private tokenCount;
string public baseURI;
| using Counters for Counters.Counter;
Counters.Counter private tokenCount;
string public baseURI;
| 28,825 |
4,644 | // 2323 | entry "sealskinned" : ENG_ADJECTIVE
| entry "sealskinned" : ENG_ADJECTIVE
| 18,935 |
58 | // Returns one of the accounts that have `role`. `index` must be a | * value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
| * value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
| 37,092 |
3 | // Make sure our discount algorithm never returns a higher rate than the base. | require(result <= Consts.DISCOUNT_RATE_BASE(), "DISCOUNT_ERROR");
| require(result <= Consts.DISCOUNT_RATE_BASE(), "DISCOUNT_ERROR");
| 46,903 |
95 | // Stores the bridged token of a message sent to the AMB bridge._messageId of the message sent to the bridge._token bridged token address./ | function setMessageToken(bytes32 _messageId, address _token) internal {
addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))] = _token;
}
| function setMessageToken(bytes32 _messageId, address _token) internal {
addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))] = _token;
}
| 20,986 |
64 | // claims any outstanding rewards. / | function claimRewards() public virtual {
address sender = _msgSender();
require(sender != _dividendWallet
&& sender != _dev
&& sender != _team
&& sender != _donation
&& sender != _marketing
&& sender != _liquidity
&& sender != _arb
, "Unauthorized to claim rewards"
);
uint256 rewards = _getRewardsForAccount(sender);
require(rewards > 0, "No rewards to collect.");
//security check - can only result due to extremely small rounding errors.
if (rewards > balanceOf(_dividendWallet)) {
rewards = balanceOf(_dividendWallet);
}
_dividendsClaimed[sender] += rewards;
_totalDividendsClaimed += rewards;
super._transfer(_dividendWallet, sender, rewards);
}
| function claimRewards() public virtual {
address sender = _msgSender();
require(sender != _dividendWallet
&& sender != _dev
&& sender != _team
&& sender != _donation
&& sender != _marketing
&& sender != _liquidity
&& sender != _arb
, "Unauthorized to claim rewards"
);
uint256 rewards = _getRewardsForAccount(sender);
require(rewards > 0, "No rewards to collect.");
//security check - can only result due to extremely small rounding errors.
if (rewards > balanceOf(_dividendWallet)) {
rewards = balanceOf(_dividendWallet);
}
_dividendsClaimed[sender] += rewards;
_totalDividendsClaimed += rewards;
super._transfer(_dividendWallet, sender, rewards);
}
| 8,436 |
19 | // Variable of token frozen rules for YAC team members. | uint public unlockat;
| uint public unlockat;
| 60,330 |
643 | // Calculate a YieldSpace pool invariant according to the whitepaper / | function invariant(uint128 baseReserves, uint128 fyTokenReserves, uint256 totalSupply, uint128 timeTillMaturity, int128 ts)
public pure returns(uint128)
| function invariant(uint128 baseReserves, uint128 fyTokenReserves, uint256 totalSupply, uint128 timeTillMaturity, int128 ts)
public pure returns(uint128)
| 47,334 |
154 | // Allows a user to create a game from Credits. Gas Cost: 61k - 22k: tx overhead - 26k: see _createNewGame() -3k: event -2k: curMaxBet() -2k: 1 event: CreditsUsed -5k: update credits[user] -1k: SLOAD, execution | function betWithCredits(uint64 _bet)
public
| function betWithCredits(uint64 _bet)
public
| 57,099 |
8 | // 要求拥有管理员权限 | modifyUserInfo(_name, _stuNo, _grade, _identity, ModifiedUser);
iLog.addLog_User("User", "Superadmin_Modify_UserInfo", msg.sender, users[msg.sender].Name, true);
return true;
| modifyUserInfo(_name, _stuNo, _grade, _identity, ModifiedUser);
iLog.addLog_User("User", "Superadmin_Modify_UserInfo", msg.sender, users[msg.sender].Name, true);
return true;
| 50,450 |
31 | // solhint-disable-next-line avoid-low-level-calls | (bool success, bytes memory returndata) = target.call{ value: value }(data);
| (bool success, bytes memory returndata) = target.call{ value: value }(data);
| 1,370 |
4 | // Mask for the 128 least significant bits | uint256 private constant MASK_128_BITS = 0xffffffffffffffffffffffffffffffff;
| uint256 private constant MASK_128_BITS = 0xffffffffffffffffffffffffffffffff;
| 29,714 |
93 | // The supplier reedems the BNDESToken by transfering the tokens to a specific address,called Redemption address.By default, the redemption address is the address of the owner.The owner can change the redemption address using this function. rs new Redemption address/ | function setRedemptionAddress(address rs) onlyOwner public {
redemptionAddress = rs;
}
| function setRedemptionAddress(address rs) onlyOwner public {
redemptionAddress = rs;
}
| 40,102 |
141 | // Query if a contract implements an interface _interfaceIDThe interface identifier, as specified in ERC-165return `true` if the contract implements `_interfaceID` and / | function supportsInterface(bytes4 _interfaceID) public override virtual pure returns (bool) {
if (_interfaceID == type(IERC1155Metadata).interfaceId) {
return true;
}
return super.supportsInterface(_interfaceID);
}
| function supportsInterface(bytes4 _interfaceID) public override virtual pure returns (bool) {
if (_interfaceID == type(IERC1155Metadata).interfaceId) {
return true;
}
return super.supportsInterface(_interfaceID);
}
| 10,399 |
38 | // Update delegation params | pool.indexingRewardCut = _indexingRewardCut;
pool.queryFeeCut = _queryFeeCut;
pool.cooldownBlocks = _cooldownBlocks;
pool.updatedAtBlock = block.number;
emit DelegationParametersUpdated(
indexer,
_indexingRewardCut,
_queryFeeCut,
_cooldownBlocks
| pool.indexingRewardCut = _indexingRewardCut;
pool.queryFeeCut = _queryFeeCut;
pool.cooldownBlocks = _cooldownBlocks;
pool.updatedAtBlock = block.number;
emit DelegationParametersUpdated(
indexer,
_indexingRewardCut,
_queryFeeCut,
_cooldownBlocks
| 19,622 |
287 | // Burn liquidity | (uint256 owed0, uint256 owed1) = IUniswapV3Pool(pool).burn(
tickLower,
tickUpper,
liquidity
);
| (uint256 owed0, uint256 owed1) = IUniswapV3Pool(pool).burn(
tickLower,
tickUpper,
liquidity
);
| 15,243 |
379 | // ctor | constructor () public {
}
| constructor () public {
}
| 41,446 |
18 | // if NFT was created by our factory contract | if (
factoryCreatedTokens[_nftCollectionAddress] > DeNftConstants.DENFT_TYPE_THIRDPARTY &&
| if (
factoryCreatedTokens[_nftCollectionAddress] > DeNftConstants.DENFT_TYPE_THIRDPARTY &&
| 7,957 |
1 | // slither-disable-next-line unused-return | deployedAddress_.safeNativeTransfer(msg.value);
| deployedAddress_.safeNativeTransfer(msg.value);
| 31,236 |
23 | // set shamapass address | function setShamaPassAddress(address _address) public onlyOwner {
SHAMAPASS_ADDRESS = _address;
}
| function setShamaPassAddress(address _address) public onlyOwner {
SHAMAPASS_ADDRESS = _address;
}
| 35,573 |
28 | // decider => true if this address is a decider | mapping(address => bool) public isDecider;
| mapping(address => bool) public isDecider;
| 36,627 |
8 | // Fallback to centralised URI | return string(abi.encodePacked(baseURI(), address(this), '/', tokenId.toString()));
| return string(abi.encodePacked(baseURI(), address(this), '/', tokenId.toString()));
| 32,446 |
16 | // Process sweep transaction inputs and extract all information needed to perform deposit bookkeeping. | DepositSweepTxInputsInfo
memory inputsInfo = processDepositSweepTxInputs(
self,
DepositSweepTxInputsProcessingInfo(
sweepTx.inputVector,
resolvedMainUtxo,
vault
)
);
| DepositSweepTxInputsInfo
memory inputsInfo = processDepositSweepTxInputs(
self,
DepositSweepTxInputsProcessingInfo(
sweepTx.inputVector,
resolvedMainUtxo,
vault
)
);
| 10,988 |
172 | // Maximum number of priority request to clear during verifying the block/Cause deleting storage slots cost 5k gas per each slot it's unprofitable to clear too many slots/Value based on the assumption of ~750k gas cost of verifying and 5 used storage slots per PriorityOperation structure | uint64 constant MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY = 6;
| uint64 constant MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY = 6;
| 29,750 |
38 | // short case: marketSize - skew= (|longSize| + |shortSize|) - (longSize + shortSize)= 2-shortSize | newSideSize = newMarketSize.sub(newSkew);
| newSideSize = newMarketSize.sub(newSkew);
| 50,686 |
10 | // Replacement for Solidity's `transfer`: sends `amount` wei to`recipient`, forwarding all available gas and reverting on errors. of certain opcodes, possibly making contracts go over the 2300 gas limitimposed by `transfer`, making them unable to receive funds via | * `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
}
| * `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
}
| 20,135 |
122 | // Buy collateral from an auction at an increasing discount id ID of the auction to buy collateral from wad New bid submitted (as a WAD which has 18 decimals) / | function buyCollateral(uint256 id, uint256 wad) external {
require(both(bids[id].amountToSell > 0, bids[id].amountToRaise > 0), "IncreasingDiscountCollateralAuctionHouse/inexistent-auction");
require(both(wad > 0, wad >= minimumBid), "IncreasingDiscountCollateralAuctionHouse/invalid-bid");
// bound max amount offered in exchange for collateral (in case someone offers more than it's necessary)
uint256 adjustedBid = wad;
if (multiply(adjustedBid, RAY) > bids[id].amountToRaise) {
adjustedBid = addUint256(bids[id].amountToRaise / RAY, 1);
}
// Read the redemption price
lastReadRedemptionPrice = oracleRelayer.redemptionPrice();
// check that the collateral FSM doesn't return an invalid value
(uint256 collateralFsmPriceFeedValue, uint256 systemCoinPriceFeedValue) = getCollateralFSMAndFinalSystemCoinPrices(lastReadRedemptionPrice);
require(collateralFsmPriceFeedValue > 0, "IncreasingDiscountCollateralAuctionHouse/collateral-fsm-invalid-value");
// get the amount of collateral bought
uint256 boughtCollateral = getBoughtCollateral(
id, collateralFsmPriceFeedValue, getCollateralMedianPrice(), systemCoinPriceFeedValue, adjustedBid, updateCurrentDiscount(id)
);
// check that the calculated amount is greater than zero
require(boughtCollateral > 0, "IncreasingDiscountCollateralAuctionHouse/null-bought-amount");
// update the amount of collateral to sell
bids[id].amountToSell = subtract(bids[id].amountToSell, boughtCollateral);
// update remainingToRaise in case amountToSell is zero (everything has been sold)
uint256 remainingToRaise = (either(multiply(wad, RAY) >= bids[id].amountToRaise, bids[id].amountToSell == 0)) ?
bids[id].amountToRaise : subtract(bids[id].amountToRaise, multiply(wad, RAY));
// update leftover amount to raise in the bid struct
bids[id].amountToRaise = (multiply(adjustedBid, RAY) > bids[id].amountToRaise) ?
0 : subtract(bids[id].amountToRaise, multiply(adjustedBid, RAY));
// check that the remaining amount to raise is either zero or higher than RAY
require(
either(bids[id].amountToRaise == 0, bids[id].amountToRaise >= RAY),
"IncreasingDiscountCollateralAuctionHouse/invalid-left-to-raise"
);
// transfer the bid to the income recipient and the collateral to the bidder
safeEngine.transferInternalCoins(msg.sender, bids[id].auctionIncomeRecipient, multiply(adjustedBid, RAY));
safeEngine.transferCollateral(collateralType, address(this), msg.sender, boughtCollateral);
// Emit the buy event
emit BuyCollateral(id, adjustedBid, boughtCollateral);
// Remove coins from the liquidation buffer
bool soldAll = either(bids[id].amountToRaise == 0, bids[id].amountToSell == 0);
if (soldAll) {
liquidationEngine.removeCoinsFromAuction(remainingToRaise);
} else {
liquidationEngine.removeCoinsFromAuction(multiply(adjustedBid, RAY));
}
// If the auction raised the whole amount or all collateral was sold,
// send remaining collateral to the forgone receiver
if (soldAll) {
safeEngine.transferCollateral(collateralType, address(this), bids[id].forgoneCollateralReceiver, bids[id].amountToSell);
delete bids[id];
emit SettleAuction(id, bids[id].amountToSell);
}
}
| function buyCollateral(uint256 id, uint256 wad) external {
require(both(bids[id].amountToSell > 0, bids[id].amountToRaise > 0), "IncreasingDiscountCollateralAuctionHouse/inexistent-auction");
require(both(wad > 0, wad >= minimumBid), "IncreasingDiscountCollateralAuctionHouse/invalid-bid");
// bound max amount offered in exchange for collateral (in case someone offers more than it's necessary)
uint256 adjustedBid = wad;
if (multiply(adjustedBid, RAY) > bids[id].amountToRaise) {
adjustedBid = addUint256(bids[id].amountToRaise / RAY, 1);
}
// Read the redemption price
lastReadRedemptionPrice = oracleRelayer.redemptionPrice();
// check that the collateral FSM doesn't return an invalid value
(uint256 collateralFsmPriceFeedValue, uint256 systemCoinPriceFeedValue) = getCollateralFSMAndFinalSystemCoinPrices(lastReadRedemptionPrice);
require(collateralFsmPriceFeedValue > 0, "IncreasingDiscountCollateralAuctionHouse/collateral-fsm-invalid-value");
// get the amount of collateral bought
uint256 boughtCollateral = getBoughtCollateral(
id, collateralFsmPriceFeedValue, getCollateralMedianPrice(), systemCoinPriceFeedValue, adjustedBid, updateCurrentDiscount(id)
);
// check that the calculated amount is greater than zero
require(boughtCollateral > 0, "IncreasingDiscountCollateralAuctionHouse/null-bought-amount");
// update the amount of collateral to sell
bids[id].amountToSell = subtract(bids[id].amountToSell, boughtCollateral);
// update remainingToRaise in case amountToSell is zero (everything has been sold)
uint256 remainingToRaise = (either(multiply(wad, RAY) >= bids[id].amountToRaise, bids[id].amountToSell == 0)) ?
bids[id].amountToRaise : subtract(bids[id].amountToRaise, multiply(wad, RAY));
// update leftover amount to raise in the bid struct
bids[id].amountToRaise = (multiply(adjustedBid, RAY) > bids[id].amountToRaise) ?
0 : subtract(bids[id].amountToRaise, multiply(adjustedBid, RAY));
// check that the remaining amount to raise is either zero or higher than RAY
require(
either(bids[id].amountToRaise == 0, bids[id].amountToRaise >= RAY),
"IncreasingDiscountCollateralAuctionHouse/invalid-left-to-raise"
);
// transfer the bid to the income recipient and the collateral to the bidder
safeEngine.transferInternalCoins(msg.sender, bids[id].auctionIncomeRecipient, multiply(adjustedBid, RAY));
safeEngine.transferCollateral(collateralType, address(this), msg.sender, boughtCollateral);
// Emit the buy event
emit BuyCollateral(id, adjustedBid, boughtCollateral);
// Remove coins from the liquidation buffer
bool soldAll = either(bids[id].amountToRaise == 0, bids[id].amountToSell == 0);
if (soldAll) {
liquidationEngine.removeCoinsFromAuction(remainingToRaise);
} else {
liquidationEngine.removeCoinsFromAuction(multiply(adjustedBid, RAY));
}
// If the auction raised the whole amount or all collateral was sold,
// send remaining collateral to the forgone receiver
if (soldAll) {
safeEngine.transferCollateral(collateralType, address(this), bids[id].forgoneCollateralReceiver, bids[id].amountToSell);
delete bids[id];
emit SettleAuction(id, bids[id].amountToSell);
}
}
| 11,729 |
14 | // Execute multiple meta-transactions./mtxs The meta-transactions./signatures The signature by each respective `mtx.signer`./ return returnResults The ABI-encoded results of the underlying calls. | function batchExecuteMetaTransactions(
MetaTransactionData[] calldata mtxs,
bytes[] calldata signatures
)
external
payable
returns (bytes[] memory returnResults);
| function batchExecuteMetaTransactions(
MetaTransactionData[] calldata mtxs,
bytes[] calldata signatures
)
external
payable
returns (bytes[] memory returnResults);
| 28,004 |
73 | // Let everyone know that our pause state has changed. | emit PauseChanged(paused);
| emit PauseChanged(paused);
| 8,902 |
62 | // | contract BasketDAOBuyAndBurn {
using SafeERC20 for IERC20;
/// @dev Owner of the contract.
address public owner;
/// @dev Address of the KeeperDAO borrow proxy. This will be the
/// `msg.sender` for calls to the `helloCallback` function.
address public borrowProxy;
/// @dev Address of the KeeperDAO liquidity pool. This is will be the
/// address to which the `helloCallback` function must return all bororwed
/// assets (and all excess profits).
address payable public liquidityPool;
/// @dev This modifier restricts the caller of a function to the owner of
/// this contract.
modifier onlyOwner {
if (msg.sender == owner) {
_;
}
}
/// @dev This modifier restricts the caller of a function to the KeeperDAO
/// borrow proxy.
modifier onlyBorrowProxy {
if (msg.sender == borrowProxy) {
_;
}
}
constructor() public payable {
owner = msg.sender;
// Approve the Uniswap/Sushiswap router to spend this contract's WETH:
IERC20 weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // WETH
// Amount is:
// 0000000000000000000000000000000000000000ffffffffffffffffffffffff
// Approval for Sushiswap:
require(weth.approve(address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F),79228162514264337593543950335), 'weth approve failed');
require(IERC20(0xcee60cFa923170e4f8204AE08B4fA6A3F5656F3a).approve(address(0xF178C0b5Bb7e7aBF4e12A4838C7b7c5bA2C623c0),79228162514264337593543950335), 'approve failed');
// Blank approvals:
address[15] memory underlyings = [0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e,
0xc00e94Cb662C3520282E6f5717214004A7f26888,
0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F,
0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2,
0x408e41876cCCDC0F92210600ef50372656052a38,
0xdeFA4e8a7bcBA345F687a2f1456F5Edd9CE97202,
0xBBbbCA6A901c926F240b89EacB641d8Aec7AEafD,
0xba100000625a3754423978a60c9317c58a424e3D,
0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984,
0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9,
0x6B3595068778DD592e39A122f4f5a5cF09C90fE2,
0x2ba592F78dB6436527729929AAf6c908497cB200,
0x514910771AF9Ca656af840dff83E8264EcF986CA,
0xc5bDdf9843308380375a611c18B50Fb9341f502A,
0xE41d2489571d322189246DaFA5ebDe1F4699F498];
for (uint256 i = 0; i < underlyings.length; i++) {
IERC20(underlyings[i]).approve(address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F),79228162514264337593543950335);
IERC20(underlyings[i]).approve(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D),79228162514264337593543950335);
}
liquidityPool = payable(0x4F868C1aa37fCf307ab38D215382e88FCA6275E2); // new contract since June 2021
borrowProxy = 0x17a4C8F43cB407dD21f9885c5289E66E21bEcD9D; // new contract since June 2021
}
receive() external payable {
// Do nothing.
}
fallback() external payable { return; }
/// @dev Set the owner of this contract. This function can only be called by
/// the current owner.
///
/// @param _newOwner The new owner of this contract.
function setOwner(address _newOwner) external onlyOwner {
owner = _newOwner;
}
/// @dev Set the borrow proxy expected by this contract. This function can
/// only be called by the current owner.
///
/// @param _newBorrowProxy The new borrow proxy expected by this contract.
function setBorrowProxy(address _newBorrowProxy) external onlyOwner {
borrowProxy = _newBorrowProxy;
}
/// @dev Set the liquidity pool used by this contract. This function can
/// only be called by the current owner.
///
/// @param _newLiquidityPool The new liquidity pool used by this contract.
/// It must be a payable address, because this contract needs to be able to
/// return borrowed assets and profits to the liquidty pool.
function setLiquidityPool(address payable _newLiquidityPool) external onlyOwner {
liquidityPool = _newLiquidityPool;
}
/// Function that allows to withdraw ERC-20 tokens that are sitting on this contract to the owner address.
/// Uses safeTransfer to deal with non-standard tokens like USDT
function withdrawTokens(address _token) external onlyOwner {
IERC20(_token).safeTransfer(
msg.sender,
IERC20(_token).balanceOf(address(this))
);
}
/// Function that allows to withdraw ETH that are sitting on this contract to the owner address.
function withdrawEth(uint256 _amount) external onlyOwner {
assert(
address(this).balance >= _amount
);
assert(_amount > 0);
(bool success, ) = owner.call{value:_amount}("");
require(success, "Transfer failed.");
}
// Safety fallback, code from @kinzrec
function delegateCall(address to, bytes memory data) external payable onlyOwner {
(bool success, bytes memory retData) = to.delegatecall(data);
require(success, string(retData));
}
/// @dev The main function.
function safeFlashLoanBuyAndRedeem(uint256 _amountToBorrow, uint256 _minimalProfitability, uint256 _amountOfProfitToReturn, address[] memory underlyings, address[] memory routers) external onlyOwner returns(uint256)
{
// Check input:
require( _amountToBorrow > 0, "empty amount");
address _token = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // WETH
// Do flash-loan:
LiquidityPool(liquidityPool).borrow(
// Address of the token we want to borrow. Using this address
// means that we want to borrow ETH.
_token,
// The amount of WEI that we will borrow. We have to return at least
// more than this amount.
_amountToBorrow,
// Encode the callback into calldata. This will be used to call a
// function on this contract.
abi.encodeWithSelector(
// Function selector of the callback function.
this.buyAndRedeemCallback.selector,
// First parameter of the callback.
_amountToBorrow,
_amountOfProfitToReturn,
underlyings,
routers
)
);
// At this point the flash-loan is paid back...
// Ensure we are left with more WETH than before
IERC20 weth = IERC20(_token);
uint256 weth_balance = weth.balanceOf(address(this));
require(weth_balance >= _minimalProfitability, 'not profitable');
// Transfer profit to owner address.
bool sent = weth.transfer(owner, weth_balance);
require(sent, "Token transfer failed");
return weth_balance;
}
function buyAndRedeemCallback(
uint256 _amountBorrowed,
uint256 _amountOfProfitToReturn,
address[] memory underlyings,
address[] memory routers
) external onlyBorrowProxy {
/// We have now borrowed a certain amount of WETH
// Pay back flash loan
IERC20 weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
//uint256 weth_balance = weth.balanceOf(address(this));
// Buy BDI on Sushiswap
// From WETH to BDI
address[] memory path = new address[](2);
path[0] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // WETH
path[1] = 0x0309c98B1bffA350bcb3F9fB9780970CA32a5060; // BDI
// Swap _amountBorrowed WETH to any amount of BDI (we will check that this was profitable later)
IUniswapV2Router02(address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F)).swapExactTokensForTokens(_amountBorrowed, 0, path, address(this), block.timestamp + 15000);
uint256 bdi_balance = IBDITokenContract(0x0309c98B1bffA350bcb3F9fB9780970CA32a5060).balanceOf(address(this));
// Burn BDI into constituents
IBDITokenContract(0x0309c98B1bffA350bcb3F9fB9780970CA32a5060).burn(bdi_balance);
// Convert constituents into underlyings
// yvYFI - https://etherscan.io/address/0xE14d13d8B3b85aF791b2AADD661cDBd5E6097Db1
uint256 bal = IERC20(0xE14d13d8B3b85aF791b2AADD661cDBd5E6097Db1).balanceOf(address(this));
(0xE14d13d8B3b85aF791b2AADD661cDBd5E6097Db1).call(abi.encodeWithSignature("withdraw(uint256)",bal));
// Now we have YFI: https://etherscan.io/token/0x0bc529c00c6401aef6d220be8c6ea1667f6ad93e
// cCOMP - 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4
bal = IERC20(0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4).balanceOf(address(this));
(0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4).call(abi.encodeWithSignature("redeem(uint256)",bal));
// Now we have COMP: 0xc00e94Cb662C3520282E6f5717214004A7f26888
// yvSNX - 0xF29AE508698bDeF169B89834F76704C3B205aedf
bal = IERC20(0xF29AE508698bDeF169B89834F76704C3B205aedf).balanceOf(address(this));
(0xF29AE508698bDeF169B89834F76704C3B205aedf).call(abi.encodeWithSignature("withdraw(uint256)",bal));
// Now we have SNX: 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F
// yvUNI: 0xFBEB78a723b8087fD2ea7Ef1afEc93d35E8Bed42
bal = IERC20(0xFBEB78a723b8087fD2ea7Ef1afEc93d35E8Bed42).balanceOf(address(this));
(0xFBEB78a723b8087fD2ea7Ef1afEc93d35E8Bed42).call(abi.encodeWithSignature("withdraw(uint256)",bal));
// Now we have UNI: 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984
// xSUSHI: 0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272
// can be directly swapped on Sushiswap, alternatively, could un-wrap First
bal = IERC20(0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272).balanceOf(address(this));
(0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272).call(abi.encodeWithSignature("leave(uint256)",bal));
// Now have Sushi 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2
// yvCurve-Link: 0xf2db9a7c0ACd427A680D640F02d90f6186E71725
bal = IERC20(0xf2db9a7c0ACd427A680D640F02d90f6186E71725).balanceOf(address(this));
(0xf2db9a7c0ACd427A680D640F02d90f6186E71725).call(abi.encodeWithSignature("withdraw(uint256)",bal));
// Now we have linkCRV: 0xcee60cfa923170e4f8204ae08b4fa6a3f5656f3a
bal = IERC20(0xcee60cFa923170e4f8204AE08B4fA6A3F5656F3a).balanceOf(address(this));
// Moved this to constructor:
//require(IERC20(0xcee60cFa923170e4f8204AE08B4fA6A3F5656F3a).approve(address(0xF178C0b5Bb7e7aBF4e12A4838C7b7c5bA2C623c0),79228162514264337593543950335), 'approve failed');
(0xF178C0b5Bb7e7aBF4e12A4838C7b7c5bA2C623c0).call(abi.encodeWithSignature("remove_liquidity_one_coin(uint256,int128,uint256)",bal,0,0)); // second 0 means we want to withdraw link
// Now we have LINK: 0x514910771AF9Ca656af840dff83E8264EcF986CA
// yvBOOST 0x9d409a0A012CFbA9B15F6D4B36Ac57A46966Ab9a
bal = IERC20(0x9d409a0A012CFbA9B15F6D4B36Ac57A46966Ab9a).balanceOf(address(this));
(0x9d409a0A012CFbA9B15F6D4B36Ac57A46966Ab9a).call(abi.encodeWithSignature("withdraw(uint256)",bal));
// Now we have yveCRVDAO: 0xc5bDdf9843308380375a611c18B50Fb9341f502A, can be swapped on Sushiswap"
// Convert all the underlyings according to the specified router (Uniswap or Sushiswap):
for (uint256 i = 0; i < underlyings.length; i++) {
bal = IERC20(underlyings[i]).balanceOf(address(this));
path[0] = underlyings[i];
path[1] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // WETH
IUniswapV2Router02(routers[i]).swapExactTokensForTokens(bal, 0, path, address(this), block.timestamp + 15000);
}
// Pay back flash loan
bal = weth.balanceOf(address(this));
require( bal >= _amountOfProfitToReturn + _amountBorrowed, 'not profitable');
// Notice that assets are transferred back to the liquidity pool, not to
// the borrow proxy.
bool sent = weth.transfer(liquidityPool, _amountBorrowed + _amountOfProfitToReturn);
require(sent, "token transfer failed");
}
}
| contract BasketDAOBuyAndBurn {
using SafeERC20 for IERC20;
/// @dev Owner of the contract.
address public owner;
/// @dev Address of the KeeperDAO borrow proxy. This will be the
/// `msg.sender` for calls to the `helloCallback` function.
address public borrowProxy;
/// @dev Address of the KeeperDAO liquidity pool. This is will be the
/// address to which the `helloCallback` function must return all bororwed
/// assets (and all excess profits).
address payable public liquidityPool;
/// @dev This modifier restricts the caller of a function to the owner of
/// this contract.
modifier onlyOwner {
if (msg.sender == owner) {
_;
}
}
/// @dev This modifier restricts the caller of a function to the KeeperDAO
/// borrow proxy.
modifier onlyBorrowProxy {
if (msg.sender == borrowProxy) {
_;
}
}
constructor() public payable {
owner = msg.sender;
// Approve the Uniswap/Sushiswap router to spend this contract's WETH:
IERC20 weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // WETH
// Amount is:
// 0000000000000000000000000000000000000000ffffffffffffffffffffffff
// Approval for Sushiswap:
require(weth.approve(address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F),79228162514264337593543950335), 'weth approve failed');
require(IERC20(0xcee60cFa923170e4f8204AE08B4fA6A3F5656F3a).approve(address(0xF178C0b5Bb7e7aBF4e12A4838C7b7c5bA2C623c0),79228162514264337593543950335), 'approve failed');
// Blank approvals:
address[15] memory underlyings = [0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e,
0xc00e94Cb662C3520282E6f5717214004A7f26888,
0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F,
0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2,
0x408e41876cCCDC0F92210600ef50372656052a38,
0xdeFA4e8a7bcBA345F687a2f1456F5Edd9CE97202,
0xBBbbCA6A901c926F240b89EacB641d8Aec7AEafD,
0xba100000625a3754423978a60c9317c58a424e3D,
0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984,
0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9,
0x6B3595068778DD592e39A122f4f5a5cF09C90fE2,
0x2ba592F78dB6436527729929AAf6c908497cB200,
0x514910771AF9Ca656af840dff83E8264EcF986CA,
0xc5bDdf9843308380375a611c18B50Fb9341f502A,
0xE41d2489571d322189246DaFA5ebDe1F4699F498];
for (uint256 i = 0; i < underlyings.length; i++) {
IERC20(underlyings[i]).approve(address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F),79228162514264337593543950335);
IERC20(underlyings[i]).approve(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D),79228162514264337593543950335);
}
liquidityPool = payable(0x4F868C1aa37fCf307ab38D215382e88FCA6275E2); // new contract since June 2021
borrowProxy = 0x17a4C8F43cB407dD21f9885c5289E66E21bEcD9D; // new contract since June 2021
}
receive() external payable {
// Do nothing.
}
fallback() external payable { return; }
/// @dev Set the owner of this contract. This function can only be called by
/// the current owner.
///
/// @param _newOwner The new owner of this contract.
function setOwner(address _newOwner) external onlyOwner {
owner = _newOwner;
}
/// @dev Set the borrow proxy expected by this contract. This function can
/// only be called by the current owner.
///
/// @param _newBorrowProxy The new borrow proxy expected by this contract.
function setBorrowProxy(address _newBorrowProxy) external onlyOwner {
borrowProxy = _newBorrowProxy;
}
/// @dev Set the liquidity pool used by this contract. This function can
/// only be called by the current owner.
///
/// @param _newLiquidityPool The new liquidity pool used by this contract.
/// It must be a payable address, because this contract needs to be able to
/// return borrowed assets and profits to the liquidty pool.
function setLiquidityPool(address payable _newLiquidityPool) external onlyOwner {
liquidityPool = _newLiquidityPool;
}
/// Function that allows to withdraw ERC-20 tokens that are sitting on this contract to the owner address.
/// Uses safeTransfer to deal with non-standard tokens like USDT
function withdrawTokens(address _token) external onlyOwner {
IERC20(_token).safeTransfer(
msg.sender,
IERC20(_token).balanceOf(address(this))
);
}
/// Function that allows to withdraw ETH that are sitting on this contract to the owner address.
function withdrawEth(uint256 _amount) external onlyOwner {
assert(
address(this).balance >= _amount
);
assert(_amount > 0);
(bool success, ) = owner.call{value:_amount}("");
require(success, "Transfer failed.");
}
// Safety fallback, code from @kinzrec
function delegateCall(address to, bytes memory data) external payable onlyOwner {
(bool success, bytes memory retData) = to.delegatecall(data);
require(success, string(retData));
}
/// @dev The main function.
function safeFlashLoanBuyAndRedeem(uint256 _amountToBorrow, uint256 _minimalProfitability, uint256 _amountOfProfitToReturn, address[] memory underlyings, address[] memory routers) external onlyOwner returns(uint256)
{
// Check input:
require( _amountToBorrow > 0, "empty amount");
address _token = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // WETH
// Do flash-loan:
LiquidityPool(liquidityPool).borrow(
// Address of the token we want to borrow. Using this address
// means that we want to borrow ETH.
_token,
// The amount of WEI that we will borrow. We have to return at least
// more than this amount.
_amountToBorrow,
// Encode the callback into calldata. This will be used to call a
// function on this contract.
abi.encodeWithSelector(
// Function selector of the callback function.
this.buyAndRedeemCallback.selector,
// First parameter of the callback.
_amountToBorrow,
_amountOfProfitToReturn,
underlyings,
routers
)
);
// At this point the flash-loan is paid back...
// Ensure we are left with more WETH than before
IERC20 weth = IERC20(_token);
uint256 weth_balance = weth.balanceOf(address(this));
require(weth_balance >= _minimalProfitability, 'not profitable');
// Transfer profit to owner address.
bool sent = weth.transfer(owner, weth_balance);
require(sent, "Token transfer failed");
return weth_balance;
}
function buyAndRedeemCallback(
uint256 _amountBorrowed,
uint256 _amountOfProfitToReturn,
address[] memory underlyings,
address[] memory routers
) external onlyBorrowProxy {
/// We have now borrowed a certain amount of WETH
// Pay back flash loan
IERC20 weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
//uint256 weth_balance = weth.balanceOf(address(this));
// Buy BDI on Sushiswap
// From WETH to BDI
address[] memory path = new address[](2);
path[0] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // WETH
path[1] = 0x0309c98B1bffA350bcb3F9fB9780970CA32a5060; // BDI
// Swap _amountBorrowed WETH to any amount of BDI (we will check that this was profitable later)
IUniswapV2Router02(address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F)).swapExactTokensForTokens(_amountBorrowed, 0, path, address(this), block.timestamp + 15000);
uint256 bdi_balance = IBDITokenContract(0x0309c98B1bffA350bcb3F9fB9780970CA32a5060).balanceOf(address(this));
// Burn BDI into constituents
IBDITokenContract(0x0309c98B1bffA350bcb3F9fB9780970CA32a5060).burn(bdi_balance);
// Convert constituents into underlyings
// yvYFI - https://etherscan.io/address/0xE14d13d8B3b85aF791b2AADD661cDBd5E6097Db1
uint256 bal = IERC20(0xE14d13d8B3b85aF791b2AADD661cDBd5E6097Db1).balanceOf(address(this));
(0xE14d13d8B3b85aF791b2AADD661cDBd5E6097Db1).call(abi.encodeWithSignature("withdraw(uint256)",bal));
// Now we have YFI: https://etherscan.io/token/0x0bc529c00c6401aef6d220be8c6ea1667f6ad93e
// cCOMP - 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4
bal = IERC20(0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4).balanceOf(address(this));
(0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4).call(abi.encodeWithSignature("redeem(uint256)",bal));
// Now we have COMP: 0xc00e94Cb662C3520282E6f5717214004A7f26888
// yvSNX - 0xF29AE508698bDeF169B89834F76704C3B205aedf
bal = IERC20(0xF29AE508698bDeF169B89834F76704C3B205aedf).balanceOf(address(this));
(0xF29AE508698bDeF169B89834F76704C3B205aedf).call(abi.encodeWithSignature("withdraw(uint256)",bal));
// Now we have SNX: 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F
// yvUNI: 0xFBEB78a723b8087fD2ea7Ef1afEc93d35E8Bed42
bal = IERC20(0xFBEB78a723b8087fD2ea7Ef1afEc93d35E8Bed42).balanceOf(address(this));
(0xFBEB78a723b8087fD2ea7Ef1afEc93d35E8Bed42).call(abi.encodeWithSignature("withdraw(uint256)",bal));
// Now we have UNI: 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984
// xSUSHI: 0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272
// can be directly swapped on Sushiswap, alternatively, could un-wrap First
bal = IERC20(0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272).balanceOf(address(this));
(0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272).call(abi.encodeWithSignature("leave(uint256)",bal));
// Now have Sushi 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2
// yvCurve-Link: 0xf2db9a7c0ACd427A680D640F02d90f6186E71725
bal = IERC20(0xf2db9a7c0ACd427A680D640F02d90f6186E71725).balanceOf(address(this));
(0xf2db9a7c0ACd427A680D640F02d90f6186E71725).call(abi.encodeWithSignature("withdraw(uint256)",bal));
// Now we have linkCRV: 0xcee60cfa923170e4f8204ae08b4fa6a3f5656f3a
bal = IERC20(0xcee60cFa923170e4f8204AE08B4fA6A3F5656F3a).balanceOf(address(this));
// Moved this to constructor:
//require(IERC20(0xcee60cFa923170e4f8204AE08B4fA6A3F5656F3a).approve(address(0xF178C0b5Bb7e7aBF4e12A4838C7b7c5bA2C623c0),79228162514264337593543950335), 'approve failed');
(0xF178C0b5Bb7e7aBF4e12A4838C7b7c5bA2C623c0).call(abi.encodeWithSignature("remove_liquidity_one_coin(uint256,int128,uint256)",bal,0,0)); // second 0 means we want to withdraw link
// Now we have LINK: 0x514910771AF9Ca656af840dff83E8264EcF986CA
// yvBOOST 0x9d409a0A012CFbA9B15F6D4B36Ac57A46966Ab9a
bal = IERC20(0x9d409a0A012CFbA9B15F6D4B36Ac57A46966Ab9a).balanceOf(address(this));
(0x9d409a0A012CFbA9B15F6D4B36Ac57A46966Ab9a).call(abi.encodeWithSignature("withdraw(uint256)",bal));
// Now we have yveCRVDAO: 0xc5bDdf9843308380375a611c18B50Fb9341f502A, can be swapped on Sushiswap"
// Convert all the underlyings according to the specified router (Uniswap or Sushiswap):
for (uint256 i = 0; i < underlyings.length; i++) {
bal = IERC20(underlyings[i]).balanceOf(address(this));
path[0] = underlyings[i];
path[1] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // WETH
IUniswapV2Router02(routers[i]).swapExactTokensForTokens(bal, 0, path, address(this), block.timestamp + 15000);
}
// Pay back flash loan
bal = weth.balanceOf(address(this));
require( bal >= _amountOfProfitToReturn + _amountBorrowed, 'not profitable');
// Notice that assets are transferred back to the liquidity pool, not to
// the borrow proxy.
bool sent = weth.transfer(liquidityPool, _amountBorrowed + _amountOfProfitToReturn);
require(sent, "token transfer failed");
}
}
| 6,522 |
5 | // An event sent when funds are received. | event Funded(address from, uint value);
| event Funded(address from, uint value);
| 38,399 |
55 | // ReentrancyGuard The contract provides protection against re-entrancy - calling a function (directly or indirectly) from within itself./ | contract ReentrancyGuard {
// true while protected code is being executed, false otherwise
bool private locked = false;
/**
* @dev ensures instantiation only by sub-contracts
*/
constructor() internal {}
// protects a function against reentrancy attacks
modifier protected() {
_protected();
locked = true;
_;
locked = false;
}
// error message binary size optimization
function _protected() internal view {
require(!locked, "ERR_REENTRANCY");
}
}
| contract ReentrancyGuard {
// true while protected code is being executed, false otherwise
bool private locked = false;
/**
* @dev ensures instantiation only by sub-contracts
*/
constructor() internal {}
// protects a function against reentrancy attacks
modifier protected() {
_protected();
locked = true;
_;
locked = false;
}
// error message binary size optimization
function _protected() internal view {
require(!locked, "ERR_REENTRANCY");
}
}
| 48,682 |
6 | // Gives an address permission to execute a method/selector The method selector to execute/executor The address to grant permission to | function addAccess(bytes4 selector, address executor) internal {
if (executor == address(this)) {
revert CannotAuthoriseSelf();
}
AccessStorage storage accStor = accessStorage();
accStor.execAccess[selector][executor] = true;
emit AccessGranted(executor, selector);
}
| function addAccess(bytes4 selector, address executor) internal {
if (executor == address(this)) {
revert CannotAuthoriseSelf();
}
AccessStorage storage accStor = accessStorage();
accStor.execAccess[selector][executor] = true;
emit AccessGranted(executor, selector);
}
| 18,428 |
82 | // ============ R = 1 cases ============ |
function _ROneSellBaseToken(PMMState memory state, uint256 payBaseAmount)
internal
pure
returns (
uint256 // receiveQuoteToken
)
|
function _ROneSellBaseToken(PMMState memory state, uint256 payBaseAmount)
internal
pure
returns (
uint256 // receiveQuoteToken
)
| 7,949 |
224 | // return if an expired oToken is ready to be settled, only true when price for underlying,strike and collateral assets at this specific expiry is available in our Oracle module _otoken oToken / | function isSettlementAllowed(address _otoken) external view returns (bool) {
(address underlying, address strike, address collateral, uint256 expiry) = _getOtokenDetails(_otoken);
return _canSettleAssets(underlying, strike, collateral, expiry);
}
| function isSettlementAllowed(address _otoken) external view returns (bool) {
(address underlying, address strike, address collateral, uint256 expiry) = _getOtokenDetails(_otoken);
return _canSettleAssets(underlying, strike, collateral, expiry);
}
| 34,519 |
20 | // Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event (ERC-20) | require(_value >= 0);
| require(_value >= 0);
| 11,663 |
48 | // Returns array with owner addresses, which confirmed transaction./_transactionId Transaction ID./ return _confirmations Returns array of owner addresses. | function getLogConfirmations(uint256 _transactionId)
public
view
returns (address[] memory _confirmations)
| function getLogConfirmations(uint256 _transactionId)
public
view
returns (address[] memory _confirmations)
| 16,020 |
1 | // assert(b > 0);Solidity automatically throws when dividing by 0 | uint256 c = a / b;
| uint256 c = a / b;
| 278 |
14 | // See {IERC20-approve}. Requirements: - `spender` cannot be the zero address. / | function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
| function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
| 41,836 |
66 | // Returns amount of tokens specific address orstaker has earned so far based on his stake and timethe stake been active so far. / | function earned(
address account
)
public
view
returns (uint256)
| function earned(
address account
)
public
view
returns (uint256)
| 32,162 |
582 | // The buffer duration required to return the highest bid if no action taken. | uint256 public receiptBuffer;
| uint256 public receiptBuffer;
| 46,578 |
882 | // Unique identifier for DVM price feed ticker. | bytes32 public priceIdentifier;
| bytes32 public priceIdentifier;
| 12,311 |
1 | // Change IPFS hash / | function lockedAmount(address owner)
external
view
returns (uint256 quantity);
| function lockedAmount(address owner)
external
view
returns (uint256 quantity);
| 6,430 |
13 | // Unpause contract Requirements: - The contract must be paused./ | function unpause() external whenPaused onlyContractAdmin {
_unpause();
}
| function unpause() external whenPaused onlyContractAdmin {
_unpause();
}
| 10,072 |
96 | // if current week before supply decay ends we add the new supply for the week diff between current week and (supply decay start week - 1) | uint decayCount = currentWeek.sub(SUPPLY_DECAY_START - 1);
totalAmount = totalAmount.add(tokenDecaySupplyForWeek(decayCount));
remainingWeeksToMint--;
| uint decayCount = currentWeek.sub(SUPPLY_DECAY_START - 1);
totalAmount = totalAmount.add(tokenDecaySupplyForWeek(decayCount));
remainingWeeksToMint--;
| 10,422 |
6 | // pass ACE Equity Token Configurations to the Constructor | function ACEEquityToken(uint initial_balance, string tokenName, string tokenSymbol, uint8 decimalUnits) public {
cap_ACE = initial_balance;
_supply += initial_balance;
_balances[msg.sender] = initial_balance;
decimals = decimalUnits;
symbol = tokenSymbol;
name = tokenName;
dev = msg.sender;
}
| function ACEEquityToken(uint initial_balance, string tokenName, string tokenSymbol, uint8 decimalUnits) public {
cap_ACE = initial_balance;
_supply += initial_balance;
_balances[msg.sender] = initial_balance;
decimals = decimalUnits;
symbol = tokenSymbol;
name = tokenName;
dev = msg.sender;
}
| 10,431 |
18 | // Remove extra owner. / | function removeOwner(address owner) onlyOwner public {
// This check is neccessary to prevent a situation where all owners
// are accidentally removed, because we do not want an ownable contract
// to become an orphan.
require(ownerCount > 1);
require(isOwner[owner]);
isOwner[owner] = false;
ownerCount--;
OwnerRemovedEvent(owner);
}
| function removeOwner(address owner) onlyOwner public {
// This check is neccessary to prevent a situation where all owners
// are accidentally removed, because we do not want an ownable contract
// to become an orphan.
require(ownerCount > 1);
require(isOwner[owner]);
isOwner[owner] = false;
ownerCount--;
OwnerRemovedEvent(owner);
}
| 14,626 |
3 | // User Interface // Sender supplies assets into the market and receives cTokens in exchange Reverts upon any failure / | function mint() external payable {
(uint256 err, ) = mintInternal(msg.value);
requireNoError(err, "mint failed");
}
| function mint() external payable {
(uint256 err, ) = mintInternal(msg.value);
requireNoError(err, "mint failed");
}
| 18,263 |
11 | // get the length of the data | let rlpLength := mload(rlpBytes)
| let rlpLength := mload(rlpBytes)
| 11,018 |
22 | // make a new transaction | Transaction memory newTransaction = Transaction({
purchaseId: transactions.length,
expirationTime: expirationTime,
nftId: nftId,
cost: cost,
buyerAddress: buyerAddress,
sellerAddress: msg.sender, // use the message sender as the seller
completed: false,
nftManager: nftManager
});
| Transaction memory newTransaction = Transaction({
purchaseId: transactions.length,
expirationTime: expirationTime,
nftId: nftId,
cost: cost,
buyerAddress: buyerAddress,
sellerAddress: msg.sender, // use the message sender as the seller
completed: false,
nftManager: nftManager
});
| 54,264 |
1 | // For marketing etc. | function reserveMintBatch(uint256[] calldata quantities, address[] calldata tos) external onlyOwner {
for(uint256 j = 0; j < quantities.length; j++){
require(
totalSupply() + quantities[j] <= collectionSize,
"Too many already minted before dev mint."
);
uint256 numChunks = quantities[j] / maxBatchSize;
for (uint256 i = 0; i < numChunks; i++) {
_safeMint(tos[j], maxBatchSize);
}
if (quantities[j] % maxBatchSize != 0){
_safeMint(tos[j], quantities[j] % maxBatchSize);
}
}
}
| function reserveMintBatch(uint256[] calldata quantities, address[] calldata tos) external onlyOwner {
for(uint256 j = 0; j < quantities.length; j++){
require(
totalSupply() + quantities[j] <= collectionSize,
"Too many already minted before dev mint."
);
uint256 numChunks = quantities[j] / maxBatchSize;
for (uint256 i = 0; i < numChunks; i++) {
_safeMint(tos[j], maxBatchSize);
}
if (quantities[j] % maxBatchSize != 0){
_safeMint(tos[j], quantities[j] % maxBatchSize);
}
}
}
| 5,070 |
46 | // BEP20Operable | * @dev Implementation of the {IBEP20Operable} interface
*/
abstract contract BEP20Operable is BEP20, IBEP20Operable, ERC165 {
using Address for address;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IBEP20Operable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Transfer tokens to a specified address and then execute a callback on recipient.
* @param recipient The address to transfer to.
* @param amount The amount to be transferred.
* @return A boolean that indicates if the operation was successful.
*/
function transferAndCall(address recipient, uint256 amount) public virtual override returns (bool) {
return transferAndCall(recipient, amount, "");
}
/**
* @dev Transfer tokens to a specified address and then execute a callback on recipient.
* @param recipient The address to transfer to
* @param amount The amount to be transferred
* @param data Additional data with no specified format
* @return A boolean that indicates if the operation was successful.
*/
function transferAndCall(address recipient, uint256 amount, bytes memory data) public virtual override returns (bool) {
transfer(recipient, amount);
require(_checkAndCallTransfer(_msgSender(), recipient, amount, data), "BEP20Operable: _checkAndCallTransfer reverts");
return true;
}
/**
* @dev Transfer tokens from one address to another and then execute a callback on recipient.
* @param sender The address which you want to send tokens from
* @param recipient The address which you want to transfer to
* @param amount The amount of tokens to be transferred
* @return A boolean that indicates if the operation was successful.
*/
function transferFromAndCall(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
return transferFromAndCall(sender, recipient, amount, "");
}
/**
* @dev Transfer tokens from one address to another and then execute a callback on recipient.
* @param sender The address which you want to send tokens from
* @param recipient The address which you want to transfer to
* @param amount The amount of tokens to be transferred
* @param data Additional data with no specified format
* @return A boolean that indicates if the operation was successful.
*/
function transferFromAndCall(address sender, address recipient, uint256 amount, bytes memory data) public virtual override returns (bool) {
transferFrom(sender, recipient, amount);
require(_checkAndCallTransfer(sender, recipient, amount, data), "BEP20Operable: _checkAndCallTransfer reverts");
return true;
}
/**
* @dev Approve spender to transfer tokens and then execute a callback on recipient.
* @param spender The address allowed to transfer to
* @param amount The amount allowed to be transferred
* @return A boolean that indicates if the operation was successful.
*/
function approveAndCall(address spender, uint256 amount) public virtual override returns (bool) {
return approveAndCall(spender, amount, "");
}
/**
* @dev Approve spender to transfer tokens and then execute a callback on recipient.
* @param spender The address allowed to transfer to.
* @param amount The amount allowed to be transferred.
* @param data Additional data with no specified format.
* @return A boolean that indicates if the operation was successful.
*/
function approveAndCall(address spender, uint256 amount, bytes memory data) public virtual override returns (bool) {
approve(spender, amount);
require(_checkAndCallApprove(spender, amount, data), "BEP20Operable: _checkAndCallApprove reverts");
return true;
}
/**
* @dev Internal function to invoke `onTransferReceived` on a target address
* The call is not executed if the target address is not a contract
* @param sender address Representing the previous owner of the given token value
* @param recipient address Target address that will receive the tokens
* @param amount uint256 The amount mount of tokens to be transferred
* @param data bytes Optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function _checkAndCallTransfer(address sender, address recipient, uint256 amount, bytes memory data) internal virtual returns (bool) {
if (!recipient.isContract()) {
return false;
}
bytes4 retval = IBEP20OperableReceiver(recipient).onTransferReceived(
_msgSender(), sender, amount, data
);
return (retval == IBEP20OperableReceiver(recipient).onTransferReceived.selector);
}
/**
* @dev Internal function to invoke `onApprovalReceived` on a target address
* The call is not executed if the target address is not a contract
* @param spender address The address which will spend the funds
* @param amount uint256 The amount of tokens to be spent
* @param data bytes Optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function _checkAndCallApprove(address spender, uint256 amount, bytes memory data) internal virtual returns (bool) {
if (!spender.isContract()) {
return false;
}
bytes4 retval = IBEP20OperableSpender(spender).onApprovalReceived(
_msgSender(), amount, data
);
return (retval == IBEP20OperableSpender(spender).onApprovalReceived.selector);
}
}
| * @dev Implementation of the {IBEP20Operable} interface
*/
abstract contract BEP20Operable is BEP20, IBEP20Operable, ERC165 {
using Address for address;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IBEP20Operable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Transfer tokens to a specified address and then execute a callback on recipient.
* @param recipient The address to transfer to.
* @param amount The amount to be transferred.
* @return A boolean that indicates if the operation was successful.
*/
function transferAndCall(address recipient, uint256 amount) public virtual override returns (bool) {
return transferAndCall(recipient, amount, "");
}
/**
* @dev Transfer tokens to a specified address and then execute a callback on recipient.
* @param recipient The address to transfer to
* @param amount The amount to be transferred
* @param data Additional data with no specified format
* @return A boolean that indicates if the operation was successful.
*/
function transferAndCall(address recipient, uint256 amount, bytes memory data) public virtual override returns (bool) {
transfer(recipient, amount);
require(_checkAndCallTransfer(_msgSender(), recipient, amount, data), "BEP20Operable: _checkAndCallTransfer reverts");
return true;
}
/**
* @dev Transfer tokens from one address to another and then execute a callback on recipient.
* @param sender The address which you want to send tokens from
* @param recipient The address which you want to transfer to
* @param amount The amount of tokens to be transferred
* @return A boolean that indicates if the operation was successful.
*/
function transferFromAndCall(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
return transferFromAndCall(sender, recipient, amount, "");
}
/**
* @dev Transfer tokens from one address to another and then execute a callback on recipient.
* @param sender The address which you want to send tokens from
* @param recipient The address which you want to transfer to
* @param amount The amount of tokens to be transferred
* @param data Additional data with no specified format
* @return A boolean that indicates if the operation was successful.
*/
function transferFromAndCall(address sender, address recipient, uint256 amount, bytes memory data) public virtual override returns (bool) {
transferFrom(sender, recipient, amount);
require(_checkAndCallTransfer(sender, recipient, amount, data), "BEP20Operable: _checkAndCallTransfer reverts");
return true;
}
/**
* @dev Approve spender to transfer tokens and then execute a callback on recipient.
* @param spender The address allowed to transfer to
* @param amount The amount allowed to be transferred
* @return A boolean that indicates if the operation was successful.
*/
function approveAndCall(address spender, uint256 amount) public virtual override returns (bool) {
return approveAndCall(spender, amount, "");
}
/**
* @dev Approve spender to transfer tokens and then execute a callback on recipient.
* @param spender The address allowed to transfer to.
* @param amount The amount allowed to be transferred.
* @param data Additional data with no specified format.
* @return A boolean that indicates if the operation was successful.
*/
function approveAndCall(address spender, uint256 amount, bytes memory data) public virtual override returns (bool) {
approve(spender, amount);
require(_checkAndCallApprove(spender, amount, data), "BEP20Operable: _checkAndCallApprove reverts");
return true;
}
/**
* @dev Internal function to invoke `onTransferReceived` on a target address
* The call is not executed if the target address is not a contract
* @param sender address Representing the previous owner of the given token value
* @param recipient address Target address that will receive the tokens
* @param amount uint256 The amount mount of tokens to be transferred
* @param data bytes Optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function _checkAndCallTransfer(address sender, address recipient, uint256 amount, bytes memory data) internal virtual returns (bool) {
if (!recipient.isContract()) {
return false;
}
bytes4 retval = IBEP20OperableReceiver(recipient).onTransferReceived(
_msgSender(), sender, amount, data
);
return (retval == IBEP20OperableReceiver(recipient).onTransferReceived.selector);
}
/**
* @dev Internal function to invoke `onApprovalReceived` on a target address
* The call is not executed if the target address is not a contract
* @param spender address The address which will spend the funds
* @param amount uint256 The amount of tokens to be spent
* @param data bytes Optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function _checkAndCallApprove(address spender, uint256 amount, bytes memory data) internal virtual returns (bool) {
if (!spender.isContract()) {
return false;
}
bytes4 retval = IBEP20OperableSpender(spender).onApprovalReceived(
_msgSender(), amount, data
);
return (retval == IBEP20OperableSpender(spender).onApprovalReceived.selector);
}
}
| 79,738 |
3 | // Execute the Arbitrable associated to a dispute based on its final ruling_disputeId Identification number of the dispute to be executed/ | function executeRuling(uint256 _disputeId) external;
| function executeRuling(uint256 _disputeId) external;
| 16,521 |
33 | // call by Owner (SupplyBooster) | function initialize(
address _virtualBalance,
address _underlyToken,
bool _isErc20
| function initialize(
address _virtualBalance,
address _underlyToken,
bool _isErc20
| 26,353 |
42 | // This method will parse a delimited string and insert them into the Domain map of a Rule/ | function splitStrIntoMap(string memory str, string memory delimiter, WonkaLibrary.WonkaRule storage targetRule, bool isOpRule) private {
bytes memory b = bytes(str); //cast the string to bytes to iterate
bytes memory delm = bytes(delimiter);
splitTempStr = "";
for(uint i; i<b.length ; i++){
if(b[i] != delm[0]) { //check if a not space
| function splitStrIntoMap(string memory str, string memory delimiter, WonkaLibrary.WonkaRule storage targetRule, bool isOpRule) private {
bytes memory b = bytes(str); //cast the string to bytes to iterate
bytes memory delm = bytes(delimiter);
splitTempStr = "";
for(uint i; i<b.length ; i++){
if(b[i] != delm[0]) { //check if a not space
| 54,395 |
28 | // @inheritdoc IERC165 | function supportsInterface(
bytes4 interfaceId_
)
public
view
override(ERC721Enumerable, ERC2981)
returns (bool)
| function supportsInterface(
bytes4 interfaceId_
)
public
view
override(ERC721Enumerable, ERC2981)
returns (bool)
| 9,421 |
32 | // Liquididity providers add liquidity _amount liquidity amount that users want to deposit. _tokenAddress address of the liquidity token. / | function addLiquidity(
uint256 _amount,
address _tokenAddress
)
external
payable
nonReentrant
whenNotPaused
| function addLiquidity(
uint256 _amount,
address _tokenAddress
)
external
payable
nonReentrant
whenNotPaused
| 25,289 |
179 | // withdraw | function withdraw() public payable onlyOwner {
uint256 _each = address(this).balance / 1;
require(payable(_address_for_withdrawal).send(_each));
}
| function withdraw() public payable onlyOwner {
uint256 _each = address(this).balance / 1;
require(payable(_address_for_withdrawal).send(_each));
}
| 74,539 |
10 | // init | _initialized = true;
return true;
| _initialized = true;
return true;
| 4,584 |
55 | // read the current registrar / | function getRegistrar()
external
view
returns (
address
)
| function getRegistrar()
external
view
returns (
address
)
| 46,854 |
160 | // Delete the slot where the moved entry was stored | map._entries.pop();
| map._entries.pop();
| 2,102 |
22 | // check if ticket is on sale | require(_exists, "Token requested is not for sale.");
| require(_exists, "Token requested is not for sale.");
| 39,592 |
14 | // Override this function to set initial operational values for module instances | function _setUp(bytes calldata _initData) internal virtual { }
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Deploy the implementation contract and set its version
/// @dev This is only used to deploy the implementation contract, and should not be used to deploy clones
constructor(string memory _version) {
version_ = _version;
// prevent the implementation contract from being initialized
_disableInitializers();
}
| function _setUp(bytes calldata _initData) internal virtual { }
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Deploy the implementation contract and set its version
/// @dev This is only used to deploy the implementation contract, and should not be used to deploy clones
constructor(string memory _version) {
version_ = _version;
// prevent the implementation contract from being initialized
_disableInitializers();
}
| 28,802 |
23 | // THIS FUMCTION WILL BE USED BY INVESTOR FOR BUYING TOKENSIF THE OWNER WILL END ICO THEN NO ONE CAN INVEST ANYMORE | function buyToken() public payable{
require(msg.value > 0,"You are passing wrong value");
require(msg.sender != address(0),"Invalid Address of Buyer");
require(now <= releaseTime, "ICO is ended.");
address sender = msg.sender;
uint256 quantity = (msg.value / tokenPrice) * 10**18;
ownerAccount.transfer(msg.value);
token.transfer(sender,quantity);
remainingTokens -= quantity;
emit Transfer(address(this),sender,quantity);
}
| function buyToken() public payable{
require(msg.value > 0,"You are passing wrong value");
require(msg.sender != address(0),"Invalid Address of Buyer");
require(now <= releaseTime, "ICO is ended.");
address sender = msg.sender;
uint256 quantity = (msg.value / tokenPrice) * 10**18;
ownerAccount.transfer(msg.value);
token.transfer(sender,quantity);
remainingTokens -= quantity;
emit Transfer(address(this),sender,quantity);
}
| 13 |
18 | // The addresses of the accounts (or contracts) that can execute actions within each roles. | address public devAddress = msg.sender;
| address public devAddress = msg.sender;
| 9,720 |
44 | // EFFICIENCY ATTRIBUTE MULTIPLIER | if(blockDif >= ONE_MINUTE_BLOCKS){
uint mins = blockDif.div(ONE_MINUTE_BLOCKS);
if(mins > 1){
| if(blockDif >= ONE_MINUTE_BLOCKS){
uint mins = blockDif.div(ONE_MINUTE_BLOCKS);
if(mins > 1){
| 25,032 |
75 | // setSalePrice// Set the token for sale. The owner of the token must be the sender and have the marketplace approved. _tokenId uint256 ID of the token _amount uint256 wei value that the item is for sale _owner address of the token owner / | function setSalePrice(
uint256 _tokenId,
uint256 _amount,
address _owner
| function setSalePrice(
uint256 _tokenId,
uint256 _amount,
address _owner
| 55,150 |
18 | // - converts raw bytes representation of a Syscoin block header to struct representation_rawBytes - first 80 bytes of a block header return - exact same header information in BlockHeader struct form | function parseHeaderBytes(bytes memory _rawBytes, uint pos) private view returns (BlockHeader memory bh) {
bh.bits = getBits(_rawBytes, pos);
bh.blockHash = bytes32(dblShaFlipMem(_rawBytes, pos, 80));
bh.timestamp = getTimestamp(_rawBytes, pos);
bh.prevBlock = bytes32(getHashPrevBlock(_rawBytes, pos));
}
| function parseHeaderBytes(bytes memory _rawBytes, uint pos) private view returns (BlockHeader memory bh) {
bh.bits = getBits(_rawBytes, pos);
bh.blockHash = bytes32(dblShaFlipMem(_rawBytes, pos, 80));
bh.timestamp = getTimestamp(_rawBytes, pos);
bh.prevBlock = bytes32(getHashPrevBlock(_rawBytes, pos));
}
| 48,639 |
11 | // Get Users Lenght | function getUsersCount()
external
view
| function getUsersCount()
external
view
| 51,911 |
13 | // Check if strategy already has been added, if not/ add it to the list of strategies | function _addStrategy(address _strategy) internal {
uint256 strategiesLength = strategies.length;
for (uint256 i; i < strategiesLength; ++i) {
if (strategies[i] == _strategy) {
return;
}
}
strategies.push(_strategy);
}
| function _addStrategy(address _strategy) internal {
uint256 strategiesLength = strategies.length;
for (uint256 i; i < strategiesLength; ++i) {
if (strategies[i] == _strategy) {
return;
}
}
strategies.push(_strategy);
}
| 33,032 |
62 | // has active bid// has active bid _tokenId uint256 ID of the token _owner address of the token owner / | function hasTokenActiveBid(uint256 _tokenId, address _owner) external view override returns (bool){
ActiveBid memory ab = activeBid[_tokenId][_owner];
if (ab.bidder == _owner || ab.bidder == address(0))
return false;
return true;
}
| function hasTokenActiveBid(uint256 _tokenId, address _owner) external view override returns (bool){
ActiveBid memory ab = activeBid[_tokenId][_owner];
if (ab.bidder == _owner || ab.bidder == address(0))
return false;
return true;
}
| 55,140 |
8 | // NFTSVG/Provides a function for generating an SVG associated with a Uniswap NFT | library MetadataGenerator {
using Strings for uint256;
using HexStrings for uint160;
using ToColor for bytes3;
function statsBar(uint chubbiness) internal pure returns (string memory) {
string memory line = '<line x1="0" y1="300" x2="400" y2="300" stroke="black" />';
string memory text = string(abi.encodePacked('<text x="50%" y="350" class="base" dominant-baseline="middle" text-anchor="middle">chubbiness: ', chubbiness.toString(), '</text>'));
return string(abi.encodePacked(line, text));
}
function batchGenerator(uint8 batch) internal pure returns (string memory) {
string memory encodedSVG = "";
if (batch == 1) {
encodedSVG = '<polygon points="9.9, 1.1, 3.3, 21.78, 19.8, 8.58, 0, 8.58, 16.5, 21.78" style="fill-rule:nonzero;"/>';
return encodedSVG;
} else if (batch == 2) {
encodedSVG = '<polygon points="9.9, 1.1, 3.3, 21.78, 19.8, 8.58, 0, 8.58, 16.5, 21.78" style="fill-rule:nonzero;"/><polygon points="40, 1.1, 3.3, 79.78, 19.8, 8.58, 0, 8.58, 16.5, 21.78" style="fill-rule:nonzero;"/>';
return encodedSVG;
} else {
return encodedSVG;
}
}
function getColor(uint8 colorindex) internal pure returns (string memory) {
if (colorindex == 1) {
return "ffffff";
} else if (colorindex == 2) {
return "FF78A9";
} else {
return "000000";
}
}
function tokenURI(
address owner,
uint256 tokenId,
uint8 color,
uint256 chubbiness,
uint8 batch
) internal pure returns (string memory) {
string memory imageURI = svgToImageURI(
owner,
tokenId,
color,
chubbiness,
batch
);
return formatTokenURI(imageURI);
}
function svgToImageURI(
address owner,
uint256 tokenId,
uint8 color,
uint256 chubbiness,
uint8 batch
) public pure returns (string memory) {
// example:
// <svg width='500' height='500' viewBox='0 0 285 350' fill='none' xmlns='http://www.w3.org/2000/svg'><path fill='black' d='M150,0,L75,200,L225,200,Z'></path></svg>
// data:image/svg+xml;base64,PHN2ZyB3aWR0aD0nNTAwJyBoZWlnaHQ9JzUwMCcgdmlld0JveD0nMCAwIDI4NSAzNTAnIGZpbGw9J25vbmUnIHhtbG5zPSdodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2Zyc+PHBhdGggZmlsbD0nYmxhY2snIGQ9J00xNTAsMCxMNzUsMjAwLEwyMjUsMjAwLFonPjwvcGF0aD48L3N2Zz4=
string memory baseURL = "data:image/svg+xml;base64,";
string memory svgBase64Encoded = Base64.encode(
bytes(
string(
abi.encodePacked(
'<svg width="400" height="400" xmlns="http://www.w3.org/2000/svg">',
'<g id="eye1">',
'<ellipse stroke-width="3" ry="29.5" rx="29.5" id="svg_1" cy="154.5" cx="181.5" stroke="#000" fill="#fff"/>',
'<ellipse ry="3.5" rx="2.5" id="svg_3" cy="154.5" cx="173.5" stroke-width="3" stroke="#000" fill="#000000"/>',
"</g>",
'<g id="head">',
'<ellipse fill="#',
getColor(color),
'" stroke-width="3" cx="204.5" cy="211.80065" id="svg_5" rx="',
chubbiness.toString(),
'" ry="51.80065" stroke="#000"/>',
"</g>",
'<g id="eye2">',
'<ellipse stroke-width="3" ry="29.5" rx="29.5" id="svg_2" cy="168.5" cx="209.5" stroke="#000" fill="#fff"/>',
'<ellipse ry="3.5" rx="3" id="svg_4" cy="169.5" cx="208" stroke-width="3" fill="#000000" stroke="#000"/>',
"</g>",
batchGenerator(batch),
statsBar(chubbiness),
"</svg>"
)
)
)
);
return string(abi.encodePacked(baseURL, svgBase64Encoded));
}
function formatTokenURI(string memory imageURI)
public
pure
returns (string memory)
{
return
string(
abi.encodePacked(
"data:application/json;base64,",
Base64.encode(
bytes(
abi.encodePacked(
'{"name":"',
"Block Monster", // You can add whatever name here
'", "description":"An NFT based on SVG!", "attributes":"", "image":"',
imageURI,
'"}'
)
)
)
)
);
}
function uint2str(uint256 _i)
internal
pure
returns (string memory _uintAsString)
{
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len;
while (_i != 0) {
k = k - 1;
uint8 temp = (48 + uint8(_i - (_i / 10) * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
}
| library MetadataGenerator {
using Strings for uint256;
using HexStrings for uint160;
using ToColor for bytes3;
function statsBar(uint chubbiness) internal pure returns (string memory) {
string memory line = '<line x1="0" y1="300" x2="400" y2="300" stroke="black" />';
string memory text = string(abi.encodePacked('<text x="50%" y="350" class="base" dominant-baseline="middle" text-anchor="middle">chubbiness: ', chubbiness.toString(), '</text>'));
return string(abi.encodePacked(line, text));
}
function batchGenerator(uint8 batch) internal pure returns (string memory) {
string memory encodedSVG = "";
if (batch == 1) {
encodedSVG = '<polygon points="9.9, 1.1, 3.3, 21.78, 19.8, 8.58, 0, 8.58, 16.5, 21.78" style="fill-rule:nonzero;"/>';
return encodedSVG;
} else if (batch == 2) {
encodedSVG = '<polygon points="9.9, 1.1, 3.3, 21.78, 19.8, 8.58, 0, 8.58, 16.5, 21.78" style="fill-rule:nonzero;"/><polygon points="40, 1.1, 3.3, 79.78, 19.8, 8.58, 0, 8.58, 16.5, 21.78" style="fill-rule:nonzero;"/>';
return encodedSVG;
} else {
return encodedSVG;
}
}
function getColor(uint8 colorindex) internal pure returns (string memory) {
if (colorindex == 1) {
return "ffffff";
} else if (colorindex == 2) {
return "FF78A9";
} else {
return "000000";
}
}
function tokenURI(
address owner,
uint256 tokenId,
uint8 color,
uint256 chubbiness,
uint8 batch
) internal pure returns (string memory) {
string memory imageURI = svgToImageURI(
owner,
tokenId,
color,
chubbiness,
batch
);
return formatTokenURI(imageURI);
}
function svgToImageURI(
address owner,
uint256 tokenId,
uint8 color,
uint256 chubbiness,
uint8 batch
) public pure returns (string memory) {
// example:
// <svg width='500' height='500' viewBox='0 0 285 350' fill='none' xmlns='http://www.w3.org/2000/svg'><path fill='black' d='M150,0,L75,200,L225,200,Z'></path></svg>
// data:image/svg+xml;base64,PHN2ZyB3aWR0aD0nNTAwJyBoZWlnaHQ9JzUwMCcgdmlld0JveD0nMCAwIDI4NSAzNTAnIGZpbGw9J25vbmUnIHhtbG5zPSdodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2Zyc+PHBhdGggZmlsbD0nYmxhY2snIGQ9J00xNTAsMCxMNzUsMjAwLEwyMjUsMjAwLFonPjwvcGF0aD48L3N2Zz4=
string memory baseURL = "data:image/svg+xml;base64,";
string memory svgBase64Encoded = Base64.encode(
bytes(
string(
abi.encodePacked(
'<svg width="400" height="400" xmlns="http://www.w3.org/2000/svg">',
'<g id="eye1">',
'<ellipse stroke-width="3" ry="29.5" rx="29.5" id="svg_1" cy="154.5" cx="181.5" stroke="#000" fill="#fff"/>',
'<ellipse ry="3.5" rx="2.5" id="svg_3" cy="154.5" cx="173.5" stroke-width="3" stroke="#000" fill="#000000"/>',
"</g>",
'<g id="head">',
'<ellipse fill="#',
getColor(color),
'" stroke-width="3" cx="204.5" cy="211.80065" id="svg_5" rx="',
chubbiness.toString(),
'" ry="51.80065" stroke="#000"/>',
"</g>",
'<g id="eye2">',
'<ellipse stroke-width="3" ry="29.5" rx="29.5" id="svg_2" cy="168.5" cx="209.5" stroke="#000" fill="#fff"/>',
'<ellipse ry="3.5" rx="3" id="svg_4" cy="169.5" cx="208" stroke-width="3" fill="#000000" stroke="#000"/>',
"</g>",
batchGenerator(batch),
statsBar(chubbiness),
"</svg>"
)
)
)
);
return string(abi.encodePacked(baseURL, svgBase64Encoded));
}
function formatTokenURI(string memory imageURI)
public
pure
returns (string memory)
{
return
string(
abi.encodePacked(
"data:application/json;base64,",
Base64.encode(
bytes(
abi.encodePacked(
'{"name":"',
"Block Monster", // You can add whatever name here
'", "description":"An NFT based on SVG!", "attributes":"", "image":"',
imageURI,
'"}'
)
)
)
)
);
}
function uint2str(uint256 _i)
internal
pure
returns (string memory _uintAsString)
{
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len;
while (_i != 0) {
k = k - 1;
uint8 temp = (48 + uint8(_i - (_i / 10) * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
}
| 2,290 |
4 | // Burn liquidity from the sender and account tokens owed for the liquidity to the position/Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0/Fees must be collected separately via a call to collect/tickLower The lower tick of the position for which to burn liquidity/tickUpper The upper tick of the position for which to burn liquidity/amount How much liquidity to burn/ return amount0 The amount of token0 sent to the recipient/ return amount1 The amount of token1 sent to the recipient | function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
| function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
| 17,400 |
304 | // Disable internal _transfer function for ERC721 - do nth, must use safeTransferFrom to transfer token | _transfer(from, to, tokenId);
| _transfer(from, to, tokenId);
| 44,181 |
16 | // state variables | OpenBooks private openBooks;
| OpenBooks private openBooks;
| 2,480 |
10 | // Wager amount in wei. | uint amount;
| uint amount;
| 19,518 |
28 | // key should be pmt sha3 hash. But currently txRef is used to globaqueue after checking queue. | uint public globalGridlockQueueDepth;
mapping (bytes32 => GridlockedPmt) public globalGridlockQueue;
uint public maxQueueDepth; // queue depth trigger
| uint public globalGridlockQueueDepth;
mapping (bytes32 => GridlockedPmt) public globalGridlockQueue;
uint public maxQueueDepth; // queue depth trigger
| 32,543 |
0 | // mint(msg.sender, 20); | admin = msg.sender;
| admin = msg.sender;
| 3,379 |
66 | // 32 byte slot 1Current round number. `round` represents the number of `period`s elapsed. | uint16 round;
| uint16 round;
| 48,702 |
35 | // StablePriceOracle sets a price in USD, based on an oracle. | contract StablePriceOracle is Ownable, PriceOracle {
using SafeMath for *;
using StringUtils for *;
// Oracle address
DSValue usdOracle;
// Rent in attodollars (1e-18) per second
uint[] public rentPrices;
event OracleChanged(address oracle);
event RentPriceChanged(uint[] prices);
constructor(DSValue _usdOracle, uint[] memory _rentPrices) public {
setOracle(_usdOracle);
setPrices(_rentPrices);
}
/**
* @dev Sets the price oracle address
* @param _usdOracle The address of the price oracle to use.
*/
function setOracle(DSValue _usdOracle) public onlyOwner {
usdOracle = _usdOracle;
emit OracleChanged(address(_usdOracle));
}
/**
* @dev Sets rent prices.
* @param _rentPrices The price array. Each element corresponds to a specific
* name length; names longer than the length of the array
* default to the price of the last element.
*/
function setPrices(uint[] memory _rentPrices) public onlyOwner {
rentPrices = _rentPrices;
emit RentPriceChanged(_rentPrices);
}
/**
* @dev Returns the price to register or renew a name.
* @param name The name being registered or renewed.
* @param duration How long the name is being registered or extended for, in seconds.
* @return The price of this renewal or registration, in wei.
*/
function price(string calldata name, uint /*expires*/, uint duration) view external returns(uint) {
uint len = name.strlen();
if(len > rentPrices.length) {
len = rentPrices.length;
}
require(len > 0);
uint priceUSD = rentPrices[len - 1].mul(duration);
// Price of one ether in attodollars
uint ethPrice = uint(usdOracle.read());
// priceUSD and ethPrice are both fixed-point values with 18dp, so we
// multiply the numerator by 1e18 before dividing.
return priceUSD.mul(1e18).div(ethPrice);
}
} | contract StablePriceOracle is Ownable, PriceOracle {
using SafeMath for *;
using StringUtils for *;
// Oracle address
DSValue usdOracle;
// Rent in attodollars (1e-18) per second
uint[] public rentPrices;
event OracleChanged(address oracle);
event RentPriceChanged(uint[] prices);
constructor(DSValue _usdOracle, uint[] memory _rentPrices) public {
setOracle(_usdOracle);
setPrices(_rentPrices);
}
/**
* @dev Sets the price oracle address
* @param _usdOracle The address of the price oracle to use.
*/
function setOracle(DSValue _usdOracle) public onlyOwner {
usdOracle = _usdOracle;
emit OracleChanged(address(_usdOracle));
}
/**
* @dev Sets rent prices.
* @param _rentPrices The price array. Each element corresponds to a specific
* name length; names longer than the length of the array
* default to the price of the last element.
*/
function setPrices(uint[] memory _rentPrices) public onlyOwner {
rentPrices = _rentPrices;
emit RentPriceChanged(_rentPrices);
}
/**
* @dev Returns the price to register or renew a name.
* @param name The name being registered or renewed.
* @param duration How long the name is being registered or extended for, in seconds.
* @return The price of this renewal or registration, in wei.
*/
function price(string calldata name, uint /*expires*/, uint duration) view external returns(uint) {
uint len = name.strlen();
if(len > rentPrices.length) {
len = rentPrices.length;
}
require(len > 0);
uint priceUSD = rentPrices[len - 1].mul(duration);
// Price of one ether in attodollars
uint ethPrice = uint(usdOracle.read());
// priceUSD and ethPrice are both fixed-point values with 18dp, so we
// multiply the numerator by 1e18 before dividing.
return priceUSD.mul(1e18).div(ethPrice);
}
} | 26,403 |
295 | // Confirm both aggregate account balance and directly staked amount are valid | this.validateAccountStakeBalance(msg.sender);
uint256 currentlyStakedForOwner = Staking(stakingAddress).totalStakedFor(msg.sender);
| this.validateAccountStakeBalance(msg.sender);
uint256 currentlyStakedForOwner = Staking(stakingAddress).totalStakedFor(msg.sender);
| 3,198 |
22 | // solium-disable indentation // solium-enable indentation / Raise appeal if both sides are fully funded. | if (round.hasPaid[uint(Party.Challenger)] && round.hasPaid[uint(Party.Requester)]) {
request.arbitrator.appeal.value(appealCost)(request.disputeID, request.arbitratorExtraData);
request.rounds.length++;
round.feeRewards = round.feeRewards.subCap(appealCost);
}
| if (round.hasPaid[uint(Party.Challenger)] && round.hasPaid[uint(Party.Requester)]) {
request.arbitrator.appeal.value(appealCost)(request.disputeID, request.arbitratorExtraData);
request.rounds.length++;
round.feeRewards = round.feeRewards.subCap(appealCost);
}
| 12,702 |
286 | // the current protocol fee as a percentage of the swap fee taken on withdrawal represented as an integer denominator (1/x)% | uint8 feeProtocol;
| uint8 feeProtocol;
| 31,043 |
2 | // The main logic. If the timer has elapsed and there is a schedule upgrade, the governance can upgrade the vault/ | function upgrade() external {
(bool should, address newImplementation) = IUpgradeSource(address(this)).shouldUpgrade();
require(should, "Upgrade not scheduled");
_upgradeTo(newImplementation);
// the finalization needs to be executed on itself to update the storage of this proxy
// it also needs to be invoked by the governance, not by address(this), so delegatecall is needed
(bool success,) = address(this).delegatecall(
abi.encodeWithSignature("finalizeUpgrade()")
);
require(success, "Issue when finalizing the upgrade");
}
| function upgrade() external {
(bool should, address newImplementation) = IUpgradeSource(address(this)).shouldUpgrade();
require(should, "Upgrade not scheduled");
_upgradeTo(newImplementation);
// the finalization needs to be executed on itself to update the storage of this proxy
// it also needs to be invoked by the governance, not by address(this), so delegatecall is needed
(bool success,) = address(this).delegatecall(
abi.encodeWithSignature("finalizeUpgrade()")
);
require(success, "Issue when finalizing the upgrade");
}
| 25,366 |
65 | // Emitted after aTokens are burned from The owner of the aTokens, getting them burned target The address that will receive the underlying value The amount being burned index The new liquidity index of the reserve // Emitted during the transfer action from The user whose tokens are being transferred to The recipient value The amount being transferred index The new liquidity index of the reserve // Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` user The owner of the aTokens, getting them burned receiverOfUnderlying The address that will receive the underlying amount The amount being | function mintToTreasury(uint256 amount, uint256 index) external;
| function mintToTreasury(uint256 amount, uint256 index) external;
| 12,794 |
48 | // Generates `_amount` tokens that are assigned to `_owner`/_owner The address that will be assigned the new tokens/_amount The quantity of tokens generated/ return True if the tokens are generated correctly | function _generateTokens(address _owner, uint _amount) internal returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
emit Transfer(address(0), _owner, _amount);
return true;
}
| function _generateTokens(address _owner, uint _amount) internal returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
emit Transfer(address(0), _owner, _amount);
return true;
}
| 1,169 |
264 | // MUST emit when an approval is updated. | event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
| event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
| 18,430 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.