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 |
|---|---|---|---|---|
125 | // Whether `a` is greater than or equal to `b`. a a FixedPoint.Signed. b an int256.return True if `a >= b`, or False. / | function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledInt(b).rawValue;
}
| function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledInt(b).rawValue;
}
| 29,931 |
7 | // Mapping that stores all Default and External position information for a given component. Position quantities are represented as virtual units; Default positions are on the top-level, while external positions are stored in a module array and accessed through its externalPositions mapping | mapping(address => IBasketToken.ComponentPosition) private componentPositions;
| mapping(address => IBasketToken.ComponentPosition) private componentPositions;
| 4,333 |
205 | // solhint-enable var-name-mixedcase // Initializes the domain separator and parameter caches. The meaning of `name` and `version` is specified in - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.- `version`: the current major version of the signing domain. NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smartcontract upgrade]. / | constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
| constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
| 1,934 |
106 | // increment address to keep track of no of users in smartcontract | contractAddresses_+=1;
contractTokenHolderAddresses_.push(_customerAddress);
| contractAddresses_+=1;
contractTokenHolderAddresses_.push(_customerAddress);
| 7,941 |
8 | // Kills the game contract and refunds the bids/ _gameID Id of the game/ _compute True if rewards need to be computed and False for simple refund | function forceKill(uint32 _gameID,bool _compute) public onlyOwner {
ChessGame game = games[_gameID];
game.activateRewardMechanism(_compute);
isActive = false;
}
| function forceKill(uint32 _gameID,bool _compute) public onlyOwner {
ChessGame game = games[_gameID];
game.activateRewardMechanism(_compute);
isActive = false;
}
| 9,768 |
27 | // Get Agreement debt dai amount/ | function _getAgreementDebtValue() internal view returns (uint) {
return IAgreement(targetAgreement).cdpDebtValue();
}
| function _getAgreementDebtValue() internal view returns (uint) {
return IAgreement(targetAgreement).cdpDebtValue();
}
| 9,056 |
41 | // Compute the payout earned by the citizen, and check whether the contract has enough funds to pay the due amount | uint payout = _computePayout(_citizen);
require(address(this).balance > payout, "Municipality has not enough funds!");
| uint payout = _computePayout(_citizen);
require(address(this).balance > payout, "Municipality has not enough funds!");
| 12,984 |
77 | // Base URI for computing {tokenURI}. / | function _setBaseURI(string memory baseURI_) internal {
_baseURI = baseURI_;
}
| function _setBaseURI(string memory baseURI_) internal {
_baseURI = baseURI_;
}
| 26,027 |
117 | // Constructor, takes maximum amount of wei accepted in the crowdsale. _cap Max amount of wei to be contributed / | constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
| constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
| 1,259 |
54 | // get the amount of network tokens already minted for the pool | uint256 networkTokensMinted = _systemStore.networkTokensMinted(poolAnchor);
| uint256 networkTokensMinted = _systemStore.networkTokensMinted(poolAnchor);
| 29,510 |
24 | // The contract authorized to deploy TWAP pairs | address public trustedDeployerContractAddress;
| address public trustedDeployerContractAddress;
| 25,029 |
126 | // $Z / 1 one token | if (getOneTokenUsd() > 1 * 10 ** 9) {
setReserveRatio(reserveRatio.sub(reserveStepSize));
} else {
| if (getOneTokenUsd() > 1 * 10 ** 9) {
setReserveRatio(reserveRatio.sub(reserveStepSize));
} else {
| 8,111 |
3 | // 如果 当前合约的总发行量 == 0 || 当前合约的余额 == 0 | if (totalShares == 0 || totalSushi == 0) {
| if (totalShares == 0 || totalSushi == 0) {
| 50,198 |
3 | // one share for governance tokens | mapping(address => uint256) public shares;
uint public totalShares;
| mapping(address => uint256) public shares;
uint public totalShares;
| 27,717 |
37 | // Otherwise, there could be a rebate, so record the price paid. Note: We record the actual sent amount, not current price. | mintPrices[msg.sender].push(msg.value);
numRebateMints++;
_processMint(msg.sender, 1);
| mintPrices[msg.sender].push(msg.value);
numRebateMints++;
_processMint(msg.sender, 1);
| 39,175 |
18 | // See {IERC721Metadata-tokenURI}. / | function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
_requireMinted(tokenId);
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
| function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
_requireMinted(tokenId);
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
| 293 |
105 | // successful end of CrowdSale | if (weiRaised.add(preSale.weiRaised()) >= softCap && now > endCrowdSaleTime && now <= endRefundableTime) {
refundPart(_to);
return;
}
| if (weiRaised.add(preSale.weiRaised()) >= softCap && now > endCrowdSaleTime && now <= endRefundableTime) {
refundPart(_to);
return;
}
| 40,778 |
29 | // Set `buyMultiplier` = 0 after all tokens sold./Buy tokens from contract by sending ether, with `data` = `0xa6f2ae3a`. | function buy() payable public {
require (buyMultiplier > 0); // if no more tokens, make Tx fail.
uint amount = msg.value * buyMultiplier / buyPrice; // calculates the amount. Multiplier allows token value < 1 ETH
_transfer(this, msg.sender, amount); // makes the transfers
}
| function buy() payable public {
require (buyMultiplier > 0); // if no more tokens, make Tx fail.
uint amount = msg.value * buyMultiplier / buyPrice; // calculates the amount. Multiplier allows token value < 1 ETH
_transfer(this, msg.sender, amount); // makes the transfers
}
| 49,118 |
8 | // lock Preslae | isRunning = false;
| isRunning = false;
| 36,191 |
400 | // do transfer skip during self transfers since toBalance is cached which leads to free minting, a critical issue | if (msg.sender != to) {
balanceOf[msg.sender] = fromBalance - amount;
| if (msg.sender != to) {
balanceOf[msg.sender] = fromBalance - amount;
| 43,084 |
161 | // after depositing/withdrawing, extra incentive tokens are transfered to the staking contractneed to pull them off and stash here. | for(uint i=0; i < tokenCount; i++){
TokenInfo storage t = tokenInfo[i];
address token = t.token;
if(token == address(0)) continue;
| for(uint i=0; i < tokenCount; i++){
TokenInfo storage t = tokenInfo[i];
address token = t.token;
if(token == address(0)) continue;
| 8,714 |
458 | // 3、新增头寸 | positions[poolIndex].push(Position.Info({
isEmpty: true,
tickLower: tickLower,
tickUpper: tickUpper
}));
| positions[poolIndex].push(Position.Info({
isEmpty: true,
tickLower: tickLower,
tickUpper: tickUpper
}));
| 50,274 |
1 | // in case some funds need to be returned or moved to another contract | function transfer(address token, uint256 amount, address to) external returns (bool);
| function transfer(address token, uint256 amount, address to) external returns (bool);
| 27,809 |
20 | // solium-disable security/no-block-members //'Powering-up a listing' is spending OpenBazaar tokens to advertise a listing in one of the OpenBazaar clients./ | contract PowerUps {
using SafeMath for uint256;
ITokenContract public token;
struct PowerUp {
string contentAddress; // IPFS/IPNS address, peerID, etc
uint256 tokensBurned; // total tokens burned towards this PowerUp
uint256 lastTopupTime; // last time tokens were burned for this PowerUp
bytes32 keyword; // search term, reserved keyword, etc
}
PowerUp[] powerUps; // stores PowerUps
mapping(bytes32 => uint256[]) keywordVsPowerUpIds;
event NewPowerUpAdded(
address indexed initiator,
uint256 id, // the index of this PowerUp in the powerUps[] array
uint256 tokensBurned
);
event Topup(
address indexed initiator,
uint256 id, // the index of the PowerUp in the powerUps[] array
uint256 tokensBurned
);
modifier powerUpExists(uint256 id) {
require(id <= powerUps.length.sub(1), "PowerUp does not exists");
_;
}
modifier nonZeroAddress(address addressToCheck) {
require(addressToCheck != address(0), "Zero address passed");
_;
}
constructor(address obTokenAddress) public nonZeroAddress(obTokenAddress) {
token = ITokenContract(obTokenAddress);
}
/**
* @dev Add new PowerUp
* @param contentAddress IPFS/IPNS address, peerID, etc
* @param amount Amount of tokens to burn
* @param keyword Bytes32 search term, reserved keyword, etc
* @return id Index of the PowerUp in the powerUps[] array
*/
function addPowerUp(
string calldata contentAddress,
uint256 amount,
bytes32 keyword
)
external
returns (uint256 id)
{
require(bytes(contentAddress).length > 0, "Content Address is empty");
id = _addPowerUp(contentAddress, amount, keyword);
return id;
}
/**
* @dev Add multiple PowerUps for different keywords but the same
* content address
* This is intended to be used for associating a given contentAddress with
* multiple search keywords by batching the PowerUps together. This is
* simply to allow the creation of multiple PowerUps with a single function
* call.
* @param contentAddress IPFS/IPNS address of the listing
* @param amounts Amount of tokens to be burnt for each PowerUp
* @param keywords Keywords in bytes32 form for each PowerUp
* Be sure to keep arrays small enough so as not to exceed the block gas
* limit.
*/
function addPowerUps(
string calldata contentAddress,
uint256[] calldata amounts,
bytes32[] calldata keywords
)
external
returns (uint256[] memory ids)
{
require(
bytes(contentAddress).length > 0,
"Content Address is empty"
);
require(
amounts.length == keywords.length,
"keywords and amounts length mismatch"
);
ids = new uint256[](amounts.length);
for (uint256 i = 0; i < amounts.length; i++) {
ids[i] = _addPowerUp(contentAddress, amounts[i], keywords[i]);
}
return ids;
}
/**
* @dev Topup a PowerUp's balance (that is, burn more tokens in association
* with am existing PowerUp)
* @param id The index of the PowerUp in the powerUps array
* @param amount Amount of tokens to burn
*/
function topUpPowerUp(
uint256 id,
uint256 amount
)
external
powerUpExists(id)
{
require(
amount > 0,
"Amount of tokens to burn should be greater than 0"
);
powerUps[id].tokensBurned = powerUps[id].tokensBurned.add(amount);
powerUps[id].lastTopupTime = block.timestamp;
token.burnFrom(msg.sender, amount);
emit Topup(msg.sender, id, amount);
}
/**
* @dev Returns info about a given PowerUp
* @param id The index of the PowerUp in the powerUps array
*/
function getPowerUpInfo(
uint256 id
)
external
view
returns (
string memory contentAddress,
uint256 tokensBurned,
uint256 lastTopupTime,
bytes32 keyword
)
{
if (powerUps.length > id) {
PowerUp storage powerUp = powerUps[id];
contentAddress = powerUp.contentAddress;
tokensBurned = powerUp.tokensBurned;
lastTopupTime = powerUp.lastTopupTime;
keyword = powerUp.keyword;
}
return (contentAddress, tokensBurned, lastTopupTime, keyword);
}
/**
* @dev returns how many powerups are available for the given keyword
* @param keyword Keyword for which the result needs to be fetched
*/
function noOfPowerUps(bytes32 keyword)
external
view
returns (uint256 count)
{
count = keywordVsPowerUpIds[keyword].length;
return count;
}
/**
* @dev returns the id (index in the powerUps[] array) of the PowerUp
* refered to by the `index`th element of a given `keyword` array.
* ie: getPowerUpIdAtIndex("shoes",23) will return the id of the 23rd
* PowerUp that burned tokens in association with the keyword "shoes".
* @param keyword Keyword string for which the PowerUp ids will be fetched
* @param index Index at which id of the PowerUp needs to be fetched
*/
function getPowerUpIdAtIndex(
bytes32 keyword,
uint256 index
)
external
view
returns (uint256 id)
{
require(
keywordVsPowerUpIds[keyword].length > index,
"Array index out of bounds"
);
id = keywordVsPowerUpIds[keyword][index];
return id;
}
/**
* @dev This method will return an array of ids of PowerUps associated with
* the given keyword
* @param keyword The keyword for which the array of PowerUps will be fetched
*/
function getPowerUpIds(bytes32 keyword)
external
view
returns (uint256[] memory ids)
{
ids = keywordVsPowerUpIds[keyword];
return ids;
}
//private helper
function _addPowerUp(
string memory contentAddress,
uint256 amount,
bytes32 keyword
)
private
returns (uint256 id)
{
require(
amount > 0,
"Amount of tokens to burn should be greater than 0"
);
powerUps.push(
PowerUp({
contentAddress:contentAddress,
tokensBurned:amount,
lastTopupTime:block.timestamp,
keyword: keyword
})
);
keywordVsPowerUpIds[keyword].push(powerUps.length.sub(1));
token.burnFrom(msg.sender, amount);
emit NewPowerUpAdded(msg.sender, powerUps.length.sub(1), amount);
id = powerUps.length.sub(1);
return id;
}
}
| contract PowerUps {
using SafeMath for uint256;
ITokenContract public token;
struct PowerUp {
string contentAddress; // IPFS/IPNS address, peerID, etc
uint256 tokensBurned; // total tokens burned towards this PowerUp
uint256 lastTopupTime; // last time tokens were burned for this PowerUp
bytes32 keyword; // search term, reserved keyword, etc
}
PowerUp[] powerUps; // stores PowerUps
mapping(bytes32 => uint256[]) keywordVsPowerUpIds;
event NewPowerUpAdded(
address indexed initiator,
uint256 id, // the index of this PowerUp in the powerUps[] array
uint256 tokensBurned
);
event Topup(
address indexed initiator,
uint256 id, // the index of the PowerUp in the powerUps[] array
uint256 tokensBurned
);
modifier powerUpExists(uint256 id) {
require(id <= powerUps.length.sub(1), "PowerUp does not exists");
_;
}
modifier nonZeroAddress(address addressToCheck) {
require(addressToCheck != address(0), "Zero address passed");
_;
}
constructor(address obTokenAddress) public nonZeroAddress(obTokenAddress) {
token = ITokenContract(obTokenAddress);
}
/**
* @dev Add new PowerUp
* @param contentAddress IPFS/IPNS address, peerID, etc
* @param amount Amount of tokens to burn
* @param keyword Bytes32 search term, reserved keyword, etc
* @return id Index of the PowerUp in the powerUps[] array
*/
function addPowerUp(
string calldata contentAddress,
uint256 amount,
bytes32 keyword
)
external
returns (uint256 id)
{
require(bytes(contentAddress).length > 0, "Content Address is empty");
id = _addPowerUp(contentAddress, amount, keyword);
return id;
}
/**
* @dev Add multiple PowerUps for different keywords but the same
* content address
* This is intended to be used for associating a given contentAddress with
* multiple search keywords by batching the PowerUps together. This is
* simply to allow the creation of multiple PowerUps with a single function
* call.
* @param contentAddress IPFS/IPNS address of the listing
* @param amounts Amount of tokens to be burnt for each PowerUp
* @param keywords Keywords in bytes32 form for each PowerUp
* Be sure to keep arrays small enough so as not to exceed the block gas
* limit.
*/
function addPowerUps(
string calldata contentAddress,
uint256[] calldata amounts,
bytes32[] calldata keywords
)
external
returns (uint256[] memory ids)
{
require(
bytes(contentAddress).length > 0,
"Content Address is empty"
);
require(
amounts.length == keywords.length,
"keywords and amounts length mismatch"
);
ids = new uint256[](amounts.length);
for (uint256 i = 0; i < amounts.length; i++) {
ids[i] = _addPowerUp(contentAddress, amounts[i], keywords[i]);
}
return ids;
}
/**
* @dev Topup a PowerUp's balance (that is, burn more tokens in association
* with am existing PowerUp)
* @param id The index of the PowerUp in the powerUps array
* @param amount Amount of tokens to burn
*/
function topUpPowerUp(
uint256 id,
uint256 amount
)
external
powerUpExists(id)
{
require(
amount > 0,
"Amount of tokens to burn should be greater than 0"
);
powerUps[id].tokensBurned = powerUps[id].tokensBurned.add(amount);
powerUps[id].lastTopupTime = block.timestamp;
token.burnFrom(msg.sender, amount);
emit Topup(msg.sender, id, amount);
}
/**
* @dev Returns info about a given PowerUp
* @param id The index of the PowerUp in the powerUps array
*/
function getPowerUpInfo(
uint256 id
)
external
view
returns (
string memory contentAddress,
uint256 tokensBurned,
uint256 lastTopupTime,
bytes32 keyword
)
{
if (powerUps.length > id) {
PowerUp storage powerUp = powerUps[id];
contentAddress = powerUp.contentAddress;
tokensBurned = powerUp.tokensBurned;
lastTopupTime = powerUp.lastTopupTime;
keyword = powerUp.keyword;
}
return (contentAddress, tokensBurned, lastTopupTime, keyword);
}
/**
* @dev returns how many powerups are available for the given keyword
* @param keyword Keyword for which the result needs to be fetched
*/
function noOfPowerUps(bytes32 keyword)
external
view
returns (uint256 count)
{
count = keywordVsPowerUpIds[keyword].length;
return count;
}
/**
* @dev returns the id (index in the powerUps[] array) of the PowerUp
* refered to by the `index`th element of a given `keyword` array.
* ie: getPowerUpIdAtIndex("shoes",23) will return the id of the 23rd
* PowerUp that burned tokens in association with the keyword "shoes".
* @param keyword Keyword string for which the PowerUp ids will be fetched
* @param index Index at which id of the PowerUp needs to be fetched
*/
function getPowerUpIdAtIndex(
bytes32 keyword,
uint256 index
)
external
view
returns (uint256 id)
{
require(
keywordVsPowerUpIds[keyword].length > index,
"Array index out of bounds"
);
id = keywordVsPowerUpIds[keyword][index];
return id;
}
/**
* @dev This method will return an array of ids of PowerUps associated with
* the given keyword
* @param keyword The keyword for which the array of PowerUps will be fetched
*/
function getPowerUpIds(bytes32 keyword)
external
view
returns (uint256[] memory ids)
{
ids = keywordVsPowerUpIds[keyword];
return ids;
}
//private helper
function _addPowerUp(
string memory contentAddress,
uint256 amount,
bytes32 keyword
)
private
returns (uint256 id)
{
require(
amount > 0,
"Amount of tokens to burn should be greater than 0"
);
powerUps.push(
PowerUp({
contentAddress:contentAddress,
tokensBurned:amount,
lastTopupTime:block.timestamp,
keyword: keyword
})
);
keywordVsPowerUpIds[keyword].push(powerUps.length.sub(1));
token.burnFrom(msg.sender, amount);
emit NewPowerUpAdded(msg.sender, powerUps.length.sub(1), amount);
id = powerUps.length.sub(1);
return id;
}
}
| 19,960 |
71 | // Private Methods - shared logic | function _deposit(uint256 _poolId, Position storage _position, uint256 _amount) private {
Pool storage pool = pools[_poolId];
_position.stakedAmount += _amount;
pool.stakedAmount += _amount.toUint96();
_position.rewardsDebt += (_amount * pool.accumulatedRewardsPerShare).toInt256();
}
| function _deposit(uint256 _poolId, Position storage _position, uint256 _amount) private {
Pool storage pool = pools[_poolId];
_position.stakedAmount += _amount;
pool.stakedAmount += _amount.toUint96();
_position.rewardsDebt += (_amount * pool.accumulatedRewardsPerShare).toInt256();
}
| 22,511 |
1 | // ========== STATE VARIABLES ========== / Pools and vaults | IyUSDC_V2_Partial private yUSDC_V2;
IAAVELendingPool_Partial private aaveUSDC_Pool;
IAAVE_aUSDC_Partial private aaveUSDC_Token;
IcUSDC_Partial private cUSDC;
| IyUSDC_V2_Partial private yUSDC_V2;
IAAVELendingPool_Partial private aaveUSDC_Pool;
IAAVE_aUSDC_Partial private aaveUSDC_Token;
IcUSDC_Partial private cUSDC;
| 28,189 |
3 | // The contract should be able to receive Eth. / | receive() external payable virtual {}
/**
* @dev Customized modifiers and methods from the original source
*/
modifier onlyBeneficiary() {
require(_msgSender() == _beneficiary, "Only Beneficiary Address can access this function");
_;
}
| receive() external payable virtual {}
/**
* @dev Customized modifiers and methods from the original source
*/
modifier onlyBeneficiary() {
require(_msgSender() == _beneficiary, "Only Beneficiary Address can access this function");
_;
}
| 33,433 |
1 | // Only the owner of a key can change it. Or anyone if the address is 0. | modifier keyExists(bytes32 key, address owner)
| modifier keyExists(bytes32 key, address owner)
| 26,637 |
37 | // Gets totalSupply/ return Total supply | function totalSupply()
public
constant
| function totalSupply()
public
constant
| 41,087 |
78 | // ====== POLICY FUNCTIONS ====== // / | function addRecipient(address _recipient, uint256 _rewardRate)
external
onlyPolicy
| function addRecipient(address _recipient, uint256 _rewardRate)
external
onlyPolicy
| 22,198 |
51 | // Get tokens for name signal amount to burn | uint256 vSignal = nSignalToVSignal(_graphAccount, _subgraphNumber, _nSignal);
uint256 tokens = curation().burn(namePool.subgraphDeploymentID, vSignal, _tokensOutMin);
| uint256 vSignal = nSignalToVSignal(_graphAccount, _subgraphNumber, _nSignal);
uint256 tokens = curation().burn(namePool.subgraphDeploymentID, vSignal, _tokensOutMin);
| 22,388 |
6 | // unchecked { | uint256 option = optionNum % 4;
int256 hue = int256(uhue);
if (option == 0) {
return
clampHue(
(((100 - int256(uint256(pct))) * hue) +
(int256(uint256(pct)) *
(direction == 0 ? hue - 10 : hue + 10)))
);
| uint256 option = optionNum % 4;
int256 hue = int256(uhue);
if (option == 0) {
return
clampHue(
(((100 - int256(uint256(pct))) * hue) +
(int256(uint256(pct)) *
(direction == 0 ? hue - 10 : hue + 10)))
);
| 17,751 |
98 | // Approves or revokes a `masterContract` access to `user` funds./user The address of the user that approves or revokes access./masterContract The address who gains or loses access./approved If True approves access. If False revokes access./v Part of the signature. (See EIP-191)/r Part of the signature. (See EIP-191)/s Part of the signature. (See EIP-191) F4 - Check behaviour for all function arguments when wrong or extreme F4: Don't allow masterContract 0 to be approved. Unknown contracts will have a masterContract of 0. F4: User can't be 0 for signed approvals because the recoveredAddress will be 0 if ecrecover fails | function setMasterContractApproval(
address user,
address masterContract,
bool approved,
uint8 v,
bytes32 r,
bytes32 s
| function setMasterContractApproval(
address user,
address masterContract,
bool approved,
uint8 v,
bytes32 r,
bytes32 s
| 3,502 |
41 | // This internal function is equivalent to {transfer}, and can be used toe.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - 'sender' cannot be the zero address.- 'recipient' cannot be the zero address.- 'sender' must have a balance of at least 'amount'. / | function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
| function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
| 12,809 |
20 | // The current token fee. / | uint internal pToken;
| uint internal pToken;
| 48,095 |
68 | // Sends `amount_` of `_drawableFunds` to `destination_`. | function _drawdownFunds(uint256 amount_, address destination_) internal {
_drawableFunds -= amount_;
require(ERC20Helper.transfer(_fundsAsset, destination_, amount_), "MLI:DF:TRANSFER_FAILED");
require(_isCollateralMaintained(), "MLI:DF:INSUFFICIENT_COLLATERAL");
}
| function _drawdownFunds(uint256 amount_, address destination_) internal {
_drawableFunds -= amount_;
require(ERC20Helper.transfer(_fundsAsset, destination_, amount_), "MLI:DF:TRANSFER_FAILED");
require(_isCollateralMaintained(), "MLI:DF:INSUFFICIENT_COLLATERAL");
}
| 1,884 |
35 | // Increase the player bid map... | games[currentGameId].PlayerBidMap[msg.sender] = games[currentGameId].PlayerBidMap[msg.sender].add(gameAmt);
| games[currentGameId].PlayerBidMap[msg.sender] = games[currentGameId].PlayerBidMap[msg.sender].add(gameAmt);
| 30,577 |
29 | // ======= AUXILLIARY ======= //allow anyone to send lost tokens to the DAO return bool / | function recoverLostToken( address _token ) external returns ( bool ) {
TransferHelper.safeTransfer(_token, DAO, IERC20( _token ).balanceOf( address(this)));
return true;
}
| function recoverLostToken( address _token ) external returns ( bool ) {
TransferHelper.safeTransfer(_token, DAO, IERC20( _token ).balanceOf( address(this)));
return true;
}
| 37,517 |
17 | // Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint256 the amout of tokens to be transfered / | function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
| function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
| 2,636 |
25 | // Transfers tokens from an approved account | function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if ((balance[_from] >= _value) && (allowed[_from][msg.sender] >= _value) && (balance[_to] + _value > balance[_to])) {
balance[_to] += _value;
balance[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
| function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if ((balance[_from] >= _value) && (allowed[_from][msg.sender] >= _value) && (balance[_to] + _value > balance[_to])) {
balance[_to] += _value;
balance[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
| 20,195 |
8 | // Smart Lock functions CreateSmartLock : create smart lock DeleteSmartLock : delete smart lock/ |
function ExistSmartLock(bytes32 _SLID)
internal
view
returns (bool exist)
|
function ExistSmartLock(bytes32 _SLID)
internal
view
returns (bool exist)
| 42,026 |
14 | // Amount of synth tokens to mint | FixedPoint.Unsigned numTokens;
| FixedPoint.Unsigned numTokens;
| 7,830 |
411 | // Sends a cross-chain transfer via the liquidity pool-based bridge and sends a message specifying a wanted swap action on the _receiver the app contract that implements the MessageReceiver abstract contract NOTE not to be confused with the receiver field in SwapInfo which is an EOA address of a user _amountIn the input amount that the user wants to swap and/or bridge _dstChainId destination chain ID _srcSwap a struct containing swap related requirements _dstSwap a struct containing swap related requirements _maxBridgeSlippage the max acceptable slippage at bridge, given as percentage in point (pip). Eg. 5000 means 0.5%. Must be greater than | function _transferWithSwap(
address _receiver,
uint256 _amountIn,
uint64 _dstChainId,
SwapInfo memory _srcSwap,
SwapInfo memory _dstSwap,
uint32 _maxBridgeSlippage,
uint64 _nonce,
bool _nativeOut,
uint256 _fee
| function _transferWithSwap(
address _receiver,
uint256 _amountIn,
uint64 _dstChainId,
SwapInfo memory _srcSwap,
SwapInfo memory _dstSwap,
uint32 _maxBridgeSlippage,
uint64 _nonce,
bool _nativeOut,
uint256 _fee
| 5,311 |
12 | // Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`call, or as part of the Solidity `fallback` or `receive` functions.If overriden should call `super._beforeFallback()`. / | function _beforeFallback() internal virtual {
}
| function _beforeFallback() internal virtual {
}
| 10,529 |
188 | // Sauce | traitTypes[1].push(Trait("BBQ","Sauce","714c4b",0));
traitTypes[1].push(Trait("Gold","Sauce","FECD51",0));
traitTypes[1].push(Trait("Hot","Sauce","cd7542",0));
traitTypes[1].push(Trait("Pesto","Sauce","7aa579",0));
traitTypes[1].push(Trait("Tomato","Sauce","c94f49",0));
traitTypes[1].push(Trait("White","Sauce","acacac",0));
| traitTypes[1].push(Trait("BBQ","Sauce","714c4b",0));
traitTypes[1].push(Trait("Gold","Sauce","FECD51",0));
traitTypes[1].push(Trait("Hot","Sauce","cd7542",0));
traitTypes[1].push(Trait("Pesto","Sauce","7aa579",0));
traitTypes[1].push(Trait("Tomato","Sauce","c94f49",0));
traitTypes[1].push(Trait("White","Sauce","acacac",0));
| 27,654 |
2 | // Events // Emitted when a pool is created pool Pool instance implementation Implementation contract / | event PoolCreated(address indexed pool, address indexed implementation);
| event PoolCreated(address indexed pool, address indexed implementation);
| 1,807 |
120 | // calculate amount staked on contract | for (uint i = startIndex; i < _stakerCount; i++) {
if (iterationsLeft == 0) {
processedToStakerIndex = i;
contractStaked = _stakedOnContract;
return (_stakedOnContract, false, iterationsLeft);
}
| for (uint i = startIndex; i < _stakerCount; i++) {
if (iterationsLeft == 0) {
processedToStakerIndex = i;
contractStaked = _stakedOnContract;
return (_stakedOnContract, false, iterationsLeft);
}
| 1,044 |
24 | // mitigates the ERC20 spend/approval race condition | if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }
| if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }
| 3,303 |
16 | // Call Uniswap contract | exchange.ethToTokenSwapInput.value(eth_balance)(
tokens_bought,
deadline
);
| exchange.ethToTokenSwapInput.value(eth_balance)(
tokens_bought,
deadline
);
| 19,101 |
264 | // Throws if called by any account other than the owner. / | modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
| modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
| 49,741 |
84 | // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; really i know you think you do but you don't | int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
| int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
| 18,755 |
351 | // Add in the term | real_result += real_term;
| real_result += real_term;
| 18,568 |
4 | // Rebalance a Linear Pool from an asset manager to maintain optimal operating conditions. This function performs the same action as `rebalance`, except this also works in scenarios where the Poolis in the no-fee zone. This is done by first taking `extraMain` tokens from the caller, to cover for roundingerrors that are normally offset by acccumulated fees. Any extra tokens unused during the rebalance are sent tothe recipient as usual. / | function rebalanceWithExtraMain(address recipient, uint256 extraMain) external returns (uint256) {
// The Pool rounds rates in its favor, which means that the fees it has collected are actually not quite enough
// to cover for the cost of wrapping/unwrapping. However, this error is so small that it is typically a
// non-issue, and simply results in slightly reduced returns for the recipient.
// However, while the Pool is in the no-fee zone, the lack of fees to cover for this rate discrepancy is a
// problem. We therefore require a minute amount of extra main token so that we'll be able to account for this
// rounding error. Values in the order of a few wei are typically sufficient.
_mainToken.safeTransferFrom(msg.sender, address(this), extraMain);
return _rebalance(recipient);
}
| function rebalanceWithExtraMain(address recipient, uint256 extraMain) external returns (uint256) {
// The Pool rounds rates in its favor, which means that the fees it has collected are actually not quite enough
// to cover for the cost of wrapping/unwrapping. However, this error is so small that it is typically a
// non-issue, and simply results in slightly reduced returns for the recipient.
// However, while the Pool is in the no-fee zone, the lack of fees to cover for this rate discrepancy is a
// problem. We therefore require a minute amount of extra main token so that we'll be able to account for this
// rounding error. Values in the order of a few wei are typically sufficient.
_mainToken.safeTransferFrom(msg.sender, address(this), extraMain);
return _rebalance(recipient);
}
| 21,931 |
38 | // Sanity check that pool has enough balance to cover relay amount + proposer reward. Reward amount will be paid on settlement after the OptimisticOracle price request has passed the challenge period. | require(
l1Token.balanceOf(address(this)) - bonds >= depositData.amount && liquidReserves >= depositData.amount,
"Insufficient pool balance"
);
| require(
l1Token.balanceOf(address(this)) - bonds >= depositData.amount && liquidReserves >= depositData.amount,
"Insufficient pool balance"
);
| 37,912 |
5 | // SafeMathMath operations with safety checks that throw on error/ | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
| library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
| 46,606 |
15 | // Checks a deposit for validity and reverts otherwise. Should be overridden by all contracts that inherit it since it iscalled by `deposit` before `depositEnact`.This function is empty by default and the overrider does not need tocall it via `super`. / | function depositCheck(bytes32 fundingID, uint256 amount) internal view virtual
| function depositCheck(bytes32 fundingID, uint256 amount) internal view virtual
| 24,897 |
20 | // mint token using erc721 safe mint | function _mintTokens(address _to, uint256 _tokenId) internal {
_safeMint(_to, _tokenId);
}
| function _mintTokens(address _to, uint256 _tokenId) internal {
_safeMint(_to, _tokenId);
}
| 30,255 |
454 | // Moves power from one user to another. fromThe user from which delegated power is moved.toThe user that will receive the delegated power.amountThe amount of power to be moved.delegationTypeThe type of power (VOTING_POWER, PROPOSITION_POWER). / | function _moveDelegatesByType(
address from,
address to,
uint256 amount,
DelegationType delegationType
)
internal
| function _moveDelegatesByType(
address from,
address to,
uint256 amount,
DelegationType delegationType
)
internal
| 43,965 |
162 | // Returns the number of elements in the map. O(1). / | function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
| function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
| 1,545 |
10 | // RLPWriter RLPWriter is a library for encoding Solidity types to RLP bytes. Adapted from Bakaoh'smodifications to improve legibility. / | library RLPWriter {
/**
* @notice RLP encodes a byte string.
*
* @param _in The byte string to encode.
*
* @return The RLP encoded string in bytes.
*/
function writeBytes(bytes memory _in) internal pure returns (bytes memory) {
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* @notice RLP encodes a list of RLP encoded byte byte strings.
*
* @param _in The list of RLP encoded byte strings.
*
* @return The RLP encoded list of items in bytes.
*/
function writeList(bytes[] memory _in) internal pure returns (bytes memory) {
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* @notice RLP encodes a string.
*
* @param _in The string to encode.
*
* @return The RLP encoded string in bytes.
*/
function writeString(string memory _in) internal pure returns (bytes memory) {
return writeBytes(bytes(_in));
}
/**
* @notice RLP encodes an address.
*
* @param _in The address to encode.
*
* @return The RLP encoded address in bytes.
*/
function writeAddress(address _in) internal pure returns (bytes memory) {
return writeBytes(abi.encodePacked(_in));
}
/**
* @notice RLP encodes a uint.
*
* @param _in The uint256 to encode.
*
* @return The RLP encoded uint256 in bytes.
*/
function writeUint(uint256 _in) internal pure returns (bytes memory) {
return writeBytes(_toBinary(_in));
}
/**
* @notice RLP encodes a bool.
*
* @param _in The bool to encode.
*
* @return The RLP encoded bool in bytes.
*/
function writeBool(bool _in) internal pure returns (bytes memory) {
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/**
* @notice Encode the first byte and then the `len` in binary form if `length` is more than 55.
*
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
*
* @return RLP encoded bytes.
*/
function _writeLength(uint256 _len, uint256 _offset) private pure returns (bytes memory) {
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = bytes1(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55);
for (i = 1; i <= lenLen; i++) {
encoded[i] = bytes1(uint8((_len / (256 ** (lenLen - i))) % 256));
}
}
return encoded;
}
/**
* @notice Encode integer in big endian binary form with no leading zeroes.
*
* @param _x The integer to encode.
*
* @return RLP encoded bytes.
*/
function _toBinary(uint256 _x) private pure returns (bytes memory) {
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* @custom:attribution https://github.com/Arachnid/solidity-stringutils
* @notice Copies a piece of memory to another location.
*
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(uint256 _dest, uint256 _src, uint256 _len) private pure {
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask;
unchecked {
mask = 256 ** (32 - len) - 1;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* @custom:attribution https://github.com/sammayo/solidity-rlp-encoder
* @notice Flattens a list of byte strings into one byte string.
*
* @param _list List of byte strings to flatten.
*
* @return The flattened byte string.
*/
function _flatten(bytes[] memory _list) private pure returns (bytes memory) {
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly {
flattenedPtr := add(flattened, 0x20)
}
for (i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly {
listPtr := add(item, 0x20)
}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
| library RLPWriter {
/**
* @notice RLP encodes a byte string.
*
* @param _in The byte string to encode.
*
* @return The RLP encoded string in bytes.
*/
function writeBytes(bytes memory _in) internal pure returns (bytes memory) {
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* @notice RLP encodes a list of RLP encoded byte byte strings.
*
* @param _in The list of RLP encoded byte strings.
*
* @return The RLP encoded list of items in bytes.
*/
function writeList(bytes[] memory _in) internal pure returns (bytes memory) {
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* @notice RLP encodes a string.
*
* @param _in The string to encode.
*
* @return The RLP encoded string in bytes.
*/
function writeString(string memory _in) internal pure returns (bytes memory) {
return writeBytes(bytes(_in));
}
/**
* @notice RLP encodes an address.
*
* @param _in The address to encode.
*
* @return The RLP encoded address in bytes.
*/
function writeAddress(address _in) internal pure returns (bytes memory) {
return writeBytes(abi.encodePacked(_in));
}
/**
* @notice RLP encodes a uint.
*
* @param _in The uint256 to encode.
*
* @return The RLP encoded uint256 in bytes.
*/
function writeUint(uint256 _in) internal pure returns (bytes memory) {
return writeBytes(_toBinary(_in));
}
/**
* @notice RLP encodes a bool.
*
* @param _in The bool to encode.
*
* @return The RLP encoded bool in bytes.
*/
function writeBool(bool _in) internal pure returns (bytes memory) {
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/**
* @notice Encode the first byte and then the `len` in binary form if `length` is more than 55.
*
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
*
* @return RLP encoded bytes.
*/
function _writeLength(uint256 _len, uint256 _offset) private pure returns (bytes memory) {
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = bytes1(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55);
for (i = 1; i <= lenLen; i++) {
encoded[i] = bytes1(uint8((_len / (256 ** (lenLen - i))) % 256));
}
}
return encoded;
}
/**
* @notice Encode integer in big endian binary form with no leading zeroes.
*
* @param _x The integer to encode.
*
* @return RLP encoded bytes.
*/
function _toBinary(uint256 _x) private pure returns (bytes memory) {
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* @custom:attribution https://github.com/Arachnid/solidity-stringutils
* @notice Copies a piece of memory to another location.
*
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(uint256 _dest, uint256 _src, uint256 _len) private pure {
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask;
unchecked {
mask = 256 ** (32 - len) - 1;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* @custom:attribution https://github.com/sammayo/solidity-rlp-encoder
* @notice Flattens a list of byte strings into one byte string.
*
* @param _list List of byte strings to flatten.
*
* @return The flattened byte string.
*/
function _flatten(bytes[] memory _list) private pure returns (bytes memory) {
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly {
flattenedPtr := add(flattened, 0x20)
}
for (i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly {
listPtr := add(item, 0x20)
}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
| 19,633 |
126 | // Order must be targeted at this protocol version (this Exchange contract). / | if (order.exchange != address(this)) {
return false;
}
| if (order.exchange != address(this)) {
return false;
}
| 36,701 |
364 | // Returns the credit balance for a given user.Not that this includes both minted credit and pending credit./user The user whose credit balance should be returned/ return The balance of the users credit | function balanceOfCredit(address user, address controlledToken) external override onlyControlledToken(controlledToken) returns (uint256) {
_accrueCredit(user, controlledToken, IERC20Upgradeable(controlledToken).balanceOf(user), 0);
return _tokenCreditBalances[controlledToken][user].balance;
}
| function balanceOfCredit(address user, address controlledToken) external override onlyControlledToken(controlledToken) returns (uint256) {
_accrueCredit(user, controlledToken, IERC20Upgradeable(controlledToken).balanceOf(user), 0);
return _tokenCreditBalances[controlledToken][user].balance;
}
| 57,970 |
104 | // Sub String Extracts the beginning part of a string based on the desired length_base When being used for a data type this is the extended object otherwise this is the string that will be used for extracting the sub string from _length The length of the sub string to be extracted from the basereturn string The extracted sub string / | function substring(string _base, int _length)
internal
| function substring(string _base, int _length)
internal
| 3,407 |
160 | // Combined | bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4(
keccak256("lendAndStake(address,bytes,bytes)")
);
bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4(
keccak256("unstakeAndRedeem(address,bytes,bytes)")
);
| bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4(
keccak256("lendAndStake(address,bytes,bytes)")
);
bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4(
keccak256("unstakeAndRedeem(address,bytes,bytes)")
);
| 12,295 |
303 | // 1 token causes rounding error with withdrawUnderlying | if(cToken.balanceOf(address(this)) > 1){
_withdrawSome(deposits.sub(borrows));
}
| if(cToken.balanceOf(address(this)) > 1){
_withdrawSome(deposits.sub(borrows));
}
| 9,104 |
11 | // Reset the recipientCount as updated data | recipientCount = _fee.length;
| recipientCount = _fee.length;
| 28,897 |
63 | // Sets a new active provider for the Vault _provider: fuji address of the new provider | * Emits a {SetActiveProvider} event.
*/
function setActiveProvider(address _provider) external override isAuthorized {
activeProvider = _provider;
emit SetActiveProvider(_provider);
}
| * Emits a {SetActiveProvider} event.
*/
function setActiveProvider(address _provider) external override isAuthorized {
activeProvider = _provider;
emit SetActiveProvider(_provider);
}
| 19,610 |
224 | // increase distributed amount for user, no overflow, so don't need to use SafeMath here | userSwapData[data.user].dAmount += uint128(distributingAmount);
| userSwapData[data.user].dAmount += uint128(distributingAmount);
| 17,064 |
149 | // Gets the balance of a particular address_owner the address to query the the balance forreturn balance an amount of tokens owned by the address specified / | function balanceOf(address _owner) external view returns (uint256 balance);
| function balanceOf(address _owner) external view returns (uint256 balance);
| 54,273 |
8 | // Computes owner's fee of a sale./_saleFee - Sale price of NFT. | function setSaleFee(uint256 _saleFee) external onlyOwner {
if (saleFee < 10000 && saleFee >= 0)
saleFee = _saleFee;
}
| function setSaleFee(uint256 _saleFee) external onlyOwner {
if (saleFee < 10000 && saleFee >= 0)
saleFee = _saleFee;
}
| 34,395 |
8 | // MyToken V1 / | contract MyToken_V1 is MintableToken {
using SafeMath for uint256;
string public name = "MyToken";
string public symbol = "MTK";
uint256 public decimals = 18;
address public burnAddress;
OldERC20 public legacyToken;
function initialize(address _legacyToken, address _burnAddress) isInitializer("MyToken", "1.0.0") public {
MintableToken.initialize(this);
burnAddress = _burnAddress;
legacyToken = OldERC20(_legacyToken);
}
function migrateToken(uint _amount) public {
migrateTokenTo(_amount, msg.sender);
}
function migrateTokenTo(uint _amount, address _to) public {
legacyToken.transferFrom(msg.sender, burnAddress, _amount);
require(this.mint(_to, _amount));
}
// these methods are just for testing purposes
function safeApprove(address _spender, uint256 _value) public {
require(super.approve(_spender, _value));
}
function safeTransfer(address _to, uint256 _value) public {
require(super.transfer(_to, _value));
}
function safeTransferFrom(address _from, address _to, uint256 _value) public {
require(super.transferFrom(_from, _to, _value));
}
}
| contract MyToken_V1 is MintableToken {
using SafeMath for uint256;
string public name = "MyToken";
string public symbol = "MTK";
uint256 public decimals = 18;
address public burnAddress;
OldERC20 public legacyToken;
function initialize(address _legacyToken, address _burnAddress) isInitializer("MyToken", "1.0.0") public {
MintableToken.initialize(this);
burnAddress = _burnAddress;
legacyToken = OldERC20(_legacyToken);
}
function migrateToken(uint _amount) public {
migrateTokenTo(_amount, msg.sender);
}
function migrateTokenTo(uint _amount, address _to) public {
legacyToken.transferFrom(msg.sender, burnAddress, _amount);
require(this.mint(_to, _amount));
}
// these methods are just for testing purposes
function safeApprove(address _spender, uint256 _value) public {
require(super.approve(_spender, _value));
}
function safeTransfer(address _to, uint256 _value) public {
require(super.transfer(_to, _value));
}
function safeTransferFrom(address _from, address _to, uint256 _value) public {
require(super.transferFrom(_from, _to, _value));
}
}
| 30,026 |
20 | // Mapping from (partition, operator) to PartitionController status. [NOT TOKEN-HOLDER-SPECIFIC] | mapping (bytes32 => mapping (address => bool)) internal _isControllerByPartition;
| mapping (bytes32 => mapping (address => bool)) internal _isControllerByPartition;
| 37,066 |
32 | // Ensure animals can breed | modifier canBreed(uint256 parentA, uint256 parentB) {
console.log("canBreed", parentA, parentB);
require(media.tokenExists(parentA) && media.tokenExists(parentB), "Non-existent token");
require(keccak256(abi.encode(parentA)) != keccak256(abi.encode(parentB)),"Not able to breed with self" );
require(breedReady(parentA) && breedReady(parentB), "Wait for cooldown to finish.");
require(isBaseAnimal(parentA) && isBaseAnimal(parentB), "Only BASE_ANIMAL can breed.");
_;
}
| modifier canBreed(uint256 parentA, uint256 parentB) {
console.log("canBreed", parentA, parentB);
require(media.tokenExists(parentA) && media.tokenExists(parentB), "Non-existent token");
require(keccak256(abi.encode(parentA)) != keccak256(abi.encode(parentB)),"Not able to breed with self" );
require(breedReady(parentA) && breedReady(parentB), "Wait for cooldown to finish.");
require(isBaseAnimal(parentA) && isBaseAnimal(parentB), "Only BASE_ANIMAL can breed.");
_;
}
| 7,157 |
7 | // check if an address has this rolereturn bool / | function has(Role storage role, address addr)
view
internal
returns (bool)
| function has(Role storage role, address addr)
view
internal
returns (bool)
| 6,188 |
358 | // Checks if an address is already delegated _add in concernreturn bool value if the address is delegated or not / | function alreadyDelegated(address _add) public view returns(bool delegated) {
for (uint i=0; i < leaderDelegation[_add].length; i++) {
if (allDelegation[leaderDelegation[_add][i]].leader == _add) {
return true;
}
}
}
| function alreadyDelegated(address _add) public view returns(bool delegated) {
for (uint i=0; i < leaderDelegation[_add].length; i++) {
if (allDelegation[leaderDelegation[_add][i]].leader == _add) {
return true;
}
}
}
| 12,926 |
19 | // Returns the kind for the account and if it, or any of its ancestors are frozenaddr The account to retrieve kind and frozen state for return The kind of the given address / | function freezeCheck(address addr)
private
view
| function freezeCheck(address addr)
private
view
| 20,965 |
94 | // update tick and write an oracle entry if the tick change | if (state.tick != slot0Start.tick) {
(uint16 observationIndex, uint16 observationCardinality) =
observations.write(
slot0Start.observationIndex,
cache.blockTimestamp,
slot0Start.tick,
cache.liquidityStart,
slot0Start.observationCardinality,
slot0Start.observationCardinalityNext
);
| if (state.tick != slot0Start.tick) {
(uint16 observationIndex, uint16 observationCardinality) =
observations.write(
slot0Start.observationIndex,
cache.blockTimestamp,
slot0Start.tick,
cache.liquidityStart,
slot0Start.observationCardinality,
slot0Start.observationCardinalityNext
);
| 25,040 |
10 | // Event for debugging purposes |
event displayParam(uint256 _param);
|
event displayParam(uint256 _param);
| 23,459 |
118 | // CALL STAR_NFT | function stakeOutQuasar(IStarNFT _starNFT, uint256 _nftID) external payable onlyStarNFT(_starNFT) nonReentrant {
require(_starNFT.isOwnerOf(msg.sender, _nftID), "Must be owner of this Quasar NFT");
// 1.1 get info, make sure nft has backing-asset
(uint256 _mintBlock, IERC20 _stakeToken, uint256 _amount, uint256 _cid) = _starNFT.quasarInfo(_nftID);
require(address(_stakeToken) != address(0), "Backing-asset token must not be null address");
require(_amount > 0, "Backing-asset amount must be greater than 0");
// 2. pay early stake out fine if applies
_payFine(_cid, _mintBlock);
// 3. pay fee
_payFees(_cid, Operation.StakeOut);
// 4. transfer back (backed asset)
require(_stakeToken.transfer(msg.sender, _amount), "Stake out transfer assert back failed");
// 5. postStakeOut (quasar->star nft; burn quasar)
if (campaignStakeConfigs[_cid].burnRequired) {
_starNFT.burn(msg.sender, _nftID);
} else {
_starNFT.burnQuasar(msg.sender, _nftID);
}
emit EventStakeOut(address(_starNFT), _nftID);
}
| function stakeOutQuasar(IStarNFT _starNFT, uint256 _nftID) external payable onlyStarNFT(_starNFT) nonReentrant {
require(_starNFT.isOwnerOf(msg.sender, _nftID), "Must be owner of this Quasar NFT");
// 1.1 get info, make sure nft has backing-asset
(uint256 _mintBlock, IERC20 _stakeToken, uint256 _amount, uint256 _cid) = _starNFT.quasarInfo(_nftID);
require(address(_stakeToken) != address(0), "Backing-asset token must not be null address");
require(_amount > 0, "Backing-asset amount must be greater than 0");
// 2. pay early stake out fine if applies
_payFine(_cid, _mintBlock);
// 3. pay fee
_payFees(_cid, Operation.StakeOut);
// 4. transfer back (backed asset)
require(_stakeToken.transfer(msg.sender, _amount), "Stake out transfer assert back failed");
// 5. postStakeOut (quasar->star nft; burn quasar)
if (campaignStakeConfigs[_cid].burnRequired) {
_starNFT.burn(msg.sender, _nftID);
} else {
_starNFT.burnQuasar(msg.sender, _nftID);
}
emit EventStakeOut(address(_starNFT), _nftID);
}
| 71,936 |
11 | // Gets virtual nodes | function getVirtualNodes() public constant returns (bytes32[], bytes32[], int[], int[], bytes32[], uint8[]) {
bytes32[] memory idVirtualNodes = new bytes32[](virtualNodes.length);
bytes32[] memory locations = new bytes32[](virtualNodes.length);
int[] memory x = new int[](virtualNodes.length);
int[] memory y = new int[](virtualNodes.length);
bytes32[] memory resourceTypes = new bytes32[](virtualNodes.length);
uint8[] memory upperBoundCosts = new uint8[](virtualNodes.length);
for (uint i = 0; i < virtualNodes.length; i++) {
idVirtualNodes[i] = virtualNodes[i].id;
locations[i] = virtualNodes[i].location;
x[i] = virtualNodes[i].x;
y[i] = virtualNodes[i].y;
resourceTypes[i] = virtualNodes[i].resourceType;
upperBoundCosts[i] = virtualNodes[i].upperBoundCost;
}
return (idVirtualNodes, locations, x, y, resourceTypes, upperBoundCosts);
}
| function getVirtualNodes() public constant returns (bytes32[], bytes32[], int[], int[], bytes32[], uint8[]) {
bytes32[] memory idVirtualNodes = new bytes32[](virtualNodes.length);
bytes32[] memory locations = new bytes32[](virtualNodes.length);
int[] memory x = new int[](virtualNodes.length);
int[] memory y = new int[](virtualNodes.length);
bytes32[] memory resourceTypes = new bytes32[](virtualNodes.length);
uint8[] memory upperBoundCosts = new uint8[](virtualNodes.length);
for (uint i = 0; i < virtualNodes.length; i++) {
idVirtualNodes[i] = virtualNodes[i].id;
locations[i] = virtualNodes[i].location;
x[i] = virtualNodes[i].x;
y[i] = virtualNodes[i].y;
resourceTypes[i] = virtualNodes[i].resourceType;
upperBoundCosts[i] = virtualNodes[i].upperBoundCost;
}
return (idVirtualNodes, locations, x, y, resourceTypes, upperBoundCosts);
}
| 44,027 |
5 | // facilityId => spaceId[] | mapping (bytes32 => bytes32[]) private _spaceIdsByFacilityId;
| mapping (bytes32 => bytes32[]) private _spaceIdsByFacilityId;
| 21,243 |
70 | // reduce debt divided equally | uint256 accDebtReduce = uCTokenTotalAmount.sub(totalSupply()).mul(1e18).div(totalSupply());
accDebtReduce = TenMath.min(accDebtReduce, accDebtPerSupply);
accDebtPerSupply = accDebtPerSupply.sub(accDebtReduce);
| uint256 accDebtReduce = uCTokenTotalAmount.sub(totalSupply()).mul(1e18).div(totalSupply());
accDebtReduce = TenMath.min(accDebtReduce, accDebtPerSupply);
accDebtPerSupply = accDebtPerSupply.sub(accDebtReduce);
| 45,114 |
0 | // Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then be | * queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
| * queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
| 6,340 |
5 | // cTokens are now in this contract | cTokens = IERC20(token).balanceOf(address(this));
| cTokens = IERC20(token).balanceOf(address(this));
| 32,812 |
172 | // Capture some additional profit if underlying vault get appreciation | uint256 debt = vault.strategies(address(this)).totalDebt;
uint256 currentValue = estimatedTotalAssets().sub(_debtPayment);
if (currentValue > debt){
uint256 target = currentValue.sub(debt);
uint256 _beforeWant = want.balanceOf(address(this));
uint256 _withdrawMShare = _convertWantToMToken(target);
if (_withdrawMShare > minShareToProfit){
uint256 _mmVault = IERC20(mmVault).balanceOf(address(this));
if (_mmVault < _withdrawMShare){
_withdrawFromFarming(_withdrawMShare, _mmVault);
| uint256 debt = vault.strategies(address(this)).totalDebt;
uint256 currentValue = estimatedTotalAssets().sub(_debtPayment);
if (currentValue > debt){
uint256 target = currentValue.sub(debt);
uint256 _beforeWant = want.balanceOf(address(this));
uint256 _withdrawMShare = _convertWantToMToken(target);
if (_withdrawMShare > minShareToProfit){
uint256 _mmVault = IERC20(mmVault).balanceOf(address(this));
if (_mmVault < _withdrawMShare){
_withdrawFromFarming(_withdrawMShare, _mmVault);
| 46,236 |
21 | // returns pending rewards from providing address | function pendingRewards(address provider) external view returns (uint256);
| function pendingRewards(address provider) external view returns (uint256);
| 77,526 |
30 | // users accumulate rewards while exposed | function pendingRewards(address _address) public view returns (uint256) {
if (_address == uniPair) {
return 0;
}
uint256 rewards = (accRewardsPerShare * balanceOf(_address)) / 1e12;
if (rewards > 0) {
rewards -= memeStealers[_address].rewardDebt;
}
return queuedRewards[_address] + rewards;
}
| function pendingRewards(address _address) public view returns (uint256) {
if (_address == uniPair) {
return 0;
}
uint256 rewards = (accRewardsPerShare * balanceOf(_address)) / 1e12;
if (rewards > 0) {
rewards -= memeStealers[_address].rewardDebt;
}
return queuedRewards[_address] + rewards;
}
| 23,347 |
99 | // And how many of those would you receive after a transfer (deducting the transfer fee) | return feePool.amountReceivedFromTransfer(synthsTransferred);
| return feePool.amountReceivedFromTransfer(synthsTransferred);
| 30,914 |
8 | // The Ownable constructor sets the original `owner` of the contract to the sender account./ | function init(address sender) public initializer {
_owner = sender;
}
| function init(address sender) public initializer {
_owner = sender;
}
| 29,882 |
43 | // View function to check if user can harvest pool | function canHarvest(
uint256 _poolId,
address _user
| function canHarvest(
uint256 _poolId,
address _user
| 25,775 |
9 | // Updates / overrides an existing plugin in the contract. | function _updatePlugin(Plugin memory _plugin) internal {
PluginStateStorage.Data storage data = PluginStateStorage.pluginStateStorage();
string memory name = _plugin.metadata.name;
require(data.pluginNames.contains(name), "PluginState: plugin does not exist.");
address oldImplementation = data.plugins[name].metadata.implementation;
require(_plugin.metadata.implementation != oldImplementation, "PluginState: re-adding same plugin.");
data.plugins[name].metadata = _plugin.metadata;
PluginFunction[] memory oldFunctions = data.plugins[name].functions;
uint256 oldFunctionsLen = oldFunctions.length;
delete data.plugins[name].functions;
for (uint256 i = 0; i < oldFunctionsLen; i += 1) {
delete data.pluginMetadata[oldFunctions[i].functionSelector];
}
uint256 len = _plugin.functions.length;
for (uint256 i = 0; i < len; i += 1) {
require(
_plugin.functions[i].functionSelector ==
bytes4(keccak256(abi.encodePacked(_plugin.functions[i].functionSignature))),
"PluginState: fn selector and signature mismatch."
);
data.pluginMetadata[_plugin.functions[i].functionSelector] = _plugin.metadata;
data.plugins[name].functions.push(_plugin.functions[i]);
emit PluginUpdated(
oldImplementation,
_plugin.metadata.implementation,
_plugin.functions[i].functionSelector,
_plugin.functions[i].functionSignature
);
}
}
| function _updatePlugin(Plugin memory _plugin) internal {
PluginStateStorage.Data storage data = PluginStateStorage.pluginStateStorage();
string memory name = _plugin.metadata.name;
require(data.pluginNames.contains(name), "PluginState: plugin does not exist.");
address oldImplementation = data.plugins[name].metadata.implementation;
require(_plugin.metadata.implementation != oldImplementation, "PluginState: re-adding same plugin.");
data.plugins[name].metadata = _plugin.metadata;
PluginFunction[] memory oldFunctions = data.plugins[name].functions;
uint256 oldFunctionsLen = oldFunctions.length;
delete data.plugins[name].functions;
for (uint256 i = 0; i < oldFunctionsLen; i += 1) {
delete data.pluginMetadata[oldFunctions[i].functionSelector];
}
uint256 len = _plugin.functions.length;
for (uint256 i = 0; i < len; i += 1) {
require(
_plugin.functions[i].functionSelector ==
bytes4(keccak256(abi.encodePacked(_plugin.functions[i].functionSignature))),
"PluginState: fn selector and signature mismatch."
);
data.pluginMetadata[_plugin.functions[i].functionSelector] = _plugin.metadata;
data.plugins[name].functions.push(_plugin.functions[i]);
emit PluginUpdated(
oldImplementation,
_plugin.metadata.implementation,
_plugin.functions[i].functionSelector,
_plugin.functions[i].functionSignature
);
}
}
| 26,967 |
9 | // Public accessor to check the eta of a queued proposal / | function proposalEta(uint256 proposalId) public view virtual override returns (uint256) {
uint256 eta = $timelock.getTimestamp($timelockIds[proposalId]);
return eta == 1 ? 0 : eta; // _DONE_TIMESTAMP (1) should be replaced with a 0 value
}
| function proposalEta(uint256 proposalId) public view virtual override returns (uint256) {
uint256 eta = $timelock.getTimestamp($timelockIds[proposalId]);
return eta == 1 ? 0 : eta; // _DONE_TIMESTAMP (1) should be replaced with a 0 value
}
| 39,881 |
48 | // Returns the subtraction of two unsigned integers, reverting with custom message on overflow (when the result is negative). CAUTION: This function is deprecated because it requires allocating memory for the error | * message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
| * message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
| 32,066 |
11 | // Approve an address to spend another addresses' tokens. owner The address that owns the tokens. spender The address that will spend the tokens. value The number of tokens that can be spent. / | function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
| function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
| 49,867 |
53 | // Testdulu Contract to create the YFIMToken / | contract puki is TestDulu {
string public constant name = "puki";
string public constant symbol = "puki";
uint32 public constant decimals = 18;
} | contract puki is TestDulu {
string public constant name = "puki";
string public constant symbol = "puki";
uint32 public constant decimals = 18;
} | 22,314 |
29 | // exclusive access for registered address | modifier onlyRegistered() {
require(registered[msg.sender] == true, "Stakeholder must be registered");
_;
}
| modifier onlyRegistered() {
require(registered[msg.sender] == true, "Stakeholder must be registered");
_;
}
| 48,427 |
750 | // ========== MUTATIVE FUNCTIONS ========== // Set the address of the TokenState contract. This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000..as balances would be unreachable. / | function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner {
tokenState = _tokenState;
emitTokenStateUpdated(address(_tokenState));
}
| function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner {
tokenState = _tokenState;
emitTokenStateUpdated(address(_tokenState));
}
| 34,356 |
318 | // Calculate any excess funds included in msg.value. If the excess is anything worth worrying about, transfer it back to message owner. NOTE: We checked above that the msg.value is greater than or equal to the price so this cannot underflow. | uint256 feeExcess = msg.value - pveBattleFee;
| uint256 feeExcess = msg.value - pveBattleFee;
| 40,886 |
297 | // If the Master's Authority does not exist or does not accept upfront: | if (address(masterAuth) == address(0) || !masterAuth.canCall(msg.sender, address(this), msg.sig)) {
Authority auth = authority; // Memoizing saves us a warm SLOAD, around 100 gas.
| if (address(masterAuth) == address(0) || !masterAuth.canCall(msg.sender, address(this), msg.sig)) {
Authority auth = authority; // Memoizing saves us a warm SLOAD, around 100 gas.
| 71,855 |
51 | // Helper function to get ideal eth/steth amount in vault or vault's dsa. / | function getIdealBalances()
public
view
returns (BalVariables memory balances_)
| function getIdealBalances()
public
view
returns (BalVariables memory balances_)
| 55,615 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.