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 |
|---|---|---|---|---|
41 | // accumulates the accrued interest of the user to the principal balance_user the address of the user for which the interest is being accumulated return the previous principal balance, the new principal balance, the balance increase and the new user index/ | returns(uint256, uint256, uint256, uint256) {
uint256 previousPrincipalBalance = super.balanceOf(_user);
//calculate the accrued interest since the last accumulation
uint256 balanceIncrease = balanceOf(_user).sub(previousPrincipalBalance);
//mints an amount of tokens equivalent to the amount accumulated
_mint(_user, balanceIncrease);
//updates the user index
uint256 index = userIndexes[_user] = core.getReserveNormalizedIncome(underlyingAssetAddress);
return (
previousPrincipalBalance,
previousPrincipalBalance.add(balanceIncrease),
balanceIncrease,
index
);
}
| returns(uint256, uint256, uint256, uint256) {
uint256 previousPrincipalBalance = super.balanceOf(_user);
//calculate the accrued interest since the last accumulation
uint256 balanceIncrease = balanceOf(_user).sub(previousPrincipalBalance);
//mints an amount of tokens equivalent to the amount accumulated
_mint(_user, balanceIncrease);
//updates the user index
uint256 index = userIndexes[_user] = core.getReserveNormalizedIncome(underlyingAssetAddress);
return (
previousPrincipalBalance,
previousPrincipalBalance.add(balanceIncrease),
balanceIncrease,
index
);
}
| 33,358 |
35 | // Failsafe function to cancel a specific auction by the contract owner. auctionId The ID of the auction. / | function cancelSpecificAuction(uint256 auctionId) public onlyOwner {
Auction storage auction = auctions[auctionId];
require(auction.seller != address(0), "Auction does not exist");
if (auction.highestBidder != address(0)) {
IERC20(auction.bidTokenAddress).transfer(
auction.highestBidder,
auction.highestBid
);
}
for (uint i = 0; i < auction.tokens.length; i++) {
IERC721(auction.tokens[i].tokenAddress).safeTransferFrom(
address(this),
auction.highestBidder,
auction.tokens[i].tokenId
);
}
// Remove auction from active auctions
for (uint i = 0; i < activeAuctionIds.length; i++) {
if (activeAuctionIds[i] == auctionId) {
activeAuctionIds[i] = activeAuctionIds[
activeAuctionIds.length - 1
];
activeAuctionIds.pop();
break;
}
}
delete auctions[auctionId];
emit AuctionCancelled(auctionId);
}
| function cancelSpecificAuction(uint256 auctionId) public onlyOwner {
Auction storage auction = auctions[auctionId];
require(auction.seller != address(0), "Auction does not exist");
if (auction.highestBidder != address(0)) {
IERC20(auction.bidTokenAddress).transfer(
auction.highestBidder,
auction.highestBid
);
}
for (uint i = 0; i < auction.tokens.length; i++) {
IERC721(auction.tokens[i].tokenAddress).safeTransferFrom(
address(this),
auction.highestBidder,
auction.tokens[i].tokenId
);
}
// Remove auction from active auctions
for (uint i = 0; i < activeAuctionIds.length; i++) {
if (activeAuctionIds[i] == auctionId) {
activeAuctionIds[i] = activeAuctionIds[
activeAuctionIds.length - 1
];
activeAuctionIds.pop();
break;
}
}
delete auctions[auctionId];
emit AuctionCancelled(auctionId);
}
| 23,798 |
43 | // authenticate wallet to mint tokens _authenticate The address of the stake contract _status boolean to activate and deactivate wallet authenticationreturn boolean/ | function authenticate( address _authenticate, bool _status) public returns (bool){
require(authentication[_authenticate] != _status, "authentication :: is already authenticated ");
require(msg.sender == owner, "setAuthentication :: owner should authenticate");
authentication[_authenticate] = _status;
return true;
}
| function authenticate( address _authenticate, bool _status) public returns (bool){
require(authentication[_authenticate] != _status, "authentication :: is already authenticated ");
require(msg.sender == owner, "setAuthentication :: owner should authenticate");
authentication[_authenticate] = _status;
return true;
}
| 24,123 |
111 | // Called with the sale price to determine how much royalty is owed and to whom. tokenId - the NFT asset queried for royalty information salePrice - the sale price of the NFT asset specified by `tokenId`return receiver - address of who should be sent the royalty paymentreturn royaltyAmount - the royalty payment amount for `salePrice` / | function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
| function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
| 42,399 |
10 | // Gets the current mStable Savings Contract address. return address of mStable Savings Contract. | function _fetchMStableSavings() internal view returns (address) {
address manager = IMStable(nexusGovernance).getModule(keccak256('SavingsManager'));
return IMStable(manager).savingsContracts(reserve);
}
| function _fetchMStableSavings() internal view returns (address) {
address manager = IMStable(nexusGovernance).getModule(keccak256('SavingsManager'));
return IMStable(manager).savingsContracts(reserve);
}
| 38,971 |
13 | // Push Updates to Campaign | campaign.updates.push(_update);
| campaign.updates.push(_update);
| 8,223 |
4 | // See {IERC20Metadata-decimals}. / | function decimals() public view virtual override(IERC20MetadataUpgradeable, ERC20Upgradeable) returns (uint8) {
return _decimals;
}
| function decimals() public view virtual override(IERC20MetadataUpgradeable, ERC20Upgradeable) returns (uint8) {
return _decimals;
}
| 22,739 |
6 | // get the total number of members stored in the map. / | function memberCount() external view returns (uint256);
| function memberCount() external view returns (uint256);
| 40,743 |
61 | // event for transfer/transferFrom request loggingfrom address from which tokens have to be transferredto address to tokens have to be transferredvalue number of tokensfee fee in tokensspender The address which will spend the tokens/ | event RecordedPendingTransaction(
| event RecordedPendingTransaction(
| 74,723 |
37 | // Perfect Number | return
'<g class="stroke"><path d="m12 12 37 37"/><path d="m12 49 37-37"/><path d="M5.4 30H56"/><path d="M30.7 55.3V4.7"/></g>';
| return
'<g class="stroke"><path d="m12 12 37 37"/><path d="m12 49 37-37"/><path d="M5.4 30H56"/><path d="M30.7 55.3V4.7"/></g>';
| 30,061 |
10 | // Internal struct for use in proof-of-work submission | struct Details {
uint256 value;
address miner;
}
| struct Details {
uint256 value;
address miner;
}
| 3,332 |
144 | // To check whether a locator was deployedImplements ILocatorWhitelist.haslocator bytes32 Locator of the delegate in question return bool True if the delegate was deployed by this contract/ | function has(bytes32 locator) external view returns (bool) {
return _deployedAddresses[address(bytes20(locator))];
}
| function has(bytes32 locator) external view returns (bool) {
return _deployedAddresses[address(bytes20(locator))];
}
| 35,774 |
57 | // Returns the follow NFT implementation address. return address The follow NFT implementation address. / | function getFollowNFTImpl() external view returns (address);
| function getFollowNFTImpl() external view returns (address);
| 3,948 |
32 | // We give `properties.length == 0` and `properties.length == 1` special treatment because we expect these to be the most common. | if (numProperties == 0) {
propertiesHash = _EMPTY_ARRAY_KECCAK256;
} else if (numProperties == 1) {
| if (numProperties == 0) {
propertiesHash = _EMPTY_ARRAY_KECCAK256;
} else if (numProperties == 1) {
| 1,390 |
100 | // Emitted when amount of registered token is claimed | event Claim(
bytes32 indexed depositTx,
address indexed token,
address indexed toWallet,
uint256 amount
);
| event Claim(
bytes32 indexed depositTx,
address indexed token,
address indexed toWallet,
uint256 amount
);
| 52,321 |
20 | // checksum is the first 4 bytes of the sha3 of the xor of the bytes32 versions of the cosmos address and the return address | if ( !( bytes4(sha3( bytes32(_donor)^bytes32(_returnAddress) )) == checksum )) throw;
| if ( !( bytes4(sha3( bytes32(_donor)^bytes32(_returnAddress) )) == checksum )) throw;
| 11,489 |
54 | // Returns the multiplication of two unsigned integers, reverting onoverflow. Counterpart to Solidity's `` operator. Requirements: - Multiplication cannot overflow. / | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
| function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
| 5,757 |
18 | // tokenURI prefix which will have the tokenId appended to it | string myTokenURIPrefix;
| string myTokenURIPrefix;
| 48,853 |
8 | // it checks if an account is already in the list of the asset's signers asset the asset to check for if the signer exists account the account to check in the list of the asset's signers / | function isSigner(address asset, address account)
public
view
returns (bool isSigner_)
| function isSigner(address asset, address account)
public
view
returns (bool isSigner_)
| 2,607 |
13 | // makes sure that user did not already claim a token | require(ownerToTokenId[msg.sender] == 0);
Token memory token = Token({
redeemedBy: msg.sender,
redeemedAt: now
});
| require(ownerToTokenId[msg.sender] == 0);
Token memory token = Token({
redeemedBy: msg.sender,
redeemedAt: now
});
| 8,333 |
108 | // ensures that the fee is valid | modifier validFee(uint32 fee) {
_validFee(fee);
_;
}
| modifier validFee(uint32 fee) {
_validFee(fee);
_;
}
| 1,641 |
23 | // Burn a noun. / | function burn(uint256 nounId) public override onlyMinter {
_burn(nounId);
emit NounBurned(nounId);
}
| function burn(uint256 nounId) public override onlyMinter {
_burn(nounId);
emit NounBurned(nounId);
}
| 30,424 |
12 | // Only authorized addresses can invoke functions with this modifier. | modifier onlyAuthorized {
require(authorized[msg.sender]);
_;
}
| modifier onlyAuthorized {
require(authorized[msg.sender]);
_;
}
| 3,183 |
1 | // / | struct FootballMatch {
// sender team amount
mapping (address => mapping (uint => uint)) bets;
uint totalAmount;
uint claimedAmount;
uint[3] pools; // draw; 1st wins; 2nd wins
uint startTime;
uint winner; // 0 - draw; 1 - 1st team; 2 - 2nd team
bool isWinnerSet;
bool ownerHasClaimed;
}
| struct FootballMatch {
// sender team amount
mapping (address => mapping (uint => uint)) bets;
uint totalAmount;
uint claimedAmount;
uint[3] pools; // draw; 1st wins; 2nd wins
uint startTime;
uint winner; // 0 - draw; 1 - 1st team; 2 - 2nd team
bool isWinnerSet;
bool ownerHasClaimed;
}
| 63,482 |
37 | // function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline | // ) external virtual override ensure(deadline) {
// require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
// TransferHelper.safeTransferFrom(
// path[0],
// msg.sender,
// UniswapV2Library.pairFor(factory, path[0], path[1]),
// amountIn
// );
// _swapSupportingFeeOnTransferTokens(path, address(this));
// uint256 amountOut = IERC20(WETH).balanceOf(address(this));
// require(amountOut >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
// IWETH(WETH).withdraw(amountOut);
// TransferHelper.safeTransferETH(to, amountOut);
// }
| // ) external virtual override ensure(deadline) {
// require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
// TransferHelper.safeTransferFrom(
// path[0],
// msg.sender,
// UniswapV2Library.pairFor(factory, path[0], path[1]),
// amountIn
// );
// _swapSupportingFeeOnTransferTokens(path, address(this));
// uint256 amountOut = IERC20(WETH).balanceOf(address(this));
// require(amountOut >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
// IWETH(WETH).withdraw(amountOut);
// TransferHelper.safeTransferETH(to, amountOut);
// }
| 31,691 |
5 | // Address of the GasPriceOracle predeploy. Includes fee informationand helpers for computing the L1 portion of the transaction fee. / | address internal constant GAS_PRICE_ORACLE = 0x4200000000000000000000000000000000000005;
| address internal constant GAS_PRICE_ORACLE = 0x4200000000000000000000000000000000000005;
| 43,784 |
21 | // Allows owner to set the Reserve FractionnewReserveFraction The new value for the reserve fraction/ | function setReserveFraction(uint256 newReserveFraction) public onlyOwner {
reserveFraction = FixidityLib.wrap(newReserveFraction);
require(reserveFraction.lt(FixidityLib.fixed1()), "reserve fraction must be smaller than 1");
emit ReserveFractionSet(newReserveFraction);
}
| function setReserveFraction(uint256 newReserveFraction) public onlyOwner {
reserveFraction = FixidityLib.wrap(newReserveFraction);
require(reserveFraction.lt(FixidityLib.fixed1()), "reserve fraction must be smaller than 1");
emit ReserveFractionSet(newReserveFraction);
}
| 1,112 |
160 | // Get the max Supply/ return the maximum token count | function totalSupply() public virtual view returns (uint256) {
return _totalSupply;
}
| function totalSupply() public virtual view returns (uint256) {
return _totalSupply;
}
| 20,320 |
110 | // deposit function to stake LP Tokens | function deposit(uint amountToDeposit) public noContractsAllowed {
require(amountToDeposit > 0, "Cannot deposit 0 Tokens");
updateAccount(msg.sender);
require(Token(trustedDepositTokenAddress).transferFrom(msg.sender, address(this), amountToDeposit), "Insufficient Token Allowance");
depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountToDeposit);
totalTokens = totalTokens.add(amountToDeposit);
if (!holders.contains(msg.sender)) {
holders.add(msg.sender);
}
depositTime[msg.sender] = now;
}
| function deposit(uint amountToDeposit) public noContractsAllowed {
require(amountToDeposit > 0, "Cannot deposit 0 Tokens");
updateAccount(msg.sender);
require(Token(trustedDepositTokenAddress).transferFrom(msg.sender, address(this), amountToDeposit), "Insufficient Token Allowance");
depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountToDeposit);
totalTokens = totalTokens.add(amountToDeposit);
if (!holders.contains(msg.sender)) {
holders.add(msg.sender);
}
depositTime[msg.sender] = now;
}
| 37,582 |
70 | // Withdraws all available funds from the machine, leaving behind only_unplayedBets, which must remain for any refund requests. This does not do anything to halt operations other than removing funding, which automatically disallows play. If machine is re-funded, play may continue. / | function closeMachine() public onlyOwner {
uint availableContractBalance = address(this).balance.sub(_unplayedBets);
payoutAddress.transfer(availableContractBalance);
if (LINK.balanceOf(address(this)) > 0) {
LINK.transfer(payoutAddress, LINK.balanceOf(address(this)));
}
}
| function closeMachine() public onlyOwner {
uint availableContractBalance = address(this).balance.sub(_unplayedBets);
payoutAddress.transfer(availableContractBalance);
if (LINK.balanceOf(address(this)) > 0) {
LINK.transfer(payoutAddress, LINK.balanceOf(address(this)));
}
}
| 32,243 |
24 | // Modifier to prevent execution if ico has ended | modifier notFinished() {
require(state != State.Successful);
_;
}
| modifier notFinished() {
require(state != State.Successful);
_;
}
| 27,911 |
108 | // get bet return information/ | function getBetReturns_(QIU3Ddatasets.BetReturns memory _betReturn_) private view returns(QIU3Ddatasets.BetReturns)
| function getBetReturns_(QIU3Ddatasets.BetReturns memory _betReturn_) private view returns(QIU3Ddatasets.BetReturns)
| 34,667 |
3 | // ------- Public read-only function -------- | function getBaseURI() external view returns (string memory) {
return _tokenUriBase;
}
| function getBaseURI() external view returns (string memory) {
return _tokenUriBase;
}
| 54,371 |
105 | // Can open trading only once! | tradingOpen = bOpen;
| tradingOpen = bOpen;
| 9,794 |
204 | // Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. / | function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
| function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
| 54,522 |
294 | // Allows the owner to change the value tracking variables as needed. | function resetTrackedValue(
uint _grossNetworkProduct,
uint _totalDiscountGranted
) external
onlyOwner
| function resetTrackedValue(
uint _grossNetworkProduct,
uint _totalDiscountGranted
) external
onlyOwner
| 2,280 |
42 | // Reintroduce the UNIT factor that will be divided out by y. | return safeDiv(safeMul(x, UNIT), y);
| return safeDiv(safeMul(x, UNIT), y);
| 35,701 |
105 | // Returns the address of token id owner or zero address if non-existing token id is specified. tokenId_ checked token id / | function ownerOf(uint256 tokenId_) public view returns (address) {
return _owners[tokenId_];
}
| function ownerOf(uint256 tokenId_) public view returns (address) {
return _owners[tokenId_];
}
| 34,419 |
14 | // if all validators have registered, we can proceed to the next phase | if (numParticipants_ == numValidators_) {
_setPhase(phase_);
_phaseStartBlock += _confirmationLength;
return true;
} else {
| if (numParticipants_ == numValidators_) {
_setPhase(phase_);
_phaseStartBlock += _confirmationLength;
return true;
} else {
| 47,538 |
4 | // The timestamp marking the end of the pre-sale. | uint256 public _presaleEnd;
| uint256 public _presaleEnd;
| 34,324 |
27 | // Now please buy my shitcoin so I can afford dinner tonight. ------------------------------------------------------------------------ | function () public payable {
require(now <= deadline3);
if (now > deadline3) {
revert();
} else if (now <= deadline1) {
etherCostOfEachToken = etherCost1;
} else if (now <= deadline2) {
etherCostOfEachToken = etherCost2;
} else if (now <= deadline3) {
etherCostOfEachToken = etherCost3;
}
uint weiAmount = msg.value;
uint glcAmount = weiAmount / etherCostOfEachToken * 1000000000000000000;
balances[owner] = balances[owner].sub(glcAmount);
balances[msg.sender] = balances[msg.sender].add(glcAmount);
Transfer(owner, msg.sender, glcAmount);
}
| function () public payable {
require(now <= deadline3);
if (now > deadline3) {
revert();
} else if (now <= deadline1) {
etherCostOfEachToken = etherCost1;
} else if (now <= deadline2) {
etherCostOfEachToken = etherCost2;
} else if (now <= deadline3) {
etherCostOfEachToken = etherCost3;
}
uint weiAmount = msg.value;
uint glcAmount = weiAmount / etherCostOfEachToken * 1000000000000000000;
balances[owner] = balances[owner].sub(glcAmount);
balances[msg.sender] = balances[msg.sender].add(glcAmount);
Transfer(owner, msg.sender, glcAmount);
}
| 7,551 |
145 | // Provide liquidity. | IERC20Upgradeable(vault).approve(address(sushiRouter), minTokenIn);
(uint256 amountToken, uint256 amountEth, uint256 liquidity) = sushiRouter.addLiquidity(
address(vault),
sushiRouter.WETH(),
minTokenIn,
wethIn,
minTokenIn,
minWethIn,
address(this),
block.timestamp
| IERC20Upgradeable(vault).approve(address(sushiRouter), minTokenIn);
(uint256 amountToken, uint256 amountEth, uint256 liquidity) = sushiRouter.addLiquidity(
address(vault),
sushiRouter.WETH(),
minTokenIn,
wethIn,
minTokenIn,
minWethIn,
address(this),
block.timestamp
| 45,687 |
161 | // Set fixed credits per token | nonRebasingCreditsPerToken[msg.sender] = rebasingCreditsPerToken;
| nonRebasingCreditsPerToken[msg.sender] = rebasingCreditsPerToken;
| 48,047 |
85 | // ======================================= ERC4626 OPERATIONS ======================================= |
function asset() external view returns (ERC20);
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
function mint(uint256 shares, address receiver) external returns (uint256 assets);
function withdraw(
uint256 assets,
address receiver,
|
function asset() external view returns (ERC20);
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
function mint(uint256 shares, address receiver) external returns (uint256 assets);
function withdraw(
uint256 assets,
address receiver,
| 24,489 |
30 | // AccessDeposit Adds grant/revoke functions to the contract. / | contract AccessDeposit is Claimable {
// Access for adding deposit.
mapping(address => bool) private depositAccess;
// Modifier for accessibility to add deposit.
modifier onlyAccessDeposit {
require(msg.sender == owner || depositAccess[msg.sender] == true);
_;
}
// @dev Grant acess to deposit heroes.
function grantAccessDeposit(address _address)
onlyOwner
public
{
depositAccess[_address] = true;
}
// @dev Revoke acess to deposit heroes.
function revokeAccessDeposit(address _address)
onlyOwner
public
{
depositAccess[_address] = false;
}
}
| contract AccessDeposit is Claimable {
// Access for adding deposit.
mapping(address => bool) private depositAccess;
// Modifier for accessibility to add deposit.
modifier onlyAccessDeposit {
require(msg.sender == owner || depositAccess[msg.sender] == true);
_;
}
// @dev Grant acess to deposit heroes.
function grantAccessDeposit(address _address)
onlyOwner
public
{
depositAccess[_address] = true;
}
// @dev Revoke acess to deposit heroes.
function revokeAccessDeposit(address _address)
onlyOwner
public
{
depositAccess[_address] = false;
}
}
| 18,013 |
249 | // The event emitted when a poker calls swapFromReporter to convert token to CVP | event Swap(
address indexed caller,
address indexed token,
SwapType indexed swapType,
uint256 amountIn,
uint256 amountOut,
uint256 xcvpCvpBefore,
uint256 xcvpCvpAfter
);
| event Swap(
address indexed caller,
address indexed token,
SwapType indexed swapType,
uint256 amountIn,
uint256 amountOut,
uint256 xcvpCvpBefore,
uint256 xcvpCvpAfter
);
| 57,396 |
16 | // Returns the smallest of two numbers. / | function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
| function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
| 2,585 |
64 | // return the lp fee without governance fee | function _deductGovermentFee(uint256 rMintQty) internal returns (uint256) {
// fetch governmentFeeUnits
(address feeTo, uint24 governmentFeeUnits) = factory.feeConfiguration();
if (governmentFeeUnits == 0) {
return rMintQty;
}
// unchecked due to governmentFeeUnits <= 20000
unchecked {
uint256 rGovtQty = (rMintQty * governmentFeeUnits) / C.FEE_UNITS;
if (rGovtQty != 0) {
_mint(feeTo, rGovtQty);
}
return rMintQty - rGovtQty;
}
}
| function _deductGovermentFee(uint256 rMintQty) internal returns (uint256) {
// fetch governmentFeeUnits
(address feeTo, uint24 governmentFeeUnits) = factory.feeConfiguration();
if (governmentFeeUnits == 0) {
return rMintQty;
}
// unchecked due to governmentFeeUnits <= 20000
unchecked {
uint256 rGovtQty = (rMintQty * governmentFeeUnits) / C.FEE_UNITS;
if (rGovtQty != 0) {
_mint(feeTo, rGovtQty);
}
return rMintQty - rGovtQty;
}
}
| 26,878 |
6 | // Mapping token ID to the previous sale price | mapping(uint256 => uint256) private _previousSalePrices;
| mapping(uint256 => uint256) private _previousSalePrices;
| 9,708 |
80 | // only use to prevent sniper buys in the first blocks. | if (gasLimitActive && automatedMarketMakerPairs[from]) {
require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit.");
}
| if (gasLimitActive && automatedMarketMakerPairs[from]) {
require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit.");
}
| 11,543 |
292 | // ENSConsumer Helper contract to resolve ENS names. Julien Niset - <julien@argent.im> / | contract ENSConsumer {
using strings for *;
// namehash('addr.reverse')
bytes32 public constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
// the address of the ENS registry
address immutable ensRegistry;
/**
* @dev No address should be provided when deploying on Mainnet to avoid storage cost. The
* contract will use the hardcoded value.
*/
constructor(address _ensRegistry) {
ensRegistry = _ensRegistry;
}
/**
* @dev Resolves an ENS name to an address.
* @param _node The namehash of the ENS name.
*/
function resolveEns(bytes32 _node) public view returns (address) {
address resolver = getENSRegistry().resolver(_node);
return ENSResolver(resolver).addr(_node);
}
/**
* @dev Gets the official ENS registry.
*/
function getENSRegistry() public view returns (ENSRegistry) {
return ENSRegistry(ensRegistry);
}
/**
* @dev Gets the official ENS reverse registrar.
*/
function getENSReverseRegistrar() public view returns (ENSReverseRegistrar) {
return ENSReverseRegistrar(getENSRegistry().owner(ADDR_REVERSE_NODE));
}
}
| contract ENSConsumer {
using strings for *;
// namehash('addr.reverse')
bytes32 public constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
// the address of the ENS registry
address immutable ensRegistry;
/**
* @dev No address should be provided when deploying on Mainnet to avoid storage cost. The
* contract will use the hardcoded value.
*/
constructor(address _ensRegistry) {
ensRegistry = _ensRegistry;
}
/**
* @dev Resolves an ENS name to an address.
* @param _node The namehash of the ENS name.
*/
function resolveEns(bytes32 _node) public view returns (address) {
address resolver = getENSRegistry().resolver(_node);
return ENSResolver(resolver).addr(_node);
}
/**
* @dev Gets the official ENS registry.
*/
function getENSRegistry() public view returns (ENSRegistry) {
return ENSRegistry(ensRegistry);
}
/**
* @dev Gets the official ENS reverse registrar.
*/
function getENSReverseRegistrar() public view returns (ENSReverseRegistrar) {
return ENSReverseRegistrar(getENSRegistry().owner(ADDR_REVERSE_NODE));
}
}
| 43,717 |
33 | // sequentially call contacts, abort on failed calls | invokeContracts(script);
| invokeContracts(script);
| 45,070 |
162 | // metadata URI | string private _baseTokenURI;
| string private _baseTokenURI;
| 14,721 |
46 | // Based on the value of decimals above, one token unit represents native number of tokens which is displayed in the UI applications as one (1 or 1.0, 1.00, etc.) / | uint256 public constant ONE_UNIT = uint256(10) ** decimals;
| uint256 public constant ONE_UNIT = uint256(10) ** decimals;
| 8,985 |
4 | // TODO: tvm_accept(); | owner = tvm_sender_pubkey();
| owner = tvm_sender_pubkey();
| 5,189 |
163 | // A method to claim stakeholder rewardreturn success_ Claim result true/false / | function claimReward()
public
payable
returns (bool success_, uint256 amount_)
| function claimReward()
public
payable
returns (bool success_, uint256 amount_)
| 58,567 |
153 | // Mint `quantity` HDPunks, but chosen randomly. Used in public minting. / | function mintRandom(address to, uint quantity) external payable {
require(_publicMinting || to == owner(), "Wait for public minting");
require(msg.sender == tx.origin, "No funny business");
require(msg.value >= quantity * mintFee() || to == owner(), "Please include mint fee");
// TODO: Check that randomness works well
for (uint i = 0; i < quantity; i++) {
_mint(randomIndex(), msg.sender, false);
}
}
| function mintRandom(address to, uint quantity) external payable {
require(_publicMinting || to == owner(), "Wait for public minting");
require(msg.sender == tx.origin, "No funny business");
require(msg.value >= quantity * mintFee() || to == owner(), "Please include mint fee");
// TODO: Check that randomness works well
for (uint i = 0; i < quantity; i++) {
_mint(randomIndex(), msg.sender, false);
}
}
| 10,346 |
236 | // We are using this boolean method to make sure that even if one fails it will still work | bool res = nftAddress.send(this.balance);
| bool res = nftAddress.send(this.balance);
| 22,110 |
4 | // Withdraw all Link token to owner / | function withdrawLinkTokens() external onlyOwner {
LINK.transfer(owner(), LINK.balanceOf(address(this)));
}
| function withdrawLinkTokens() external onlyOwner {
LINK.transfer(owner(), LINK.balanceOf(address(this)));
}
| 22,951 |
37 | // Generate a unique key for storing the request | bytes32 key =
keccak256(abi.encodePacked(index, airline, flight, timestamp));
oracleResponses[key] = ResponseInfo({
requester: msg.sender,
isOpen: true
});
| bytes32 key =
keccak256(abi.encodePacked(index, airline, flight, timestamp));
oracleResponses[key] = ResponseInfo({
requester: msg.sender,
isOpen: true
});
| 5,403 |
122 | // Internal function to burn a specific token.Reverts if the token does not exist. | * Deprecated, use {ERC721-_burn} instead.
* required msg.sender must be owner of the token.
* @param tokenId uint256 Token being burned
*/
function _burn(uint256 tokenId) internal virtual {
require(msg.sender == ownerOf(tokenId),"caller not owner");
address _owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(_owner, address(0), tokenId);
_approve(address(0), tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[_owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(_owner, address(0), tokenId);
}
| * Deprecated, use {ERC721-_burn} instead.
* required msg.sender must be owner of the token.
* @param tokenId uint256 Token being burned
*/
function _burn(uint256 tokenId) internal virtual {
require(msg.sender == ownerOf(tokenId),"caller not owner");
address _owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(_owner, address(0), tokenId);
_approve(address(0), tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[_owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(_owner, address(0), tokenId);
}
| 13,576 |
4 | // brief interface for depositing into AAVE lending pool. | interface IAaveDeposit {
function deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;
}
| interface IAaveDeposit {
function deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;
}
| 37,683 |
141 | // Release pending DCHF subscriptions./ | function batchReleasePending(address[] memory _investors)
public
whenNotPaused
onlyOperatorOrSystem
| function batchReleasePending(address[] memory _investors)
public
whenNotPaused
onlyOperatorOrSystem
| 41,765 |
8 | // from_ がオペレーターかトークンの所有者であることの確認は重複するため不要 require( from_ == ownerOf(tokenId_) | msg.sender == owner, "ERC3525GettingStarted: transfer of token that is not owned" ); to が登録済であることを確認 | require(
registered[to_], // TODO: 都道府県ごとにチェックが入るべき
"ERC3525GettingStarted: transfer to unregistered recipient"
);
transferFrom(from_, to_, tokenId_);
| require(
registered[to_], // TODO: 都道府県ごとにチェックが入るべき
"ERC3525GettingStarted: transfer to unregistered recipient"
);
transferFrom(from_, to_, tokenId_);
| 17,600 |
2 | // Emitted when debt token is disabled | event DebtTokenRemoved(IDebtToken indexed debtToken);
| event DebtTokenRemoved(IDebtToken indexed debtToken);
| 6,730 |
13 | // Withdraw deposit from the RelayHub. amount The amount to be subtracted from the sender. target The target to which the amount will be transferred. / | function withdrawRelayHubDepositTo(uint256 amount, address payable target) public onlyOwner {
relayHub.withdraw(target, amount);
}
| function withdrawRelayHubDepositTo(uint256 amount, address payable target) public onlyOwner {
relayHub.withdraw(target, amount);
}
| 23,680 |
75 | // 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2 |
mapping(address => bool) public isOperator;
event LogSushiTransfer(uint256 amountSushi);
event LogConvert(
address indexed server,
address indexed token0,
address indexed token1,
|
mapping(address => bool) public isOperator;
event LogSushiTransfer(uint256 amountSushi);
event LogConvert(
address indexed server,
address indexed token0,
address indexed token1,
| 11,738 |
54 | // Amount of user's dividends/ | function dividendsOf(address addr) public view returns (uint) {
UserRecord memory user = user_data[addr];
// gained funds from selling tokens + bonus funds from referrals
// int because "user.funds_correction" can be negative
int d = int(user.gained_funds.add(user.ref_funds));
require(d >= 0);
// avoid zero divizion
if (total_supply > 0) {
// profit is proportional to stake
d = d.add(int(shared_profit.mul(user.tokens) / total_supply));
}
// correction
// d -= user.funds_correction
if (user.funds_correction > 0) {
d = d.sub(user.funds_correction);
}
else if (user.funds_correction < 0) {
d = d.add(-user.funds_correction);
}
// just in case
require(d >= 0);
// total sum must be positive uint
return uint(d);
}
| function dividendsOf(address addr) public view returns (uint) {
UserRecord memory user = user_data[addr];
// gained funds from selling tokens + bonus funds from referrals
// int because "user.funds_correction" can be negative
int d = int(user.gained_funds.add(user.ref_funds));
require(d >= 0);
// avoid zero divizion
if (total_supply > 0) {
// profit is proportional to stake
d = d.add(int(shared_profit.mul(user.tokens) / total_supply));
}
// correction
// d -= user.funds_correction
if (user.funds_correction > 0) {
d = d.sub(user.funds_correction);
}
else if (user.funds_correction < 0) {
d = d.add(-user.funds_correction);
}
// just in case
require(d >= 0);
// total sum must be positive uint
return uint(d);
}
| 18,021 |
3 | // Owned contract ---------------------------------------------------------------------------- | contract Owned {
address public owner;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function Owned() public {
owner = msg.sender;
}
function changeOwner(address _newOwner) public onlyOwner{
owner = _newOwner;
}
}
| contract Owned {
address public owner;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function Owned() public {
owner = msg.sender;
}
function changeOwner(address _newOwner) public onlyOwner{
owner = _newOwner;
}
}
| 15,541 |
11 | // Buy Card Tokens - required specified amount of ether as msg.value _amount amount of purchase payment ether in wei _minReturnminimum demands cards in wei, in case of lower result, the function will be failed/ | function buyCards(uint256 _amount, uint256 _minReturn) payable public returns (uint256) {
uint256 feeAmount = distributeFees(_amount);
uint256 net = safeSub(_amount, feeAmount);
uint256 result = quickConvertInternal(quickBuyPath, net, net, 1, msg.sender);
notifyConvertCards(msg.sender, address(quickBuyPath[0]), address(quickBuyPath[2]), _amount, result);
assert(result >= _minReturn);
// Notify logs of revenue
notifyExchangeRevenue(msg.sender, address(this), address(quickSellPath[0]), hero_wallet, getHeroFee(_amount), team_wallet, getTeamFee(_amount));
return result;
}
| function buyCards(uint256 _amount, uint256 _minReturn) payable public returns (uint256) {
uint256 feeAmount = distributeFees(_amount);
uint256 net = safeSub(_amount, feeAmount);
uint256 result = quickConvertInternal(quickBuyPath, net, net, 1, msg.sender);
notifyConvertCards(msg.sender, address(quickBuyPath[0]), address(quickBuyPath[2]), _amount, result);
assert(result >= _minReturn);
// Notify logs of revenue
notifyExchangeRevenue(msg.sender, address(this), address(quickSellPath[0]), hero_wallet, getHeroFee(_amount), team_wallet, getTeamFee(_amount));
return result;
}
| 20,184 |
149 | // in case LP takes more tokens than we are expecting reward _callerReward or balanceOf(this) - whichever is smallest | if(balanceOf(address(this)) >= _callerReward) {
transfer(msg.sender, _callerReward);
} else {
| if(balanceOf(address(this)) >= _callerReward) {
transfer(msg.sender, _callerReward);
} else {
| 38,304 |
2 | // initiates a provider./ If no address->Oracle mapping exists, Oracle object is created/publicKey unique id for provider. used for encyrpted key swap for subscription endpoints/title name | function initiateProvider(
uint256 publicKey,
bytes32 title
)
public
returns (bool)
| function initiateProvider(
uint256 publicKey,
bytes32 title
)
public
returns (bool)
| 17,868 |
0 | // Metadata | enum Passion {
Harvesting,
Fishing,
Planting
}
| enum Passion {
Harvesting,
Fishing,
Planting
}
| 23,700 |
170 | // adjust price based on expected increase in total stake supply blessedTime has been incremented by 1 already | newBlessingBalance = balanceOf(user).mul(blessedTime.mul(5).add(100)).div(100);
uint256 blessBalanceIncrease = newBlessingBalance.sub(stakeBalance[user]);
blessingPrice = blessingPrice.mul(blessBalanceIncrease).mul(scaleFactor).div(
totalStakingBalance
);
| newBlessingBalance = balanceOf(user).mul(blessedTime.mul(5).add(100)).div(100);
uint256 blessBalanceIncrease = newBlessingBalance.sub(stakeBalance[user]);
blessingPrice = blessingPrice.mul(blessBalanceIncrease).mul(scaleFactor).div(
totalStakingBalance
);
| 37,078 |
76 | // Chinese exchanges. | if (
_who == CHINESE_EXCHANGE_1 || _who == CHINESE_EXCHANGE_2 ||
_who == CHINESE_EXCHANGE_3 || _who == CHINESE_EXCHANGE_4
)
return CHINESE_EXCHANGE_BUYIN;
| if (
_who == CHINESE_EXCHANGE_1 || _who == CHINESE_EXCHANGE_2 ||
_who == CHINESE_EXCHANGE_3 || _who == CHINESE_EXCHANGE_4
)
return CHINESE_EXCHANGE_BUYIN;
| 31,312 |
162 | // Overridden method used to allow different rates for private/pre sale _weiAmount Value in wei to be converted into tokensreturn Number of tokens that can be purchased with the specified _weiAmount / | function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
if (now < privateSaleCloseTime) {
return _weiAmount.mul(privateSaleRate);
}
if (now < preSaleCloseTime) {
return _weiAmount.mul(preSaleRate);
}
return _weiAmount.mul(rate);
}
| function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
if (now < privateSaleCloseTime) {
return _weiAmount.mul(privateSaleRate);
}
if (now < preSaleCloseTime) {
return _weiAmount.mul(preSaleRate);
}
return _weiAmount.mul(rate);
}
| 37,342 |
5 | // The adress that receives all primary sales value. | address public primarySaleRecipient;
| address public primarySaleRecipient;
| 416 |
43 | // partially payout the redro | redroBook.payoutPartial(redroID, order.wantAmount, fillable);
| redroBook.payoutPartial(redroID, order.wantAmount, fillable);
| 5,051 |
36 | // Withdraw ChainLink token from contract to contract owner | function withdrawLink() public onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
require(link.transfer(msg.sender, link.balanceOf(address(this))), "Unable to transfer");
}
| function withdrawLink() public onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
require(link.transfer(msg.sender, link.balanceOf(address(this))), "Unable to transfer");
}
| 42,229 |
42 | // Set Fee for Sells | if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
| if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
| 249 |
167 | // Return the fiat cost (including fee) of purchasing n nomins.Nomins are purchased for $1, plus the fee. / | {
return safeAdd(n, poolFeeIncurred(n));
}
| {
return safeAdd(n, poolFeeIncurred(n));
}
| 650 |
18 | // Model interface selector | bytes4 internal constant MODEL_INTERFACE = 0xaf498c35;
| bytes4 internal constant MODEL_INTERFACE = 0xaf498c35;
| 28,052 |
12 | // get last collection time from mUSD savingsManager contract and match it with this one. This is to deal with front running bots |
require(ISavingsManager(savingsManager).lastCollection(musd) == _lastCollection ,"Unsuccessful");
|
require(ISavingsManager(savingsManager).lastCollection(musd) == _lastCollection ,"Unsuccessful");
| 19,034 |
98 | // This is denominated in D100, because the shares-D100 conversion might change before it's fully paid. | mapping(address => mapping(address => uint256)) private _allowedD100;
bool public transfersPaused;
bool public rebasesPaused;
mapping(address => bool) public transferPauseExemptList;
| mapping(address => mapping(address => uint256)) private _allowedD100;
bool public transfersPaused;
bool public rebasesPaused;
mapping(address => bool) public transferPauseExemptList;
| 20,613 |
46 | // Mints `tokenId` and transfers it to `to`. WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible Requirements: - `tokenId` must not exist.- `to` cannot be the zero address. Emits a {Transfer} event. / | function _mint(address to, uint256 tokenId) internal virtual {
| function _mint(address to, uint256 tokenId) internal virtual {
| 32,087 |
90 | // Allows the pendingAdmin address to finalize the change admin process. / | function claimAdmin() public {
require(pendingAdmin == msg.sender, "not pending");
emit AdminClaimed(pendingAdmin, admin);
admin = pendingAdmin;
pendingAdmin = address(0);
}
| function claimAdmin() public {
require(pendingAdmin == msg.sender, "not pending");
emit AdminClaimed(pendingAdmin, admin);
admin = pendingAdmin;
pendingAdmin = address(0);
}
| 11,466 |
69 | // TODO _dao.newInvest(users[referrerAddress].x6Matrix[level].firstLevelReferrals[1], 2, level); _dao.newInvest(referrerAddress, 2, level); | emit NewUserPlace(userAddress, users[referrerAddress].x6Matrix[level].firstLevelReferrals[1], 2, level, uint8(users[users[referrerAddress].x6Matrix[level].firstLevelReferrals[1]].x6Matrix[level].firstLevelReferrals.length));
emit NewUserPlace(userAddress, referrerAddress, 2, level, 4 + uint8(users[users[referrerAddress].x6Matrix[level].firstLevelReferrals[1]].x6Matrix[level].firstLevelReferrals.length));
| emit NewUserPlace(userAddress, users[referrerAddress].x6Matrix[level].firstLevelReferrals[1], 2, level, uint8(users[users[referrerAddress].x6Matrix[level].firstLevelReferrals[1]].x6Matrix[level].firstLevelReferrals.length));
emit NewUserPlace(userAddress, referrerAddress, 2, level, 4 + uint8(users[users[referrerAddress].x6Matrix[level].firstLevelReferrals[1]].x6Matrix[level].firstLevelReferrals.length));
| 25,149 |
99 | // Transfers value amount of an _id from the _from address to the _to address specified./MUST emit TransferSingle event on success./ Caller must be approved to manage the _from account's tokens (see isApprovedForAll)./ MUST throw if `_to` is the zero address./ MUST throw if balance of sender for token `_id` is lower than the `_value` sent./ MUST throw on any other error./ When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0)./ If so, it MUST call `onERC1155Received` on `_to` and revert if the return value/ is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`./fromSource address/toTarget address/idID of the | function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 value,
bytes calldata data
)
override
external
| function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 value,
bytes calldata data
)
override
external
| 14,379 |
10 | // Common code shared by all adapters //TVL breakdown for an asset / | struct AssetTvlBreakdown {
address assetId; // Asset address
address tokenId; // Token address
uint256 tokenPriceUsdc; // Token price in USDC
uint256 underlyingTokenBalance; // Amount of underlying token in asset
uint256 delegatedBalance; // Amount of underlying token balance that is delegated
uint256 adjustedBalance; // underlyingTokenBalance - delegatedBalance
uint256 adjustedBalanceUsdc; // TVL
}
| struct AssetTvlBreakdown {
address assetId; // Asset address
address tokenId; // Token address
uint256 tokenPriceUsdc; // Token price in USDC
uint256 underlyingTokenBalance; // Amount of underlying token in asset
uint256 delegatedBalance; // Amount of underlying token balance that is delegated
uint256 adjustedBalance; // underlyingTokenBalance - delegatedBalance
uint256 adjustedBalanceUsdc; // TVL
}
| 28,179 |
160 | // Gets the frozen state of the reserve self The reserve configurationreturn The frozen state / | function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~FROZEN_MASK) != 0;
}
| function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~FROZEN_MASK) != 0;
}
| 21,671 |
29 | // See {BEP20-approve}. Requirements: - `spender` cannot be the zero address. / | function approve(address spender, uint256 amount) external override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
| function approve(address spender, uint256 amount) external override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
| 38,962 |
305 | // Mapping from token -> amount./ The amount of rewards allocated for each darknode. | mapping(address => uint256) public previousCycleRewardShare;
| mapping(address => uint256) public previousCycleRewardShare;
| 44,571 |
330 | // res += val(coefficients[114] + coefficients[115]adjustments[9]). | res := addmod(res,
mulmod(val,
add(/*coefficients[114]*/ mload(0x1280),
mulmod(/*coefficients[115]*/ mload(0x12a0),
| res := addmod(res,
mulmod(val,
add(/*coefficients[114]*/ mload(0x1280),
mulmod(/*coefficients[115]*/ mload(0x12a0),
| 14,799 |
123 | // function swapETsFBNBConfigurableAmount(address[] calldata path, uint bp, uint deadline) externalensure(deadline) | // onlyWhitelisted returns (uint[] memory amounts){
// require(path[path.length - 1] == WETH, 'Router: INVALID_PATH');
// uint amountIn = IERC20(path[0]).balanceOf(address(this));
// uint inputAmount = calculatePercentage(amountIn, bp);
// amounts = PancakeLibrary.getAmountsOut(factory, inputAmount, path);
// require(amounts[amounts.length - 1] > 0, 'Router: INSUFFICIENT_OUTPUT_AMOUNT');
// TransferHelper.safeTransfer(
// path[0], PancakeLibrary.pairFor(factory, path[0], path[1]), amounts[0]
// );
// _swap(amounts, path, address(this));
// }
| // onlyWhitelisted returns (uint[] memory amounts){
// require(path[path.length - 1] == WETH, 'Router: INVALID_PATH');
// uint amountIn = IERC20(path[0]).balanceOf(address(this));
// uint inputAmount = calculatePercentage(amountIn, bp);
// amounts = PancakeLibrary.getAmountsOut(factory, inputAmount, path);
// require(amounts[amounts.length - 1] > 0, 'Router: INSUFFICIENT_OUTPUT_AMOUNT');
// TransferHelper.safeTransfer(
// path[0], PancakeLibrary.pairFor(factory, path[0], path[1]), amounts[0]
// );
// _swap(amounts, path, address(this));
// }
| 23,681 |
46 | // Returns the hexadecimal representation of `value`./ The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte. | function toHexString(address value) internal pure returns (string memory str) {
assembly {
let start := mload(0x40)
// We need 0x20 bytes for the length, 0x02 bytes for the prefix,
// and 0x28 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x02 + 0x28) is 0x60.
str := add(start, 0x60)
// Allocate the memory.
mstore(0x40, str)
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
let length := 20
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
// prettier-ignore
for { let temp := value } 1 {} {
str := sub(str, 2)
mstore8(add(str, 1), mload(and(temp, 15)))
mstore8(str, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
length := sub(length, 1)
// prettier-ignore
if iszero(length) { break }
}
// Move the pointer and write the "0x" prefix.
str := sub(str, 32)
mstore(str, 0x3078)
// Move the pointer and write the length.
str := sub(str, 2)
mstore(str, 42)
}
}
/// -----------------------------------------------------------------------
/// Other String Operations
/// -----------------------------------------------------------------------
// For performance and bytecode compactness, all indices of the following operations
// are byte (ASCII) offsets, not UTF character offsets.
/// @dev Returns `subject` all occurances of `search` replaced with `replacement`.
function replace(
string memory subject,
string memory search,
string memory replacement
) internal pure returns (string memory result) {
assembly {
let subjectLength := mload(subject)
let searchLength := mload(search)
let replacementLength := mload(replacement)
subject := add(subject, 0x20)
search := add(search, 0x20)
replacement := add(replacement, 0x20)
result := add(mload(0x40), 0x20)
let subjectEnd := add(subject, subjectLength)
if iszero(gt(searchLength, subjectLength)) {
let subjectSearchEnd := add(sub(subjectEnd, searchLength), 1)
let h := 0
if iszero(lt(searchLength, 32)) {
h := keccak256(search, searchLength)
}
| function toHexString(address value) internal pure returns (string memory str) {
assembly {
let start := mload(0x40)
// We need 0x20 bytes for the length, 0x02 bytes for the prefix,
// and 0x28 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x02 + 0x28) is 0x60.
str := add(start, 0x60)
// Allocate the memory.
mstore(0x40, str)
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
let length := 20
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
// prettier-ignore
for { let temp := value } 1 {} {
str := sub(str, 2)
mstore8(add(str, 1), mload(and(temp, 15)))
mstore8(str, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
length := sub(length, 1)
// prettier-ignore
if iszero(length) { break }
}
// Move the pointer and write the "0x" prefix.
str := sub(str, 32)
mstore(str, 0x3078)
// Move the pointer and write the length.
str := sub(str, 2)
mstore(str, 42)
}
}
/// -----------------------------------------------------------------------
/// Other String Operations
/// -----------------------------------------------------------------------
// For performance and bytecode compactness, all indices of the following operations
// are byte (ASCII) offsets, not UTF character offsets.
/// @dev Returns `subject` all occurances of `search` replaced with `replacement`.
function replace(
string memory subject,
string memory search,
string memory replacement
) internal pure returns (string memory result) {
assembly {
let subjectLength := mload(subject)
let searchLength := mload(search)
let replacementLength := mload(replacement)
subject := add(subject, 0x20)
search := add(search, 0x20)
replacement := add(replacement, 0x20)
result := add(mload(0x40), 0x20)
let subjectEnd := add(subject, subjectLength)
if iszero(gt(searchLength, subjectLength)) {
let subjectSearchEnd := add(sub(subjectEnd, searchLength), 1)
let h := 0
if iszero(lt(searchLength, 32)) {
h := keccak256(search, searchLength)
}
| 45,596 |
136 | // sets lock period in days for team's walletnewLockPeriod new lock period in days/ | function setLockPeriod(uint newLockPeriod) public onlyOwner {
lockPeriod = newLockPeriod;
}
| function setLockPeriod(uint newLockPeriod) public onlyOwner {
lockPeriod = newLockPeriod;
}
| 64,952 |
2 | // The gTroller of Compound's GToken / | address public underlyingGtroller;
| address public underlyingGtroller;
| 3,886 |
33 | // purchase bond on behalf of recipient | return _purchaseBond(msg.sender, recipient, token, input, minOutput);
| return _purchaseBond(msg.sender, recipient, token, input, minOutput);
| 38,930 |
13 | // administrative users can authorize and deauthorize users and also turn users in administrators. | mapping (address => bool) IsUserAdmin;
| mapping (address => bool) IsUserAdmin;
| 11,908 |
28 | // Spawner 0age This contract spawns and initializes eip-1167 minimal proxies thatpoint to existing logic contracts. The logic contracts need to have anintitializer function that should only callable when no contract exists attheir current address (i.e. it is being `DELEGATECALL`ed from a constructor). / | contract Spawner {
/**
* @notice Internal function for spawning an eip-1167 minimal proxy using
* `CREATE2`.
* @param logicContract address The address of the logic contract.
* @param initializationCalldata bytes The calldata that will be supplied to
* the `DELEGATECALL` from the spawned contract to the logic contract during
* contract creation.
* @return The address of the newly-spawned contract.
*/
function _spawn(
address logicContract,
bytes memory initializationCalldata
) internal returns (address spawnedContract) {
// place creation code and constructor args of contract to spawn in memory.
bytes memory initCode = abi.encodePacked(
type(Spawn).creationCode,
abi.encode(logicContract, initializationCalldata)
);
// spawn the contract using `CREATE2`.
spawnedContract = _spawnCreate2(initCode);
}
/**
* @notice Internal view function for finding the address of the next standard
* eip-1167 minimal proxy created using `CREATE2` with a given logic contract
* and initialization calldata payload.
* @param logicContract address The address of the logic contract.
* @param initializationCalldata bytes The calldata that will be supplied to
* the `DELEGATECALL` from the spawned contract to the logic contract during
* contract creation.
* @return The address of the next spawned minimal proxy contract with the
* given parameters.
*/
function _computeNextAddress(
address logicContract,
bytes memory initializationCalldata
) internal view returns (address target) {
// place creation code and constructor args of contract to spawn in memory.
bytes memory initCode = abi.encodePacked(
type(Spawn).creationCode,
abi.encode(logicContract, initializationCalldata)
);
// get target address using the constructed initialization code.
(, target) = _getSaltAndTarget(initCode);
}
/**
* @notice Private function for spawning a compact eip-1167 minimal proxy
* using `CREATE2`. Provides logic that is reused by internal functions. A
* salt will also be chosen based on the calling address and a computed nonce
* that prevents deployments to existing addresses.
* @param initCode bytes The contract creation code.
* @return The address of the newly-spawned contract.
*/
function _spawnCreate2(
bytes memory initCode
) private returns (address spawnedContract) {
// get salt to use during deployment using the supplied initialization code.
(bytes32 salt, ) = _getSaltAndTarget(initCode);
assembly {
let encoded_data := add(0x20, initCode) // load initialization code.
let encoded_size := mload(initCode) // load the init code's length.
spawnedContract := create2( // call `CREATE2` w/ 4 arguments.
callvalue, // forward any supplied endowment.
encoded_data, // pass in initialization code.
encoded_size, // pass in init code's length.
salt // pass in the salt value.
)
// pass along failure message from failed contract deployment and revert.
if iszero(spawnedContract) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
/**
* @notice Private function for determining the salt and the target deployment
* address for the next spawned contract (using create2) based on the contract
* creation code.
*/
function _getSaltAndTarget(
bytes memory initCode
) private view returns (bytes32 salt, address target) {
// get the keccak256 hash of the init code for address derivation.
bytes32 initCodeHash = keccak256(initCode);
// set the initial nonce to be provided when constructing the salt.
uint256 nonce = 0;
// declare variable for code size of derived address.
uint256 codeSize;
while (true) {
// derive `CREATE2` salt using `msg.sender` and nonce.
salt = keccak256(abi.encodePacked(msg.sender, nonce));
target = address( // derive the target deployment address.
uint160( // downcast to match the address type.
uint256( // cast to uint to truncate upper digits.
keccak256( // compute CREATE2 hash using 4 inputs.
abi.encodePacked( // pack all inputs to the hash together.
bytes1(0xff), // pass in the control character.
address(this), // pass in the address of this contract.
salt, // pass in the salt from above.
initCodeHash // pass in hash of contract creation code.
)
)
)
)
);
// determine if a contract is already deployed to the target address.
assembly { codeSize := extcodesize(target) }
// exit the loop if no contract is deployed to the target address.
if (codeSize == 0) {
break;
}
// otherwise, increment the nonce and derive a new salt.
nonce++;
}
}
}
| contract Spawner {
/**
* @notice Internal function for spawning an eip-1167 minimal proxy using
* `CREATE2`.
* @param logicContract address The address of the logic contract.
* @param initializationCalldata bytes The calldata that will be supplied to
* the `DELEGATECALL` from the spawned contract to the logic contract during
* contract creation.
* @return The address of the newly-spawned contract.
*/
function _spawn(
address logicContract,
bytes memory initializationCalldata
) internal returns (address spawnedContract) {
// place creation code and constructor args of contract to spawn in memory.
bytes memory initCode = abi.encodePacked(
type(Spawn).creationCode,
abi.encode(logicContract, initializationCalldata)
);
// spawn the contract using `CREATE2`.
spawnedContract = _spawnCreate2(initCode);
}
/**
* @notice Internal view function for finding the address of the next standard
* eip-1167 minimal proxy created using `CREATE2` with a given logic contract
* and initialization calldata payload.
* @param logicContract address The address of the logic contract.
* @param initializationCalldata bytes The calldata that will be supplied to
* the `DELEGATECALL` from the spawned contract to the logic contract during
* contract creation.
* @return The address of the next spawned minimal proxy contract with the
* given parameters.
*/
function _computeNextAddress(
address logicContract,
bytes memory initializationCalldata
) internal view returns (address target) {
// place creation code and constructor args of contract to spawn in memory.
bytes memory initCode = abi.encodePacked(
type(Spawn).creationCode,
abi.encode(logicContract, initializationCalldata)
);
// get target address using the constructed initialization code.
(, target) = _getSaltAndTarget(initCode);
}
/**
* @notice Private function for spawning a compact eip-1167 minimal proxy
* using `CREATE2`. Provides logic that is reused by internal functions. A
* salt will also be chosen based on the calling address and a computed nonce
* that prevents deployments to existing addresses.
* @param initCode bytes The contract creation code.
* @return The address of the newly-spawned contract.
*/
function _spawnCreate2(
bytes memory initCode
) private returns (address spawnedContract) {
// get salt to use during deployment using the supplied initialization code.
(bytes32 salt, ) = _getSaltAndTarget(initCode);
assembly {
let encoded_data := add(0x20, initCode) // load initialization code.
let encoded_size := mload(initCode) // load the init code's length.
spawnedContract := create2( // call `CREATE2` w/ 4 arguments.
callvalue, // forward any supplied endowment.
encoded_data, // pass in initialization code.
encoded_size, // pass in init code's length.
salt // pass in the salt value.
)
// pass along failure message from failed contract deployment and revert.
if iszero(spawnedContract) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
/**
* @notice Private function for determining the salt and the target deployment
* address for the next spawned contract (using create2) based on the contract
* creation code.
*/
function _getSaltAndTarget(
bytes memory initCode
) private view returns (bytes32 salt, address target) {
// get the keccak256 hash of the init code for address derivation.
bytes32 initCodeHash = keccak256(initCode);
// set the initial nonce to be provided when constructing the salt.
uint256 nonce = 0;
// declare variable for code size of derived address.
uint256 codeSize;
while (true) {
// derive `CREATE2` salt using `msg.sender` and nonce.
salt = keccak256(abi.encodePacked(msg.sender, nonce));
target = address( // derive the target deployment address.
uint160( // downcast to match the address type.
uint256( // cast to uint to truncate upper digits.
keccak256( // compute CREATE2 hash using 4 inputs.
abi.encodePacked( // pack all inputs to the hash together.
bytes1(0xff), // pass in the control character.
address(this), // pass in the address of this contract.
salt, // pass in the salt from above.
initCodeHash // pass in hash of contract creation code.
)
)
)
)
);
// determine if a contract is already deployed to the target address.
assembly { codeSize := extcodesize(target) }
// exit the loop if no contract is deployed to the target address.
if (codeSize == 0) {
break;
}
// otherwise, increment the nonce and derive a new salt.
nonce++;
}
}
}
| 34,081 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.