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 |
|---|---|---|---|---|
34 | // update position margin | position.margin += margin;
| position.margin += margin;
| 7,137 |
2 | // Used to withdraw tokens from this Strategy, to the `depositor`'s address depositor is the address to receive the withdrawn funds token is the ERC20 token being transferred out amountShares is the amount of shares being withdrawn This function is only callable by the strategyManager contract. It is invoked inside of the strategyManager'sother functions, and individual share balances are recorded in the strategyManager as well. / | function withdraw(
address depositor,
IERC20 token,
uint256 amountShares
) external;
| function withdraw(
address depositor,
IERC20 token,
uint256 amountShares
) external;
| 22,980 |
122 | // scaling factor can only go up to 2256-1 = initSupplyyamsScalingFactor this is used to check if yamsScalingFactor will be too high to compute balances when rebasing. | return uint256(-1) / initSupply;
| return uint256(-1) / initSupply;
| 3,050 |
4 | // Check payer has sufficient balance and has granted router sufficient allowance | if (ERC20(tokenAddress).balanceOf(msg.sender) < amount ||
ERC20(tokenAddress).allowance(msg.sender, tokenTransferProxy) < amount) {
LogError(uint8(Errors.PAYER_BALANCE_OR_ALLOWANCE_INSUFFICIENT), agreementId);
return 0;
}
| if (ERC20(tokenAddress).balanceOf(msg.sender) < amount ||
ERC20(tokenAddress).allowance(msg.sender, tokenTransferProxy) < amount) {
LogError(uint8(Errors.PAYER_BALANCE_OR_ALLOWANCE_INSUFFICIENT), agreementId);
return 0;
}
| 21,626 |
6 | // Initial value is randomly generated from https:www.random.org/ | bytes32 public merkleRoot = 0xa204682a31130d0acf7f63a1c180deb6c1036ec25a02190ba096e18033065319;
| bytes32 public merkleRoot = 0xa204682a31130d0acf7f63a1c180deb6c1036ec25a02190ba096e18033065319;
| 54,292 |
3 | // Can be upgraded | Done,
| Done,
| 28,721 |
17 | // Fetching the NFT's list the user posses. | function fetchMyNFTs() public view returns (MarketItem[] memory) {
uint256 totalItemCount = _itemIds.current();
uint256 itemCount = 0;
uint256 currentIndex = 0;
for (uint256 i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].owner == msg.sender) {
itemCount += 1;
}
}
MarketItem[] memory items = new MarketItem[](itemCount);
for (uint256 i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].owner == msg.sender) {
uint256 currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
| function fetchMyNFTs() public view returns (MarketItem[] memory) {
uint256 totalItemCount = _itemIds.current();
uint256 itemCount = 0;
uint256 currentIndex = 0;
for (uint256 i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].owner == msg.sender) {
itemCount += 1;
}
}
MarketItem[] memory items = new MarketItem[](itemCount);
for (uint256 i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].owner == msg.sender) {
uint256 currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
| 37,692 |
24 | // ERC223 method to transfer token to a specified address with data._to The address to transfer to._value The amount to be transferred._data Transaction metadata./ | function transfer(address _to, uint256 _value, bytes _data) public validAddress(_to) returns (bool success) {
uint codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
// Call token fallback function if _to is a contract. Rejects if not implemented.
if (codeLength > 0) {
ERC223ReceivingContract(_to).tokenFallback(msg.sender, _value, _data);
}
emit Transfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
| function transfer(address _to, uint256 _value, bytes _data) public validAddress(_to) returns (bool success) {
uint codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
// Call token fallback function if _to is a contract. Rejects if not implemented.
if (codeLength > 0) {
ERC223ReceivingContract(_to).tokenFallback(msg.sender, _value, _data);
}
emit Transfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
| 81,124 |
11 | // If no period is desired, instead set startBonus = 100% and bonusPeriod to a small value like 1sec. | require(bonusPeriodSec_ != 0, "EnokiGeyser: bonus period is zero");
require(initialSharesPerToken > 0, "EnokiGeyser: initialSharesPerToken is zero");
| require(bonusPeriodSec_ != 0, "EnokiGeyser: bonus period is zero");
require(initialSharesPerToken > 0, "EnokiGeyser: initialSharesPerToken is zero");
| 18,210 |
2 | // emit OwnershipTransferred(owner, newOwner); | owner = newOwner;
| owner = newOwner;
| 25,195 |
94 | // Save the new position. | totalOfAllPositionsForGameOption[
gameOptionKey
] = newTotalAmountCommitted;
position.amount = newPositionSize;
| totalOfAllPositionsForGameOption[
gameOptionKey
] = newTotalAmountCommitted;
position.amount = newPositionSize;
| 23,314 |
14 | // Name must only include upper and lowercase English letters,/ numbers, and certain characters: ! ( ) - . _ SPACE/ Function will return false if the name is not valid/ or if it's too similar to a name that's already taken. | function setName(string name) returns (bool success) {
require (validateNameInternal(name));
uint fuzzyHash = computeNameFuzzyHash(name);
uint oldFuzzyHash;
string storage oldName = playerNames[msg.sender];
bool oldNameEmpty = bytes(oldName).length == 0;
if (nameTaken[fuzzyHash]) {
require(!oldNameEmpty);
oldFuzzyHash = computeNameFuzzyHash(oldName);
require(fuzzyHash == oldFuzzyHash);
| function setName(string name) returns (bool success) {
require (validateNameInternal(name));
uint fuzzyHash = computeNameFuzzyHash(name);
uint oldFuzzyHash;
string storage oldName = playerNames[msg.sender];
bool oldNameEmpty = bytes(oldName).length == 0;
if (nameTaken[fuzzyHash]) {
require(!oldNameEmpty);
oldFuzzyHash = computeNameFuzzyHash(oldName);
require(fuzzyHash == oldFuzzyHash);
| 60 |
6 | // Instance variables | uint256 public totalDeposit;
uint256 public totalInterestOwed;
| uint256 public totalDeposit;
uint256 public totalInterestOwed;
| 13,346 |
4 | // Calculates and returns`_tree`'s current root | function root(Tree storage _tree) internal view returns (bytes32) {
return rootWithCtx(_tree, zeroHashes());
}
| function root(Tree storage _tree) internal view returns (bytes32) {
return rootWithCtx(_tree, zeroHashes());
}
| 20,594 |
119 | // After reducing the redeem fee, the remaining pool tokens are burned! | IERC20MintableBurnable(poolToken).burnFrom(msg.sender, _amount);
emit Redeemed(msg.sender, _amount.add(feeAmount), amounts, feeAmount);
| IERC20MintableBurnable(poolToken).burnFrom(msg.sender, _amount);
emit Redeemed(msg.sender, _amount.add(feeAmount), amounts, feeAmount);
| 48,766 |
9 | // Check if the given pair is a whitelisted pair Args:pair: pair to check if whitelisted Return: True if whitelisted / | function isWhitelisted(address pair) public view returns (bool) {
return
avaxPairs.contains(pair) ||
partyPairs.contains(pair) ||
stableTokenPairs.contains(pair);
}
| function isWhitelisted(address pair) public view returns (bool) {
return
avaxPairs.contains(pair) ||
partyPairs.contains(pair) ||
stableTokenPairs.contains(pair);
}
| 10,478 |
354 | // Token ID to its URI | mapping (uint256 => string) internal tokenUris;
| mapping (uint256 => string) internal tokenUris;
| 38,073 |
44 | // IERC20 public good; | mapping (address => bool) public minters;
| mapping (address => bool) public minters;
| 52,756 |
66 | // Adds two unsigned integers, returns 2^256 - 1 on overflow. / | function addCap(uint _a, uint _b) internal pure returns (uint) {
uint c = _a + _b;
return c >= _a ? c : UINT_MAX;
}
| function addCap(uint _a, uint _b) internal pure returns (uint) {
uint c = _a + _b;
return c >= _a ? c : UINT_MAX;
}
| 53,796 |
120 | // 0xDefensor - 29.76 MKR - 0x9542b441d65B6BF4dDdd3d4D2a66D8dCB9EE07a9 | mkr.transfer(DEFENSOR, 29.76 ether); // NOTE: ether is a keyword helper, only MKR is transferred here
| mkr.transfer(DEFENSOR, 29.76 ether); // NOTE: ether is a keyword helper, only MKR is transferred here
| 8,514 |
9 | // Transfer `tokens` tokens from `src` to `dst` by `spender` Called by both `transfer` and `transferFrom` internally spender The address of the account performing the transfer src The address of the source account dst The address of the destination account tokens The number of tokens to transferreturn Whether or not the transfer succeeded / | function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = type(uint).max;
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != type(uint).max) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
// unused function
// comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
| function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = type(uint).max;
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != type(uint).max) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
// unused function
// comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
| 12,213 |
687 | // totalReward(usersInvestmentTotal / overallEpochTotal)(secondsToClaim / epochLength) |
return proportionalRewardShare;
|
return proportionalRewardShare;
| 46,561 |
13 | // Set initial failure thresholds (10% of vault balance at time of test deploy) | address vault;
uint256 numVaults = thetaVaults.length;
for (uint256 i; i < numVaults; i++) {
vault = thetaVaults[i];
thresholds[vault] = (calculateAssetBalance(vault) * INITIAL_FAILURE_THRESHOLD_PERCENT) / 100;
testedContracts.push(vault);
}
| address vault;
uint256 numVaults = thetaVaults.length;
for (uint256 i; i < numVaults; i++) {
vault = thetaVaults[i];
thresholds[vault] = (calculateAssetBalance(vault) * INITIAL_FAILURE_THRESHOLD_PERCENT) / 100;
testedContracts.push(vault);
}
| 27,531 |
15 | // _v != 0 && key != _k | if and(iszero(iszero(_v)), iszero(eq(key, _k))) {
| if and(iszero(iszero(_v)), iszero(eq(key, _k))) {
| 1,812 |
60 | // [Tier 1: 10% Sell Fee] | txTaxes["marketingSellTax"] = 4; // 4% DAO, Governance, Farming Pools
txTaxes["developmentSellTax"] = 3; // 3% Marketing Fee
txTaxes["coreteamSellTax"] = 1; // 1% Development Fee
txTaxes["daoandfarmingSellTax"] = 2; // 2% DecentraWorld's Core-Team
| txTaxes["marketingSellTax"] = 4; // 4% DAO, Governance, Farming Pools
txTaxes["developmentSellTax"] = 3; // 3% Marketing Fee
txTaxes["coreteamSellTax"] = 1; // 1% Development Fee
txTaxes["daoandfarmingSellTax"] = 2; // 2% DecentraWorld's Core-Team
| 21,756 |
48 | // Transfer approved withdrawal amount from the contract to the caller. | collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
| collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
| 27,474 |
93 | // The indicate we consumed the input bond and (inputBondunderlyingPerBond) | amountsIn[baseIndex] = neededUnderlying;
amountsIn[bondIndex] = inputBond;
| amountsIn[baseIndex] = neededUnderlying;
amountsIn[bondIndex] = inputBond;
| 66,595 |
3 | // amount of weico recieved by each random inflation recipient | uint256 randomInflationReward;
| uint256 randomInflationReward;
| 9,827 |
17 | // Returns an amount available for withdrawal (unused ASX tokensamount) by an owner.return A withdrawable amount. / | function getWithdrawableASXAmount() public view returns (uint256) {
return token.balanceOf(address(this)) - totalDistributionAmount;
}
| function getWithdrawableASXAmount() public view returns (uint256) {
return token.balanceOf(address(this)) - totalDistributionAmount;
}
| 37,859 |
2 | // part of left amount going to pot | uint16 POTP = 0; // DIVP and POTP are both 100; scaled to dev factor.
| uint16 POTP = 0; // DIVP and POTP are both 100; scaled to dev factor.
| 33,182 |
162 | // will revert if disagreement found | sourceToDestSwapRate = IPriceFeeds(priceFeeds).checkPriceDisagreement(
sourceToken,
destToken,
sourceTokenAmountUsed,
destTokenAmountReceived,
maxDisagreement
);
emit LoanSwap(
loanId,
| sourceToDestSwapRate = IPriceFeeds(priceFeeds).checkPriceDisagreement(
sourceToken,
destToken,
sourceTokenAmountUsed,
destTokenAmountReceived,
maxDisagreement
);
emit LoanSwap(
loanId,
| 963 |
7 | // Receive the response in the form of uint256 / | function fulfill(bytes32 _requestId, uint256 _volume) public recordChainlinkFulfillment(_requestId)
| function fulfill(bytes32 _requestId, uint256 _volume) public recordChainlinkFulfillment(_requestId)
| 28,484 |
220 | // ========== CONSTANT FUNCTIONS ========== / these should stay the same across different wants. |
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
|
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
| 7,771 |
88 | // Cancel the proposal | settings.treasury.cancel(_proposalId);
| settings.treasury.cancel(_proposalId);
| 17,966 |
21 | // Underflow of the sender's balance is impossible because we check for ownership above and the recipient's balance can't realistically overflow. | unchecked {
balanceOf[from]--;
balanceOf[to]++;
}
| unchecked {
balanceOf[from]--;
balanceOf[to]++;
}
| 23,390 |
35 | // Solve t in emaPremium == y equationy Required function output. v0 LastEMAPremium. _lastPremium LastPremium. / | function timeOnFundingCurve(
int256 y,
int256 v0,
int256 _lastPremium
)
internal
view
returns (
int256 t // normal int, not WAD
)
| function timeOnFundingCurve(
int256 y,
int256 v0,
int256 _lastPremium
)
internal
view
returns (
int256 t // normal int, not WAD
)
| 27,819 |
1 | // View functions | function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
addresses = new bytes32[](4);
addresses[0] = CONTRACT_ISSUER;
addresses[1] = CONTRACT_EXCHANGER;
addresses[2] = CONTRACT_BRIDGESTATEPUSD;
addresses[3] = CONTRACT_EXCHANGERATES;
}
| function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
addresses = new bytes32[](4);
addresses[0] = CONTRACT_ISSUER;
addresses[1] = CONTRACT_EXCHANGER;
addresses[2] = CONTRACT_BRIDGESTATEPUSD;
addresses[3] = CONTRACT_EXCHANGERATES;
}
| 17,559 |
689 | // get ETH in return to LUSD | function swap(uint lusdAmount, uint minEthReturn, address payable dest) public returns(uint) {
(uint ethAmount, uint feeAmount) = getSwapEthAmount(lusdAmount);
require(ethAmount >= minEthReturn, "swap: low return");
LUSD.transferFrom(msg.sender, address(this), lusdAmount);
SP.provideToSP(lusdAmount, frontEndTag);
if(feeAmount > 0) feePool.transfer(feeAmount);
(bool success, ) = dest.call{ value: ethAmount }(""); // re-entry is fine here
require(success, "swap: sending ETH failed");
emit RebalanceSwap(msg.sender, lusdAmount, ethAmount, now);
return ethAmount;
}
| function swap(uint lusdAmount, uint minEthReturn, address payable dest) public returns(uint) {
(uint ethAmount, uint feeAmount) = getSwapEthAmount(lusdAmount);
require(ethAmount >= minEthReturn, "swap: low return");
LUSD.transferFrom(msg.sender, address(this), lusdAmount);
SP.provideToSP(lusdAmount, frontEndTag);
if(feeAmount > 0) feePool.transfer(feeAmount);
(bool success, ) = dest.call{ value: ethAmount }(""); // re-entry is fine here
require(success, "swap: sending ETH failed");
emit RebalanceSwap(msg.sender, lusdAmount, ethAmount, now);
return ethAmount;
}
| 10,459 |
119 | // xref:ROOT:erc1155.adocbatch-operations[Batched] version of {_burn}. Emits a {TransferBatch} event. Requirements: - `ids` and `amounts` must have the same length. / | function _burnBatch(address from, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
| function _burnBatch(address from, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
| 8,497 |
42 | // initalize the deployed contract _addressBook addressbook module _owner account owner address / | function initialize(address _addressBook, address _owner) external initializer {
require(_addressBook != address(0), "C7");
require(_owner != address(0), "C8");
__Ownable_init(_owner);
__ReentrancyGuard_init_unchained();
addressbook = AddressBookInterface(_addressBook);
_refreshConfigInternal();
callRestricted = true;
}
| function initialize(address _addressBook, address _owner) external initializer {
require(_addressBook != address(0), "C7");
require(_owner != address(0), "C8");
__Ownable_init(_owner);
__ReentrancyGuard_init_unchained();
addressbook = AddressBookInterface(_addressBook);
_refreshConfigInternal();
callRestricted = true;
}
| 44,754 |
34 | // Mark it claimed and send the token. | _setClaimed(index[i], rootHashes[i]);
require(IERC20(XIO_CONTRACT).transfer(account, amount[i]), "MerkleDistributor: Transfer failed.");
emit Claimed(index[i], account, amount[i],rootHashes[i]);
| _setClaimed(index[i], rootHashes[i]);
require(IERC20(XIO_CONTRACT).transfer(account, amount[i]), "MerkleDistributor: Transfer failed.");
emit Claimed(index[i], account, amount[i],rootHashes[i]);
| 16,306 |
1 | // Deposit Mapping | mapping(address => uint256[]) public amountDepositPerAddress;
mapping(address => uint256[]) public timeDepositPerAddress;
| mapping(address => uint256[]) public amountDepositPerAddress;
mapping(address => uint256[]) public timeDepositPerAddress;
| 62,270 |
27 | // total eth | _totalCoin = _totalCoin.add(msg.value);
| _totalCoin = _totalCoin.add(msg.value);
| 7,822 |
11 | // console.log('ETH', ETH);console.log('LUSDAmount', LUSDAmount); |
echidnaProxy.openTrovePrx(ETH, LUSDAmount, address(0), address(0), 0);
numberOfTroves = troveManager.getTroveOwnersCount();
assert(numberOfTroves > 0);
|
echidnaProxy.openTrovePrx(ETH, LUSDAmount, address(0), address(0), 0);
numberOfTroves = troveManager.getTroveOwnersCount();
assert(numberOfTroves > 0);
| 18,684 |
12 | // Require the function call went through EntryPoint or owner | function _requireFromEntryPointOrOwner() internal view {
require(msg.sender == address(entryPoint()) || msg.sender == owner, "account: not Owner or EntryPoint");
}
| function _requireFromEntryPointOrOwner() internal view {
require(msg.sender == address(entryPoint()) || msg.sender == owner, "account: not Owner or EntryPoint");
}
| 17,099 |
537 | // Updates the global index, reflecting cumulative rewards given out per staked token. totalStakedThe total staked balance, which should be constant in the interval (_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp).settleUpToTimestampThe timestamp up to which to settle rewards. It MUST satisfy `settleUpToTimestamp <= block.timestamp`. return The new global index. / | function _settleGlobalIndexUpToTimestamp(
uint256 totalStaked,
uint256 settleUpToTimestamp
)
private
returns (uint256)
| function _settleGlobalIndexUpToTimestamp(
uint256 totalStaked,
uint256 settleUpToTimestamp
)
private
returns (uint256)
| 30,157 |
47 | // Update the list of NFT contracts that can Timelock any NFT for Front-run Protection | function setPermsForTimelockAny(address contractAddress, bool state)
external
override
virtual
onlyOwner
| function setPermsForTimelockAny(address contractAddress, bool state)
external
override
virtual
onlyOwner
| 73,857 |
98 | // Joins an array of slices, using `self` as a delimiter, returning a newly allocated string. self The delimiter to use. parts A list of slices to join.return A newly allocated string containing all the slices in `parts`,joined with `self`. / | function join(slice memory self, slice[] memory parts)
internal
pure
returns (string memory)
| function join(slice memory self, slice[] memory parts)
internal
pure
returns (string memory)
| 33,121 |
13 | // Pause a currently unpaused role and emit a `RolePaused` event. Onlythe owner or the designated pauser may call this function. Also, bear inmind that only the owner may unpause a role once paused. role The role to pause. / | function pause(Role role) public override onlyAdminOr(Role.PAUSER) {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(!storedRoleStatus.paused, "EndaomentAdmin: Role in question is already paused.");
storedRoleStatus.paused = true;
emit RolePaused(role);
}
| function pause(Role role) public override onlyAdminOr(Role.PAUSER) {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(!storedRoleStatus.paused, "EndaomentAdmin: Role in question is already paused.");
storedRoleStatus.paused = true;
emit RolePaused(role);
}
| 7,911 |
21 | // Calculate percent and return result | function calculatePercentage(uint256 PercentOf, uint256 percentTo ) internal pure returns (uint256)
| function calculatePercentage(uint256 PercentOf, uint256 percentTo ) internal pure returns (uint256)
| 53,661 |
8 | // for servicer to easily check if retainer is in escrowAddress | function checkEscrow() public restricted view returns(uint256) {
return ierc20.balanceOf(escrowAddress);
}
| function checkEscrow() public restricted view returns(uint256) {
return ierc20.balanceOf(escrowAddress);
}
| 50,853 |
0 | // All of the details of an auction's completion, | event OrderFilledAuction(
uint256 auctionId,
address nftContractAddress,
address winner,
uint256 amount
);
| event OrderFilledAuction(
uint256 auctionId,
address nftContractAddress,
address winner,
uint256 amount
);
| 21,523 |
206 | // set a new royalty receiver and rate, Can only be set by the `royaltyAdmin`./newReceiver the address that should receive the royalty proceeds./royaltyPer10Thousands the share of the salePrice (in 1/10000) given to the receiver. | function setRoyaltyParameters(address newReceiver, uint96 royaltyPer10Thousands) external {
require(msg.sender == royaltyAdmin, "NOT_AUTHORIZED");
// require(royaltyPer10Thousands <= 50, "ROYALTY_TOO_HIGH"); ?
_royalty.receiver = newReceiver;
_royalty.per10Thousands = royaltyPer10Thousands;
emit RoyaltySet(newReceiver, royaltyPer10Thousands);
}
| function setRoyaltyParameters(address newReceiver, uint96 royaltyPer10Thousands) external {
require(msg.sender == royaltyAdmin, "NOT_AUTHORIZED");
// require(royaltyPer10Thousands <= 50, "ROYALTY_TOO_HIGH"); ?
_royalty.receiver = newReceiver;
_royalty.per10Thousands = royaltyPer10Thousands;
emit RoyaltySet(newReceiver, royaltyPer10Thousands);
}
| 35,052 |
116 | // the liquidation threshold of the reserve. Expressed in percentage (0-100) | uint256 liquidationThreshold;
| uint256 liquidationThreshold;
| 23,832 |
131 | // last = (n(n-1)(-d))/2 | uint256 last = n.mul(n.sub(1)).mul(d).div(2);
uint256 sn = first.sub(last);
return other.add(sn).sub(totalMintAmount);
| uint256 last = n.mul(n.sub(1)).mul(d).div(2);
uint256 sn = first.sub(last);
return other.add(sn).sub(totalMintAmount);
| 78,060 |
11 | // Toggle if asset allow list is being enforced | bool public useAssetAllowlist;
| bool public useAssetAllowlist;
| 8,447 |
34 | // used for interacting with uniswap | if (token0 == kassiahomeAddress_) {
isToken0 = true;
} else {
| if (token0 == kassiahomeAddress_) {
isToken0 = true;
} else {
| 10,098 |
57 | // tokenWallet address of the token wallet / | function setTokenWallet(address tokenWallet) external onlyOwner {
_setTokenWallet(tokenWallet);
}
| function setTokenWallet(address tokenWallet) external onlyOwner {
_setTokenWallet(tokenWallet);
}
| 2,838 |
0 | // NFTの値段 | uint public cost = 0.025 ether;
| uint public cost = 0.025 ether;
| 24,340 |
21 | // Return indicating whether this is a valid service type / | function serviceTypeIsValid(bytes32 _serviceType)
external view returns (bool)
| function serviceTypeIsValid(bytes32 _serviceType)
external view returns (bool)
| 49,010 |
24 | // verify that the converter is inactive or that the owner is the upgrader contract | require(!isActive() || owner == converterUpgrader, "ERR_ACCESS_DENIED");
_to.transfer(address(this).balance);
| require(!isActive() || owner == converterUpgrader, "ERR_ACCESS_DENIED");
_to.transfer(address(this).balance);
| 17,666 |
147 | // produces non-zero if sender does not have all of the perms in the old scheme | require(bytes4(0x1F)&(scheme.permissions&(~schemes[msg.sender].permissions)) == bytes4(0));
| require(bytes4(0x1F)&(scheme.permissions&(~schemes[msg.sender].permissions)) == bytes4(0));
| 8,073 |
4 | // Check if address is a valid destination to transfer tokens to- must not be zero address- must not be the token address- must not be the owner's address- must not be the admin's address- must not be the token offering contract address / | modifier validDestination(address to) {
require(to != address(0x0));
require(to != address(this));
require(to != owner);
require(to != address(adminAddr));
require(to != address(tokenAllowanceAddr));
_;
}
| modifier validDestination(address to) {
require(to != address(0x0));
require(to != address(this));
require(to != owner);
require(to != address(adminAddr));
require(to != address(tokenAllowanceAddr));
_;
}
| 13,154 |
50 | // 1 - scheduled departure and arrival time in the format /dep/YYYY/MM/DD | bytes32 departureYearMonthDay;
| bytes32 departureYearMonthDay;
| 38,044 |
45 | // reqAmount would now be set to zero, no longer need to reserve, so breaking | break;
| break;
| 2,331 |
88 | // Updates `rewardPerShare` and `lastUpdatedBlockNumber`. strategyId An ID of an earning strategy. / | function _updateStrategyRewards(uint256 strategyId) private {
Strategy storage strategy = strategies[strategyId];
strategy.rewardPerShare = _getUpdatedRewardPerShare(strategyId);
strategy.lastUpdatedBlockNumber = block.number;
}
| function _updateStrategyRewards(uint256 strategyId) private {
Strategy storage strategy = strategies[strategyId];
strategy.rewardPerShare = _getUpdatedRewardPerShare(strategyId);
strategy.lastUpdatedBlockNumber = block.number;
}
| 36,017 |
112 | // the following code is to allow the Kyber trade to fail silently and not revert if it does, preventing a "bubble up" / will revert is disagreement found | _verifyPriceAgreement(
sourceTokenAddress,
destTokenAddress,
sourceTokenAmountUsed,
destTokenAmountReceived
);
| _verifyPriceAgreement(
sourceTokenAddress,
destTokenAddress,
sourceTokenAmountUsed,
destTokenAmountReceived
);
| 10,280 |
2 | // Views | function balanceOf(address account) external view returns (uint256);
function earned(address account) external view returns (uint256);
function getRewardForDuration() external view returns (uint256);
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
| function balanceOf(address account) external view returns (uint256);
function earned(address account) external view returns (uint256);
function getRewardForDuration() external view returns (uint256);
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
| 18,146 |
202 | // The mapping from deposit id to interest transfer date | mapping(uint256 => uint256) _interestTransferDates;
| mapping(uint256 => uint256) _interestTransferDates;
| 22,139 |
167 | // the fees owed to the position owner in token0/token1 | uint128 tokensOwed0;
uint128 tokensOwed1;
| uint128 tokensOwed0;
uint128 tokensOwed1;
| 46,894 |
28 | // [INTERNAL] Remove a token from a specific partition. from Token holder. partition Name of the partition. value Number of tokens to transfer. / | function _removeTokenFromPartition(address from, bytes32 partition, uint256 value) internal {
_balanceOfByPartition[from][partition] = _balanceOfByPartition[from][partition].sub(value);
_totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].sub(value);
// If the balance of the TokenHolder's partition is zero, finds and deletes the partition.
if(_balanceOfByPartition[from][partition] == 0) {
for (uint i = 0; i < _partitionsOf[from].length; i++) {
if(_partitionsOf[from][i] == partition) {
_partitionsOf[from][i] = _partitionsOf[from][_partitionsOf[from].length - 1];
delete _partitionsOf[from][_partitionsOf[from].length - 1];
_partitionsOf[from].length--;
break;
}
}
}
// If the total supply is zero, finds and deletes the partition.
if(_totalSupplyByPartition[partition] == 0) {
for (i = 0; i < _totalPartitions.length; i++) {
if(_totalPartitions[i] == partition) {
_totalPartitions[i] = _totalPartitions[_totalPartitions.length - 1];
delete _totalPartitions[_totalPartitions.length - 1];
_totalPartitions.length--;
break;
}
}
}
}
| function _removeTokenFromPartition(address from, bytes32 partition, uint256 value) internal {
_balanceOfByPartition[from][partition] = _balanceOfByPartition[from][partition].sub(value);
_totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].sub(value);
// If the balance of the TokenHolder's partition is zero, finds and deletes the partition.
if(_balanceOfByPartition[from][partition] == 0) {
for (uint i = 0; i < _partitionsOf[from].length; i++) {
if(_partitionsOf[from][i] == partition) {
_partitionsOf[from][i] = _partitionsOf[from][_partitionsOf[from].length - 1];
delete _partitionsOf[from][_partitionsOf[from].length - 1];
_partitionsOf[from].length--;
break;
}
}
}
// If the total supply is zero, finds and deletes the partition.
if(_totalSupplyByPartition[partition] == 0) {
for (i = 0; i < _totalPartitions.length; i++) {
if(_totalPartitions[i] == partition) {
_totalPartitions[i] = _totalPartitions[_totalPartitions.length - 1];
delete _totalPartitions[_totalPartitions.length - 1];
_totalPartitions.length--;
break;
}
}
}
}
| 11,721 |
64 | // MANAGEMENT OF PERMITTED REWARD TOKENS / | function isPermittedRewardToken(address token) public view returns (bool) {
return permittedRewardTokens.contains(token);
}
| function isPermittedRewardToken(address token) public view returns (bool) {
return permittedRewardTokens.contains(token);
}
| 29,130 |
523 | // contract creator has full privileges | userRoles[msg.sender] = FULL_PRIVILEGES_MASK;
| userRoles[msg.sender] = FULL_PRIVILEGES_MASK;
| 7,209 |
8 | // Emitted when treasury address is changed / | event NewTreasuryAddress(address oldTreasuryAddress, address newTreasuryAddress);
| event NewTreasuryAddress(address oldTreasuryAddress, address newTreasuryAddress);
| 44,110 |
10 | // Fallback Manager - A contract that manages fallback calls made to this contract/Richard Meissner - <richard@gnosis.pm> | contract GuardManager is SelfAuthorized {
event ChangedGuard(address guard);
// keccak256("guard_manager.guard.address")
bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8;
/// @dev Set a guard that checks transactions before execution
/// @param guard The address of the guard to be used or the 0 address to disable the guard
function setGuard(address guard) external authorized {
if (guard != address(0)) {
require(Guard(guard).supportsInterface(type(Guard).interfaceId), "GS300");
}
bytes32 slot = GUARD_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, guard)
}
emit ChangedGuard(guard);
}
function getGuard() internal view returns (address guard) {
bytes32 slot = GUARD_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
guard := sload(slot)
}
}
}
| contract GuardManager is SelfAuthorized {
event ChangedGuard(address guard);
// keccak256("guard_manager.guard.address")
bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8;
/// @dev Set a guard that checks transactions before execution
/// @param guard The address of the guard to be used or the 0 address to disable the guard
function setGuard(address guard) external authorized {
if (guard != address(0)) {
require(Guard(guard).supportsInterface(type(Guard).interfaceId), "GS300");
}
bytes32 slot = GUARD_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, guard)
}
emit ChangedGuard(guard);
}
function getGuard() internal view returns (address guard) {
bytes32 slot = GUARD_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
guard := sload(slot)
}
}
}
| 20,365 |
74 | // Returns the index of a reporter timestamp in the timestamp array for a specific data ID _queryId is ID of the specific data feed _timestamp is the timestamp to find in the timestamps arrayreturn uint256 of the index of the reporter timestamp in the array for specific ID / | function getTimestampIndexByTimestamp(bytes32 _queryId, uint256 _timestamp)
external
view
returns (uint256)
| function getTimestampIndexByTimestamp(bytes32 _queryId, uint256 _timestamp)
external
view
returns (uint256)
| 18,221 |
4 | // Event to log new BathPairs and their bathTokens | event LogNewBathPair(
address newPair,
address newPairBathAsset,
address newPairBathQuote,
address newPairAsset,
address newPairQuote,
uint8 newPairStratRewardRate
);
| event LogNewBathPair(
address newPair,
address newPairBathAsset,
address newPairBathQuote,
address newPairAsset,
address newPairQuote,
uint8 newPairStratRewardRate
);
| 17,523 |
75 | // Update deposit | uint256 newDeposit = compoundedDebtDeposit;
| uint256 newDeposit = compoundedDebtDeposit;
| 41,555 |
5 | // Now increase the daily reward |
uint8 _days; // local variable to make this easier to implement
|
uint8 _days; // local variable to make this easier to implement
| 31,295 |
138 | // check if there is something in bufffer | if (_buffer > 0) {
| if (_buffer > 0) {
| 36,522 |
13 | // ERC721A Queryable ERC721A subclass with convenience query functions. / | abstract contract ERC721AQueryable is ERC721A, IERC721AQueryable {
/**
* @dev Returns the `TokenOwnership` struct at `tokenId` without reverting.
*
* If the `tokenId` is out of bounds:
* - `addr` = `address(0)`
* - `startTimestamp` = `0`
* - `burned` = `false`
*
* If the `tokenId` is burned:
* - `addr` = `<Address of owner before token was burned>`
* - `startTimestamp` = `<Timestamp when token was burned>`
* - `burned = `true`
*
* Otherwise:
* - `addr` = `<Address of owner>`
* - `startTimestamp` = `<Timestamp of start of ownership>`
* - `burned = `false`
*/
function explicitOwnershipOf(uint256 tokenId) public view override returns (TokenOwnership memory) {
TokenOwnership memory ownership;
if (tokenId < _startTokenId() || tokenId >= _nextTokenId()) {
return ownership;
}
ownership = _ownershipAt(tokenId);
if (ownership.burned) {
return ownership;
}
return _ownershipOf(tokenId);
}
/**
* @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order.
* See {ERC721AQueryable-explicitOwnershipOf}
*/
function explicitOwnershipsOf(uint256[] memory tokenIds) external view override returns (TokenOwnership[] memory) {
unchecked {
uint256 tokenIdsLength = tokenIds.length;
TokenOwnership[] memory ownerships = new TokenOwnership[](tokenIdsLength);
for (uint256 i; i != tokenIdsLength; ++i) {
ownerships[i] = explicitOwnershipOf(tokenIds[i]);
}
return ownerships;
}
}
/**
* @dev Returns an array of token IDs owned by `owner`,
* in the range [`start`, `stop`)
* (i.e. `start <= tokenId < stop`).
*
* This function allows for tokens to be queried if the collection
* grows too big for a single call of {ERC721AQueryable-tokensOfOwner}.
*
* Requirements:
*
* - `start` < `stop`
*/
function tokensOfOwnerIn(
address owner,
uint256 start,
uint256 stop
) external view override returns (uint256[] memory) {
unchecked {
if (start >= stop) revert InvalidQueryRange();
uint256 tokenIdsIdx;
uint256 stopLimit = _nextTokenId();
// Set `start = max(start, _startTokenId())`.
if (start < _startTokenId()) {
start = _startTokenId();
}
// Set `stop = min(stop, stopLimit)`.
if (stop > stopLimit) {
stop = stopLimit;
}
uint256 tokenIdsMaxLength = balanceOf(owner);
// Set `tokenIdsMaxLength = min(balanceOf(owner), stop - start)`,
// to cater for cases where `balanceOf(owner)` is too big.
if (start < stop) {
uint256 rangeLength = stop - start;
if (rangeLength < tokenIdsMaxLength) {
tokenIdsMaxLength = rangeLength;
}
} else {
tokenIdsMaxLength = 0;
}
uint256[] memory tokenIds = new uint256[](tokenIdsMaxLength);
if (tokenIdsMaxLength == 0) {
return tokenIds;
}
// We need to call `explicitOwnershipOf(start)`,
// because the slot at `start` may not be initialized.
TokenOwnership memory ownership = explicitOwnershipOf(start);
address currOwnershipAddr;
// If the starting slot exists (i.e. not burned), initialize `currOwnershipAddr`.
// `ownership.address` will not be zero, as `start` is clamped to the valid token ID range.
if (!ownership.burned) {
currOwnershipAddr = ownership.addr;
}
for (uint256 i = start; i != stop && tokenIdsIdx != tokenIdsMaxLength; ++i) {
ownership = _ownershipAt(i);
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
tokenIds[tokenIdsIdx++] = i;
}
}
// Downsize the array to fit.
assembly {
mstore(tokenIds, tokenIdsIdx)
}
return tokenIds;
}
}
/**
* @dev Returns an array of token IDs owned by `owner`.
*
* This function scans the ownership mapping and is O(totalSupply) in complexity.
* It is meant to be called off-chain.
*
* See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into
* multiple smaller scans if the collection is large enough to cause
* an out-of-gas error (10K pfp collections should be fine).
*/
function tokensOfOwner(address owner) external view override returns (uint256[] memory) {
unchecked {
uint256 tokenIdsIdx;
address currOwnershipAddr;
uint256 tokenIdsLength = balanceOf(owner);
uint256[] memory tokenIds = new uint256[](tokenIdsLength);
TokenOwnership memory ownership;
for (uint256 i = _startTokenId(); tokenIdsIdx != tokenIdsLength; ++i) {
ownership = _ownershipAt(i);
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
tokenIds[tokenIdsIdx++] = i;
}
}
return tokenIds;
}
}
} | abstract contract ERC721AQueryable is ERC721A, IERC721AQueryable {
/**
* @dev Returns the `TokenOwnership` struct at `tokenId` without reverting.
*
* If the `tokenId` is out of bounds:
* - `addr` = `address(0)`
* - `startTimestamp` = `0`
* - `burned` = `false`
*
* If the `tokenId` is burned:
* - `addr` = `<Address of owner before token was burned>`
* - `startTimestamp` = `<Timestamp when token was burned>`
* - `burned = `true`
*
* Otherwise:
* - `addr` = `<Address of owner>`
* - `startTimestamp` = `<Timestamp of start of ownership>`
* - `burned = `false`
*/
function explicitOwnershipOf(uint256 tokenId) public view override returns (TokenOwnership memory) {
TokenOwnership memory ownership;
if (tokenId < _startTokenId() || tokenId >= _nextTokenId()) {
return ownership;
}
ownership = _ownershipAt(tokenId);
if (ownership.burned) {
return ownership;
}
return _ownershipOf(tokenId);
}
/**
* @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order.
* See {ERC721AQueryable-explicitOwnershipOf}
*/
function explicitOwnershipsOf(uint256[] memory tokenIds) external view override returns (TokenOwnership[] memory) {
unchecked {
uint256 tokenIdsLength = tokenIds.length;
TokenOwnership[] memory ownerships = new TokenOwnership[](tokenIdsLength);
for (uint256 i; i != tokenIdsLength; ++i) {
ownerships[i] = explicitOwnershipOf(tokenIds[i]);
}
return ownerships;
}
}
/**
* @dev Returns an array of token IDs owned by `owner`,
* in the range [`start`, `stop`)
* (i.e. `start <= tokenId < stop`).
*
* This function allows for tokens to be queried if the collection
* grows too big for a single call of {ERC721AQueryable-tokensOfOwner}.
*
* Requirements:
*
* - `start` < `stop`
*/
function tokensOfOwnerIn(
address owner,
uint256 start,
uint256 stop
) external view override returns (uint256[] memory) {
unchecked {
if (start >= stop) revert InvalidQueryRange();
uint256 tokenIdsIdx;
uint256 stopLimit = _nextTokenId();
// Set `start = max(start, _startTokenId())`.
if (start < _startTokenId()) {
start = _startTokenId();
}
// Set `stop = min(stop, stopLimit)`.
if (stop > stopLimit) {
stop = stopLimit;
}
uint256 tokenIdsMaxLength = balanceOf(owner);
// Set `tokenIdsMaxLength = min(balanceOf(owner), stop - start)`,
// to cater for cases where `balanceOf(owner)` is too big.
if (start < stop) {
uint256 rangeLength = stop - start;
if (rangeLength < tokenIdsMaxLength) {
tokenIdsMaxLength = rangeLength;
}
} else {
tokenIdsMaxLength = 0;
}
uint256[] memory tokenIds = new uint256[](tokenIdsMaxLength);
if (tokenIdsMaxLength == 0) {
return tokenIds;
}
// We need to call `explicitOwnershipOf(start)`,
// because the slot at `start` may not be initialized.
TokenOwnership memory ownership = explicitOwnershipOf(start);
address currOwnershipAddr;
// If the starting slot exists (i.e. not burned), initialize `currOwnershipAddr`.
// `ownership.address` will not be zero, as `start` is clamped to the valid token ID range.
if (!ownership.burned) {
currOwnershipAddr = ownership.addr;
}
for (uint256 i = start; i != stop && tokenIdsIdx != tokenIdsMaxLength; ++i) {
ownership = _ownershipAt(i);
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
tokenIds[tokenIdsIdx++] = i;
}
}
// Downsize the array to fit.
assembly {
mstore(tokenIds, tokenIdsIdx)
}
return tokenIds;
}
}
/**
* @dev Returns an array of token IDs owned by `owner`.
*
* This function scans the ownership mapping and is O(totalSupply) in complexity.
* It is meant to be called off-chain.
*
* See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into
* multiple smaller scans if the collection is large enough to cause
* an out-of-gas error (10K pfp collections should be fine).
*/
function tokensOfOwner(address owner) external view override returns (uint256[] memory) {
unchecked {
uint256 tokenIdsIdx;
address currOwnershipAddr;
uint256 tokenIdsLength = balanceOf(owner);
uint256[] memory tokenIds = new uint256[](tokenIdsLength);
TokenOwnership memory ownership;
for (uint256 i = _startTokenId(); tokenIdsIdx != tokenIdsLength; ++i) {
ownership = _ownershipAt(i);
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
tokenIds[tokenIdsIdx++] = i;
}
}
return tokenIds;
}
}
} | 13,961 |
195 | // The maximum value of a uint256 contains 78 digits (1 byte per digit), but we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned. We will need 1 word for the trailing zeros padding, 1 word for the length, and 3 words for a maximum of 78 digits. Total: 50x20 = 0xa0. | let m := add(mload(0x40), 0xa0)
| let m := add(mload(0x40), 0xa0)
| 44,313 |
152 | // Creates a new pool.// The created pool will need to have its reward weight initialized before it begins generating rewards.//_token The token the pool will accept for staking.// return the identifier for the newly created pool. | function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.FixedDecimal(0),
lastUpdatedBlock: block.number
}));
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
| function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.FixedDecimal(0),
lastUpdatedBlock: block.number
}));
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
| 32,205 |
113 | // Returns natural logarithm value of given x/x x/ return ln(x) | function ln(uint x)
public
pure
returns (int)
| function ln(uint x)
public
pure
returns (int)
| 45,898 |
658 | // removes desitnation as eligible for transfer _address address being removed / | function removeEligibleLockedDestination(address _address) public {
if(hasRole(ROLE_ADMIN, _msgSender())){
require(_address != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address");
delete(m_lockedDestinations[_address]);
}
}
| function removeEligibleLockedDestination(address _address) public {
if(hasRole(ROLE_ADMIN, _msgSender())){
require(_address != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address");
delete(m_lockedDestinations[_address]);
}
}
| 32,810 |
67 | // if attacked by no-unit do nothing | else {
continue;
}
| else {
continue;
}
| 1,633 |
68 | // Checks if first Exp is less than second Exp./ | function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa; //TODO: Add some simple tests and this in another PR yo.
}
| function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa; //TODO: Add some simple tests and this in another PR yo.
}
| 37,584 |
114 | // Minimal ERC4626 tokenized Vault implementation./Solmate (https:github.com/Rari-Capital/solmate/blob/main/src/mixins/ERC4626.sol)/Do not use in production! ERC-4626 is still in the last call stage and is subject to change. | abstract contract ERC4626 is ERC20 {
using SafeTransferLib for ERC20;
using FixedPointMathLib for uint256;
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed caller,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/*///////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
ERC20 public immutable asset;
constructor(
ERC20 _asset,
string memory _name,
string memory _symbol
) ERC20(_name, _symbol, _asset.decimals()) {
asset = _asset;
}
/*///////////////////////////////////////////////////////////////
DEPOSIT/WITHDRAWAL LOGIC
//////////////////////////////////////////////////////////////*/
function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) {
// Check for rounding error since we round down in previewDeposit.
require((shares = previewDeposit(assets)) != 0, "ZERO_SHARES");
// Need to transfer before minting or ERC777s could reenter.
asset.safeTransferFrom(msg.sender, address(this), assets);
_mint(receiver, shares);
emit Deposit(msg.sender, receiver, assets, shares);
afterDeposit(assets, shares);
}
function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) {
assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.
// Need to transfer before minting or ERC777s could reenter.
asset.safeTransferFrom(msg.sender, address(this), assets);
_mint(receiver, shares);
emit Deposit(msg.sender, receiver, assets, shares);
afterDeposit(assets, shares);
}
function withdraw(
uint256 assets,
address receiver,
address owner
) public virtual returns (uint256 shares) {
shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.
if (msg.sender != owner) {
uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
}
beforeWithdraw(assets, shares);
_burn(owner, shares);
emit Withdraw(msg.sender, receiver, owner, assets, shares);
asset.safeTransfer(receiver, assets);
}
function redeem(
uint256 shares,
address receiver,
address owner
) public virtual returns (uint256 assets) {
if (msg.sender != owner) {
uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
}
// Check for rounding error since we round down in previewRedeem.
require((assets = previewRedeem(shares)) != 0, "ZERO_ASSETS");
beforeWithdraw(assets, shares);
_burn(owner, shares);
emit Withdraw(msg.sender, receiver, owner, assets, shares);
asset.safeTransfer(receiver, assets);
}
/*///////////////////////////////////////////////////////////////
ACCOUNTING LOGIC
//////////////////////////////////////////////////////////////*/
function totalAssets() public view virtual returns (uint256);
function convertToShares(uint256 assets) public view returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());
}
function convertToAssets(uint256 shares) public view returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);
}
function previewDeposit(uint256 assets) public view virtual returns (uint256) {
return convertToShares(assets);
}
function previewMint(uint256 shares) public view virtual returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);
}
function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());
}
function previewRedeem(uint256 shares) public view virtual returns (uint256) {
return convertToAssets(shares);
}
/*///////////////////////////////////////////////////////////////
DEPOSIT/WITHDRAWAL LIMIT LOGIC
//////////////////////////////////////////////////////////////*/
function maxDeposit(address) public view virtual returns (uint256) {
return type(uint256).max;
}
function maxMint(address) public view virtual returns (uint256) {
return type(uint256).max;
}
function maxWithdraw(address owner) public view virtual returns (uint256) {
return convertToAssets(balanceOf[owner]);
}
function maxRedeem(address owner) public view virtual returns (uint256) {
return balanceOf[owner];
}
/*///////////////////////////////////////////////////////////////
INTERNAL HOOKS LOGIC
//////////////////////////////////////////////////////////////*/
function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}
function afterDeposit(uint256 assets, uint256 shares) internal virtual {}
}
| abstract contract ERC4626 is ERC20 {
using SafeTransferLib for ERC20;
using FixedPointMathLib for uint256;
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed caller,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/*///////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
ERC20 public immutable asset;
constructor(
ERC20 _asset,
string memory _name,
string memory _symbol
) ERC20(_name, _symbol, _asset.decimals()) {
asset = _asset;
}
/*///////////////////////////////////////////////////////////////
DEPOSIT/WITHDRAWAL LOGIC
//////////////////////////////////////////////////////////////*/
function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) {
// Check for rounding error since we round down in previewDeposit.
require((shares = previewDeposit(assets)) != 0, "ZERO_SHARES");
// Need to transfer before minting or ERC777s could reenter.
asset.safeTransferFrom(msg.sender, address(this), assets);
_mint(receiver, shares);
emit Deposit(msg.sender, receiver, assets, shares);
afterDeposit(assets, shares);
}
function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) {
assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.
// Need to transfer before minting or ERC777s could reenter.
asset.safeTransferFrom(msg.sender, address(this), assets);
_mint(receiver, shares);
emit Deposit(msg.sender, receiver, assets, shares);
afterDeposit(assets, shares);
}
function withdraw(
uint256 assets,
address receiver,
address owner
) public virtual returns (uint256 shares) {
shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.
if (msg.sender != owner) {
uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
}
beforeWithdraw(assets, shares);
_burn(owner, shares);
emit Withdraw(msg.sender, receiver, owner, assets, shares);
asset.safeTransfer(receiver, assets);
}
function redeem(
uint256 shares,
address receiver,
address owner
) public virtual returns (uint256 assets) {
if (msg.sender != owner) {
uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
}
// Check for rounding error since we round down in previewRedeem.
require((assets = previewRedeem(shares)) != 0, "ZERO_ASSETS");
beforeWithdraw(assets, shares);
_burn(owner, shares);
emit Withdraw(msg.sender, receiver, owner, assets, shares);
asset.safeTransfer(receiver, assets);
}
/*///////////////////////////////////////////////////////////////
ACCOUNTING LOGIC
//////////////////////////////////////////////////////////////*/
function totalAssets() public view virtual returns (uint256);
function convertToShares(uint256 assets) public view returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());
}
function convertToAssets(uint256 shares) public view returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);
}
function previewDeposit(uint256 assets) public view virtual returns (uint256) {
return convertToShares(assets);
}
function previewMint(uint256 shares) public view virtual returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);
}
function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());
}
function previewRedeem(uint256 shares) public view virtual returns (uint256) {
return convertToAssets(shares);
}
/*///////////////////////////////////////////////////////////////
DEPOSIT/WITHDRAWAL LIMIT LOGIC
//////////////////////////////////////////////////////////////*/
function maxDeposit(address) public view virtual returns (uint256) {
return type(uint256).max;
}
function maxMint(address) public view virtual returns (uint256) {
return type(uint256).max;
}
function maxWithdraw(address owner) public view virtual returns (uint256) {
return convertToAssets(balanceOf[owner]);
}
function maxRedeem(address owner) public view virtual returns (uint256) {
return balanceOf[owner];
}
/*///////////////////////////////////////////////////////////////
INTERNAL HOOKS LOGIC
//////////////////////////////////////////////////////////////*/
function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}
function afterDeposit(uint256 assets, uint256 shares) internal virtual {}
}
| 71,740 |
862 | // Add Emergency pause/_pause to set Emergency Pause ON/OFF/_by to set who Start/Stop EP | function addEmergencyPause(bool _pause, bytes4 _by) public {
require(_by == "AB" || _by == "AUT","Invalid call.");
require(msg.sender == getLatestAddress("P1") || msg.sender == getLatestAddress("GV"),"Callable by P1 and GV only.");
emergencyPaused.push(EmergencyPause(_pause, now, _by));
if (_pause == false) {
Claims c1 = Claims(allContractVersions["CL"]);
c1.submitClaimAfterEPOff(); // Process claims submitted while EP was on
c1.startAllPendingClaimsVoting(); // Resume voting on all pending claims
}
}
| function addEmergencyPause(bool _pause, bytes4 _by) public {
require(_by == "AB" || _by == "AUT","Invalid call.");
require(msg.sender == getLatestAddress("P1") || msg.sender == getLatestAddress("GV"),"Callable by P1 and GV only.");
emergencyPaused.push(EmergencyPause(_pause, now, _by));
if (_pause == false) {
Claims c1 = Claims(allContractVersions["CL"]);
c1.submitClaimAfterEPOff(); // Process claims submitted while EP was on
c1.startAllPendingClaimsVoting(); // Resume voting on all pending claims
}
}
| 29,165 |
3 | // Save state of current variables needed for validation of properties | BalanceOfStruct[] memory old_balanceOf = new BalanceOfStruct[](addressesInUse.length);
address[] memory old_addressesInUse = new address[](addressesInUse.length);
for(uint x; x < addressesInUse.length; x++){
old_addressesInUse[x] = addressesInUse[x];
old_balanceOf[x] = BalanceOfStruct(addressesInUse[x], balanceOf[addressesInUse[x]]);
}
| BalanceOfStruct[] memory old_balanceOf = new BalanceOfStruct[](addressesInUse.length);
address[] memory old_addressesInUse = new address[](addressesInUse.length);
for(uint x; x < addressesInUse.length; x++){
old_addressesInUse[x] = addressesInUse[x];
old_balanceOf[x] = BalanceOfStruct(addressesInUse[x], balanceOf[addressesInUse[x]]);
}
| 264 |
92 | // Address where fees are sent to. / | address internal feeCollector;
| address internal feeCollector;
| 49,655 |
5 | // mapping (uint => Vault) private snToVault; | uint[128] internal nextSN;
mapping (uint => uint) public valToVotes; // slot: 134
uint[] public validators; // slot: 135
| uint[128] internal nextSN;
mapping (uint => uint) public valToVotes; // slot: 134
uint[] public validators; // slot: 135
| 36,866 |
37 | // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function Adapters will automatically handle the difference of precision | wad = mul(
amt,
10 ** (18 - GemJoinLike(gemJoin).dec())
);
| wad = mul(
amt,
10 ** (18 - GemJoinLike(gemJoin).dec())
);
| 53,580 |
7 | // validateTransactionStateProofDecodes and validates a TransactionStateProof, which containsan inclusion proof for a transaction and the state root prior toits execution. state storage struct representing the state of Tiramisu proofBytes encoded TransactionStateProof transactionBytes encoded transaction to verify inclusion proof ofreturn root state root prior to the transaction / | function validateTransactionStateProof(
State.State storage state,
Block.BlockHeader memory header,
bytes memory proofBytes,
bytes memory transactionBytes
| function validateTransactionStateProof(
State.State storage state,
Block.BlockHeader memory header,
bytes memory proofBytes,
bytes memory transactionBytes
| 31,203 |
127 | // remove Global Constraint _globalConstraint the address of the global constraint to be remove. _avatar the organization avatar.return bool which represents a success / | function removeGlobalConstraint (address _globalConstraint, address _avatar)
| function removeGlobalConstraint (address _globalConstraint, address _avatar)
| 11,067 |
84 | // An alias for `transferFrom` function./_from The address of the sender./_to The address of the recipient./_amount The value to transfer. | function move(address _from, address _to, uint256 _amount) public {
transferFrom(_from, _to, _amount);
}
| function move(address _from, address _to, uint256 _amount) public {
transferFrom(_from, _to, _amount);
}
| 33,843 |
1 | // caution, check safe-to-multiply here | uint256 _numerator = numerator * 10 ** (precision+1);
| uint256 _numerator = numerator * 10 ** (precision+1);
| 40,718 |
61 | // This will assign ownership, and also emit the Transfer event as per ERC721 draft | _transfer(address(0), _owner, newTokenId);
| _transfer(address(0), _owner, newTokenId);
| 6,611 |
0 | // up to 3 parameters can be indexed | event Log(address indexed sender, string message);
event AnotherLog();
| event Log(address indexed sender, string message);
event AnotherLog();
| 35,056 |
63 | // this modifier requires that msg.sender is the controller of this contract | modifier only_controller {
require( msg.sender == controller, "not controller" );
_;
}
| modifier only_controller {
require( msg.sender == controller, "not controller" );
_;
}
| 41,565 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.