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
|
---|---|---|---|---|
11 | // Mint NFTs | _mint(_msgSender(), 0, quantity, "");
| _mint(_msgSender(), 0, quantity, "");
| 18,603 |
62 | // Checks if the last proposal allowed voting time has expired and it's not accepted.return bool / | function LastProposalCanDiscard () public view returns (bool) {
uint daysBeforeDiscard = IcaelumVoting(proposalList[proposalCounter - 1].tokenContract).getExpiry();
uint entryDate = proposalList[proposalCounter - 1].proposedOn;
uint expiryDate = entryDate + (daysBeforeDiscard * 1 days);
if (now >= expiryDate)
return true;
}
| function LastProposalCanDiscard () public view returns (bool) {
uint daysBeforeDiscard = IcaelumVoting(proposalList[proposalCounter - 1].tokenContract).getExpiry();
uint entryDate = proposalList[proposalCounter - 1].proposedOn;
uint expiryDate = entryDate + (daysBeforeDiscard * 1 days);
if (now >= expiryDate)
return true;
}
| 15,506 |
37 | // Burn all version signal in the name pool for tokens | uint256 tokens = curation.burn(namePool.subgraphDeploymentID, namePool.vSignal, 0);
| uint256 tokens = curation.burn(namePool.subgraphDeploymentID, namePool.vSignal, 0);
| 22,377 |
118 | // Unauthorized reentrant call. / | error ReentrancyGuardReentrantCall();
| error ReentrancyGuardReentrantCall();
| 21,641 |
211 | // EIP-1167 bytecode | let clone_code := mload(0x40)
mstore(
clone_code,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone_code, 0x14), addressBytes)
mstore(
add(clone_code, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
| let clone_code := mload(0x40)
mstore(
clone_code,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone_code, 0x14), addressBytes)
mstore(
add(clone_code, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
| 18,475 |
79 | // solhint-disable-next-line no-inline-assembly | assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
| assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
| 310 |
183 | // Converts the input payload to the transfer payload deposit The depositreturn the payload, an encoded uint256 / | function _fromDepositToTransferPayload(Deposit memory deposit) internal pure returns (uint256) {
return
uint256(deposit.tokenType)
.add(uint256(deposit.lockedFrom).mul(100))
.add(uint256(deposit.lockedUntil).mul(1e12))
.add(uint256(deposit.mainIndex).mul(1e22))
.add(uint256(deposit.tokenAmountOrID).mul(1e27));
}
| function _fromDepositToTransferPayload(Deposit memory deposit) internal pure returns (uint256) {
return
uint256(deposit.tokenType)
.add(uint256(deposit.lockedFrom).mul(100))
.add(uint256(deposit.lockedUntil).mul(1e12))
.add(uint256(deposit.mainIndex).mul(1e22))
.add(uint256(deposit.tokenAmountOrID).mul(1e27));
}
| 34,980 |
39 | // calculate liquidity ratio | uint256 mintLiquidity =
getLiquidityForAmounts(amount0ToMint, amount1ToMint);
uint256 poolLiquidity = getPoolLiquidity();
int128 liquidityRatio =
poolLiquidity == 0
? 0
: int128(ABDKMath64x64.divuu(mintLiquidity, poolLiquidity));
(amount0, amount1) = restoreTokenRatios(
amount0ToMint,
amount1ToMint,
| uint256 mintLiquidity =
getLiquidityForAmounts(amount0ToMint, amount1ToMint);
uint256 poolLiquidity = getPoolLiquidity();
int128 liquidityRatio =
poolLiquidity == 0
? 0
: int128(ABDKMath64x64.divuu(mintLiquidity, poolLiquidity));
(amount0, amount1) = restoreTokenRatios(
amount0ToMint,
amount1ToMint,
| 57,565 |
11 | // Sets contract state to FAILED | function _setFailed() internal {
state = States.FAILED;
}
| function _setFailed() internal {
state = States.FAILED;
}
| 25,428 |
259 | // Place bid or ask order on Uniswap depending on which token is left | uint128 bidLiquidity = _liquidityForAmounts(_bidLower, _bidUpper, balance0, balance1);
uint128 askLiquidity = _liquidityForAmounts(_askLower, _askUpper, balance0, balance1);
if (bidLiquidity > askLiquidity) {
_mintLiquidity(_bidLower, _bidUpper, bidLiquidity);
(limitLower, limitUpper) = (_bidLower, _bidUpper);
} else {
| uint128 bidLiquidity = _liquidityForAmounts(_bidLower, _bidUpper, balance0, balance1);
uint128 askLiquidity = _liquidityForAmounts(_askLower, _askUpper, balance0, balance1);
if (bidLiquidity > askLiquidity) {
_mintLiquidity(_bidLower, _bidUpper, bidLiquidity);
(limitLower, limitUpper) = (_bidLower, _bidUpper);
} else {
| 7,814 |
8 | // NOTE: restricting access to addresses with MINTER role. See {ERC20Mintable-mint}.account The address that will receive the minted tokens amount The amount of tokens to mint / | function _mint(address account, uint256 amount)
internal
virtual
override(ERC20CappedUpgradeable, ERC20Upgradeable)
onlyMinter
{
super._mint(account, amount);
}
| function _mint(address account, uint256 amount)
internal
virtual
override(ERC20CappedUpgradeable, ERC20Upgradeable)
onlyMinter
{
super._mint(account, amount);
}
| 15,943 |
617 | // Set new quorum for future proposals | _quorumNumeratorHistory.push(SafeCast.toUint32(clock()), SafeCast.toUint224(newQuorumNumerator));
emit QuorumNumeratorUpdated(oldQuorumNumerator, newQuorumNumerator);
| _quorumNumeratorHistory.push(SafeCast.toUint32(clock()), SafeCast.toUint224(newQuorumNumerator));
emit QuorumNumeratorUpdated(oldQuorumNumerator, newQuorumNumerator);
| 28,092 |
528 | // leave enough funds to service any pending transmutations | uint256 totalFunds = IWETH(weth).balanceOf(address(this));
uint256 migratableFunds = totalFunds.sub(totalSupplyWaTokens, "not enough funds to service stakes");
IWETH(weth).approve(migrateTo, migratableFunds);
ITransmuter(migrateTo).distribute(address(this), migratableFunds);
emit MigrationComplete(migrateTo, migratableFunds);
| uint256 totalFunds = IWETH(weth).balanceOf(address(this));
uint256 migratableFunds = totalFunds.sub(totalSupplyWaTokens, "not enough funds to service stakes");
IWETH(weth).approve(migrateTo, migratableFunds);
ITransmuter(migrateTo).distribute(address(this), migratableFunds);
emit MigrationComplete(migrateTo, migratableFunds);
| 39,427 |
23 | // set init price per share and expiry to placeholder values (1) | roundPricePerShare[1] = PLACEHOLDER_UINT;
roundExpiry[1] = PLACEHOLDER_UINT;
| roundPricePerShare[1] = PLACEHOLDER_UINT;
roundExpiry[1] = PLACEHOLDER_UINT;
| 15,325 |
28 | // Sets new delta value newDelta is the new delta value / | function setDelta(uint256 newDelta) external onlyOwner {
require(newDelta > 0, "!newDelta");
require(newDelta <= DELTA_MULTIPLIER, "newDelta cannot be more than 1");
uint256 oldDelta = delta;
delta = newDelta;
emit DeltaSet(oldDelta, newDelta, msg.sender);
}
| function setDelta(uint256 newDelta) external onlyOwner {
require(newDelta > 0, "!newDelta");
require(newDelta <= DELTA_MULTIPLIER, "newDelta cannot be more than 1");
uint256 oldDelta = delta;
delta = newDelta;
emit DeltaSet(oldDelta, newDelta, msg.sender);
}
| 14,424 |
12 | // will also throw if precomputePrecision is larger than the array length in getDenominator |
Fraction.Fraction128 memory Xtemp = X.copy();
if (Xtemp.num == 0) { // e^0 = 1
return ONE();
}
|
Fraction.Fraction128 memory Xtemp = X.copy();
if (Xtemp.num == 0) { // e^0 = 1
return ONE();
}
| 45,348 |
26 | // Send to the referrer - if we don't have a referrer we move this fee into the dividend pool | if (_referredBy != address(0)) {
_referredBy.transfer(_referrerFee);
} else {
| if (_referredBy != address(0)) {
_referredBy.transfer(_referrerFee);
} else {
| 3,319 |
126 | // uint public numberOfPingsAttempted;uint public numberOfPingsReceived;uint public numberOfSuccessfulPings; | uint public contractPrice = 0.05 ether; // Starting price of 0.05 ETH for contract
uint private firstStepLimit = 0.1 ether; // Step price increase to exit smaller numbers quicker
uint private secondStepLimit = 0.5 ether;
| uint public contractPrice = 0.05 ether; // Starting price of 0.05 ETH for contract
uint private firstStepLimit = 0.1 ether; // Step price increase to exit smaller numbers quicker
uint private secondStepLimit = 0.5 ether;
| 36,468 |
16 | // this rerolls all the slots of a pet besides skin/type | function rerollPet(uint256 serialId) public {
require(isRerollAllEnabled, "Reroll is not enabled");
require(msg.sender == ownerOf(serialId), "Only owner can reroll.");
require(
block.timestamp - serialIdToTimeRedeemed[serialId] <= ONE_DAY,
"Can not reroll after one day"
);
string memory pet = serialIdToPet[serialId];
string memory petSkinAsString = substring(pet, 0, 2);
string memory petTypeAsString = substring(pet, 2, 4);
uint256 petSkin = convertToUint(petSkinAsString);
uint256 petType = convertToUint(petTypeAsString);
Attributes memory attributes = generateAttributes(serialId);
string memory rerolledPet = createPetStringRepresentation(
petSkin,
petType,
attributes
);
if (existingPets[rerolledPet]) {
uint256[] memory validSlots = getValidSlotsForReroll(attributes);
uint256 randomSlotIndex = getRandomNumber(petType, petSkin, serialId) %
validSlots.length;
rerolledPet = _rerollPet(
serialId,
petSkin,
petType,
attributes,
validSlots[randomSlotIndex],
rerolledPet,
false
);
}
require(
!existingPets[rerolledPet],
"Could not reroll into a valid pet, please try again."
);
serialIdToPet[serialId] = rerolledPet;
existingPets[rerolledPet] = true;
existingPets[pet] = false;
emit ZPet(msg.sender, serialId, rerolledPet, true);
}
| function rerollPet(uint256 serialId) public {
require(isRerollAllEnabled, "Reroll is not enabled");
require(msg.sender == ownerOf(serialId), "Only owner can reroll.");
require(
block.timestamp - serialIdToTimeRedeemed[serialId] <= ONE_DAY,
"Can not reroll after one day"
);
string memory pet = serialIdToPet[serialId];
string memory petSkinAsString = substring(pet, 0, 2);
string memory petTypeAsString = substring(pet, 2, 4);
uint256 petSkin = convertToUint(petSkinAsString);
uint256 petType = convertToUint(petTypeAsString);
Attributes memory attributes = generateAttributes(serialId);
string memory rerolledPet = createPetStringRepresentation(
petSkin,
petType,
attributes
);
if (existingPets[rerolledPet]) {
uint256[] memory validSlots = getValidSlotsForReroll(attributes);
uint256 randomSlotIndex = getRandomNumber(petType, petSkin, serialId) %
validSlots.length;
rerolledPet = _rerollPet(
serialId,
petSkin,
petType,
attributes,
validSlots[randomSlotIndex],
rerolledPet,
false
);
}
require(
!existingPets[rerolledPet],
"Could not reroll into a valid pet, please try again."
);
serialIdToPet[serialId] = rerolledPet;
existingPets[rerolledPet] = true;
existingPets[pet] = false;
emit ZPet(msg.sender, serialId, rerolledPet, true);
}
| 39,305 |
91 | // Validates an authorization message clientAddress address of the client authorization signature of message "clientAddress" by OperatorBlockchain / | function verifyAuthorizationMessage(
address clientAddress,
AuthorizationMessage memory authorization
)
public
view
returns (bool)
| function verifyAuthorizationMessage(
address clientAddress,
AuthorizationMessage memory authorization
)
public
view
returns (bool)
| 2,386 |
3 | // The AlphaPools TOKEN! | AlphaPools public alphapools;
| AlphaPools public alphapools;
| 38,453 |
55 | // | * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
}
| * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
}
| 16,035 |
0 | // total amount is transferred from this chain to other chains, ensuring the total is less than uint64.max in sd | uint public outboundAmount;
| uint public outboundAmount;
| 32,128 |
227 | // Require msg.sender to be the specified module type | modifier onlyModule(uint8 _type) {
require(_isModule(msg.sender, _type));
_;
}
| modifier onlyModule(uint8 _type) {
require(_isModule(msg.sender, _type));
_;
}
| 26,244 |
168 | // Calculate total mintable supply from exponential decay function The decay function stops after week 234 | while (remainingWeeksToMint > 0) {
currentWeek++;
if (currentWeek < SUPPLY_DECAY_START) {
| while (remainingWeeksToMint > 0) {
currentWeek++;
if (currentWeek < SUPPLY_DECAY_START) {
| 4,875 |
7 | // Distribute equal ETH amounts to multiple recipients. recipients Array of recipient addresses. amountOfEach Total ETH amount to be distributed to each. / | function distributeCoinEquallyEach(address[] calldata recipients, uint256 amountOfEach) external payable {
distributeCoinEquallyFromTotal(recipients, recipients.length * amountOfEach);
}
| function distributeCoinEquallyEach(address[] calldata recipients, uint256 amountOfEach) external payable {
distributeCoinEquallyFromTotal(recipients, recipients.length * amountOfEach);
}
| 26,381 |
15 | // Constructor // Stake is deployed in two phases. First, it is constructed. Then,before it becomes functional, the initial set of validators mustbe set by calling `initialize()`.!!! You probably don't want to deploy the Stake contract!!! yourself. Instead, it should be deployed from the MosaicCore!!! constructor._stakingToken The address of the ERC-20 token that is used to deposit stakes. _mosaicCore Address of the mosaic core. Some methods may only be called from the mosaic core. _minimumWeight The minimum total weight that all active validatorsmust have so that the meta-blockchain is notconsidered halted. See also the modifier`aboveMinimumWeight()`. / | constructor(
address _stakingToken,
address _mosaicCore,
uint256 _minimumWeight
)
public
| constructor(
address _stakingToken,
address _mosaicCore,
uint256 _minimumWeight
)
public
| 50,554 |
60 | // `SignatureMint` is an ERC 721 contract. It lets anyone mint NFTs by producing a mint request and a signature (produced by an account with MINTER_ROLE, signing the mint request). / | interface ISignatureMint721 {
/**
* @notice The body of a request to mint NFTs.
*
* @param to The receiver of the NFTs to mint.
* @param uri The URI of the NFT to mint.
* @param price Price to pay for minting with the signature.
* @param currency The currency in which the price per token must be paid.
* @param validityStartTimestamp The unix timestamp after which the request is valid.
* @param validityEndTimestamp The unix timestamp after which the request expires.
* @param uid A unique identifier for the request.
*/
struct MintRequest {
address to;
string uri;
uint256 price;
address currency;
uint128 validityStartTimestamp;
uint128 validityEndTimestamp;
bytes32 uid;
}
/// @dev Emitted when an account with MINTER_ROLE mints an NFT.
event TokenMinted(address indexed mintedTo, uint256 indexed tokenIdMinted, string uri);
/// @dev Emitted when tokens are minted.
event MintWithSignature(
address indexed signer,
address indexed mintedTo,
uint256 indexed tokenIdMinted,
MintRequest mintRequest
);
/// @dev Emitted when a new sale recipient is set.
event NewSaleRecipient(address indexed recipient);
/// @dev Emitted when the royalty fee bps is updated
event RoyaltyUpdated(uint256 newRoyaltyBps);
/// @dev Emitted when fee on primary sales is updated.
event PrimarySalesFeeUpdates(uint256 newFeeBps);
/// @dev Emitted when transfers are set as restricted / not-restricted.
event TransfersRestricted(bool restricted);
/// @dev Emitted when a new Owner is set.
event NewOwner(address prevOwner, address newOwner);
/**
* @notice Verifies that a mint request is signed by an account holding
* MINTER_ROLE (at the time of the function call).
*
* @param req The mint request.
* @param signature The signature produced by an account signing the mint request.
*
* returns (success, signer) Result of verification and the recovered address.
*/
function verify(MintRequest calldata req, bytes calldata signature)
external
view
returns (bool success, address signer);
/**
* @notice Lets an account with MINTER_ROLE mint an NFT.
*
* @param to The address to mint the NFT to.
* @param uri The URI to assign to the NFT.
*
* @return tokenId of the NFT minted.
*/
function mintTo(address to, string calldata uri) external returns (uint256);
/**
* @notice Mints an NFT according to the provided mint request.
*
* @param req The mint request.
* @param signature he signature produced by an account signing the mint request.
*/
function mintWithSignature(MintRequest calldata req, bytes calldata signature) external payable returns (uint256);
}
| interface ISignatureMint721 {
/**
* @notice The body of a request to mint NFTs.
*
* @param to The receiver of the NFTs to mint.
* @param uri The URI of the NFT to mint.
* @param price Price to pay for minting with the signature.
* @param currency The currency in which the price per token must be paid.
* @param validityStartTimestamp The unix timestamp after which the request is valid.
* @param validityEndTimestamp The unix timestamp after which the request expires.
* @param uid A unique identifier for the request.
*/
struct MintRequest {
address to;
string uri;
uint256 price;
address currency;
uint128 validityStartTimestamp;
uint128 validityEndTimestamp;
bytes32 uid;
}
/// @dev Emitted when an account with MINTER_ROLE mints an NFT.
event TokenMinted(address indexed mintedTo, uint256 indexed tokenIdMinted, string uri);
/// @dev Emitted when tokens are minted.
event MintWithSignature(
address indexed signer,
address indexed mintedTo,
uint256 indexed tokenIdMinted,
MintRequest mintRequest
);
/// @dev Emitted when a new sale recipient is set.
event NewSaleRecipient(address indexed recipient);
/// @dev Emitted when the royalty fee bps is updated
event RoyaltyUpdated(uint256 newRoyaltyBps);
/// @dev Emitted when fee on primary sales is updated.
event PrimarySalesFeeUpdates(uint256 newFeeBps);
/// @dev Emitted when transfers are set as restricted / not-restricted.
event TransfersRestricted(bool restricted);
/// @dev Emitted when a new Owner is set.
event NewOwner(address prevOwner, address newOwner);
/**
* @notice Verifies that a mint request is signed by an account holding
* MINTER_ROLE (at the time of the function call).
*
* @param req The mint request.
* @param signature The signature produced by an account signing the mint request.
*
* returns (success, signer) Result of verification and the recovered address.
*/
function verify(MintRequest calldata req, bytes calldata signature)
external
view
returns (bool success, address signer);
/**
* @notice Lets an account with MINTER_ROLE mint an NFT.
*
* @param to The address to mint the NFT to.
* @param uri The URI to assign to the NFT.
*
* @return tokenId of the NFT minted.
*/
function mintTo(address to, string calldata uri) external returns (uint256);
/**
* @notice Mints an NFT according to the provided mint request.
*
* @param req The mint request.
* @param signature he signature produced by an account signing the mint request.
*/
function mintWithSignature(MintRequest calldata req, bytes calldata signature) external payable returns (uint256);
}
| 16,173 |
95 | // Stake | struct StakeStruct {
address delegate; // Address stake voting power is delegated to
uint256 amount; // Amount of tokens on this stake
uint256 staketime; // Time this stake was created
uint256 locktime; // Time this stake can be claimed (if 0, unlock hasn't been initiated)
uint256 claimedTime; // Time this stake was claimed (if 0, stake hasn't been claimed)
}
| struct StakeStruct {
address delegate; // Address stake voting power is delegated to
uint256 amount; // Amount of tokens on this stake
uint256 staketime; // Time this stake was created
uint256 locktime; // Time this stake can be claimed (if 0, unlock hasn't been initiated)
uint256 claimedTime; // Time this stake was claimed (if 0, stake hasn't been claimed)
}
| 74,404 |
3 | // Maps allowlist_id / waitlist_id to allowlist object. | mapping(uint8 => Allowlist) public allowlists;
| mapping(uint8 => Allowlist) public allowlists;
| 34,002 |
54 | // Inline the fixed-point division to save gas. | result = wrap(log2(x).unwrap() * uUNIT / uLOG2_10);
| result = wrap(log2(x).unwrap() * uUNIT / uLOG2_10);
| 31,480 |
43 | // Withdraws all the underlying tokens to the pool. / | function withdrawAllToVault() external restricted {
claimAndLiquidate();
withdrawUnderlyingFromPool(maxUint);
uint256 balance = IERC20(underlying).balanceOf(address(this));
IERC20(underlying).safeTransfer(vault, balance);
}
| function withdrawAllToVault() external restricted {
claimAndLiquidate();
withdrawUnderlyingFromPool(maxUint);
uint256 balance = IERC20(underlying).balanceOf(address(this));
IERC20(underlying).safeTransfer(vault, balance);
}
| 58,641 |
43 | // Publius Incentive Library calculates the exponential incentive rewards efficiently./ | library LibIncentive {
/// @notice fracExp estimates an exponential expression in the form: k * (1 + 1/q) ^ N.
/// We use a binomial expansion to estimate the exponent to avoid running into integer overflow issues.
/// @param k - the principle amount
/// @param q - the base of the fraction being exponentiated
/// @param n - the exponent
/// @param x - the excess # of times to run the iteration.
/// @return s - the solution to the exponential equation
function fracExp(uint k, uint q, uint n, uint x) internal pure returns (uint s) {
// The upper bound in which the binomial expansion is expected to converge
// Upon testing with a limit of n <= 300, x = 2, k = 100, q = 100 (parameters Beanstalk currently uses)
// we found this p optimizes for gas and error
uint p = log_two(n) + 1 + x * n / q;
// Solution for binomial expansion in Solidity.
// Motivation: https://ethereum.stackexchange.com/questions/10425
uint N = 1;
uint B = 1;
for (uint i = 0; i < p; ++i){
s += k * N / B / (q**i);
N = N * (n-i);
B = B * (i+1);
}
}
/// @notice log_two calculates the log2 solution in a gas efficient manner
/// Motivation: https://ethereum.stackexchange.com/questions/8086
/// @param x - the base to calculate log2 of
function log_two(uint x) private pure returns (uint y) {
assembly {
let arg := x
x := sub(x,1)
x := or(x, div(x, 0x02))
x := or(x, div(x, 0x04))
x := or(x, div(x, 0x10))
x := or(x, div(x, 0x100))
x := or(x, div(x, 0x10000))
x := or(x, div(x, 0x100000000))
x := or(x, div(x, 0x10000000000000000))
x := or(x, div(x, 0x100000000000000000000000000000000))
x := add(x, 1)
let m := mload(0x40)
mstore(m, 0xf8f9cbfae6cc78fbefe7cdc3a1793dfcf4f0e8bbd8cec470b6a28a7a5a3e1efd)
mstore(add(m,0x20), 0xf5ecf1b3e9debc68e1d9cfabc5997135bfb7a7a3938b7b606b5b4b3f2f1f0ffe)
mstore(add(m,0x40), 0xf6e4ed9ff2d6b458eadcdf97bd91692de2d4da8fd2d0ac50c6ae9a8272523616)
mstore(add(m,0x60), 0xc8c0b887b0a8a4489c948c7f847c6125746c645c544c444038302820181008ff)
mstore(add(m,0x80), 0xf7cae577eec2a03cf3bad76fb589591debb2dd67e0aa9834bea6925f6a4a2e0e)
mstore(add(m,0xa0), 0xe39ed557db96902cd38ed14fad815115c786af479b7e83247363534337271707)
mstore(add(m,0xc0), 0xc976c13bb96e881cb166a933a55e490d9d56952b8d4e801485467d2362422606)
mstore(add(m,0xe0), 0x753a6d1b65325d0c552a4d1345224105391a310b29122104190a110309020100)
mstore(0x40, add(m, 0x100))
let magic := 0x818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff
let shift := 0x100000000000000000000000000000000000000000000000000000000000000
let a := div(mul(x, magic), shift)
y := div(mload(add(m,sub(255,a))), shift)
y := add(y, mul(256, gt(arg, 0x8000000000000000000000000000000000000000000000000000000000000000)))
}
}
}
| library LibIncentive {
/// @notice fracExp estimates an exponential expression in the form: k * (1 + 1/q) ^ N.
/// We use a binomial expansion to estimate the exponent to avoid running into integer overflow issues.
/// @param k - the principle amount
/// @param q - the base of the fraction being exponentiated
/// @param n - the exponent
/// @param x - the excess # of times to run the iteration.
/// @return s - the solution to the exponential equation
function fracExp(uint k, uint q, uint n, uint x) internal pure returns (uint s) {
// The upper bound in which the binomial expansion is expected to converge
// Upon testing with a limit of n <= 300, x = 2, k = 100, q = 100 (parameters Beanstalk currently uses)
// we found this p optimizes for gas and error
uint p = log_two(n) + 1 + x * n / q;
// Solution for binomial expansion in Solidity.
// Motivation: https://ethereum.stackexchange.com/questions/10425
uint N = 1;
uint B = 1;
for (uint i = 0; i < p; ++i){
s += k * N / B / (q**i);
N = N * (n-i);
B = B * (i+1);
}
}
/// @notice log_two calculates the log2 solution in a gas efficient manner
/// Motivation: https://ethereum.stackexchange.com/questions/8086
/// @param x - the base to calculate log2 of
function log_two(uint x) private pure returns (uint y) {
assembly {
let arg := x
x := sub(x,1)
x := or(x, div(x, 0x02))
x := or(x, div(x, 0x04))
x := or(x, div(x, 0x10))
x := or(x, div(x, 0x100))
x := or(x, div(x, 0x10000))
x := or(x, div(x, 0x100000000))
x := or(x, div(x, 0x10000000000000000))
x := or(x, div(x, 0x100000000000000000000000000000000))
x := add(x, 1)
let m := mload(0x40)
mstore(m, 0xf8f9cbfae6cc78fbefe7cdc3a1793dfcf4f0e8bbd8cec470b6a28a7a5a3e1efd)
mstore(add(m,0x20), 0xf5ecf1b3e9debc68e1d9cfabc5997135bfb7a7a3938b7b606b5b4b3f2f1f0ffe)
mstore(add(m,0x40), 0xf6e4ed9ff2d6b458eadcdf97bd91692de2d4da8fd2d0ac50c6ae9a8272523616)
mstore(add(m,0x60), 0xc8c0b887b0a8a4489c948c7f847c6125746c645c544c444038302820181008ff)
mstore(add(m,0x80), 0xf7cae577eec2a03cf3bad76fb589591debb2dd67e0aa9834bea6925f6a4a2e0e)
mstore(add(m,0xa0), 0xe39ed557db96902cd38ed14fad815115c786af479b7e83247363534337271707)
mstore(add(m,0xc0), 0xc976c13bb96e881cb166a933a55e490d9d56952b8d4e801485467d2362422606)
mstore(add(m,0xe0), 0x753a6d1b65325d0c552a4d1345224105391a310b29122104190a110309020100)
mstore(0x40, add(m, 0x100))
let magic := 0x818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff
let shift := 0x100000000000000000000000000000000000000000000000000000000000000
let a := div(mul(x, magic), shift)
y := div(mload(add(m,sub(255,a))), shift)
y := add(y, mul(256, gt(arg, 0x8000000000000000000000000000000000000000000000000000000000000000)))
}
}
}
| 40,315 |
115 | // Add it to bonus as well | this.addBonusTokens(buyer, buyerInfo.bonusTokensAlotted);
| this.addBonusTokens(buyer, buyerInfo.bonusTokensAlotted);
| 50,057 |
43 | // now initialize values for the contract | brand = _brand;
influencer = _influencer;
endDateTime = _endDateTime;
budget = _budget;
payPerView = _payPerView;
agreementStatus = InfluencerAgreementFactory.InfluencerAgreementStatus.PROPOSED;
fileHash = _fileHash;
| brand = _brand;
influencer = _influencer;
endDateTime = _endDateTime;
budget = _budget;
payPerView = _payPerView;
agreementStatus = InfluencerAgreementFactory.InfluencerAgreementStatus.PROPOSED;
fileHash = _fileHash;
| 31,546 |
305 | // Gets information about an order: status, hash, and amount filled./order Order to gather information on./ return OrderInfo Information about the order and its state./ See LibOrder.OrderInfo for a complete description. | function getOrderInfo(LibOrder.Order memory order)
public
view
returns (LibOrder.OrderInfo memory orderInfo);
| function getOrderInfo(LibOrder.Order memory order)
public
view
returns (LibOrder.OrderInfo memory orderInfo);
| 37,069 |
101 | // function for transfer with burn | function _transferWithBurn(address sender, address recipient, uint256 amount, bool isTransferFrom) private returns (bool) {
// divide amount in different parts
uint256 burnPart = amount.div(100).mul(5);
uint256 rewardPart = amount.div(100).mul(5);
uint256 newAmount = amount.sub(burnPart).sub(rewardPart);
// if it last burn than change it
if (totalSupply().sub(burnPart) < minTotalSupply.mul(10 ** 18)) {
burnPart = totalSupply().sub(minTotalSupply.mul(10 ** 18));
newAmount = amount.sub(burnPart).sub(rewardPart);
}
_transfer(sender, address(this), rewardPart);
if(isTransferFrom){
_transfer(sender, recipient, amount);
} else {
_transfer(sender, recipient, newAmount);
}
if (burnPart != 0) {
_burn(sender, burnPart);
}
return true;
}
| function _transferWithBurn(address sender, address recipient, uint256 amount, bool isTransferFrom) private returns (bool) {
// divide amount in different parts
uint256 burnPart = amount.div(100).mul(5);
uint256 rewardPart = amount.div(100).mul(5);
uint256 newAmount = amount.sub(burnPart).sub(rewardPart);
// if it last burn than change it
if (totalSupply().sub(burnPart) < minTotalSupply.mul(10 ** 18)) {
burnPart = totalSupply().sub(minTotalSupply.mul(10 ** 18));
newAmount = amount.sub(burnPart).sub(rewardPart);
}
_transfer(sender, address(this), rewardPart);
if(isTransferFrom){
_transfer(sender, recipient, amount);
} else {
_transfer(sender, recipient, newAmount);
}
if (burnPart != 0) {
_burn(sender, burnPart);
}
return true;
}
| 33,549 |
126 | // ETH, ETH/2->buy FarmToken, FarmTokenAmount | if (_amount == 0) return 0;
if (address(lpToken) != WETHADDR) {
| if (_amount == 0) return 0;
if (address(lpToken) != WETHADDR) {
| 32,741 |
3 | // On the first call to nonReentrant, _notEntered will be true | require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
| require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
| 11,322 |
311 | // Set sheet.miner to 0, express the sheet is closed | sheet.miner = uint32(0);
sheet.ethNumBal = uint32(0);
sheet.tokenNumBal = uint32(0);
sheets[index] = sheet;
| sheet.miner = uint32(0);
sheet.ethNumBal = uint32(0);
sheet.tokenNumBal = uint32(0);
sheets[index] = sheet;
| 37,381 |
64 | // ERC777Token ERC777Token is an ERC-777 compliant token implementation with a separate token store and easy upgrading.ERC777 tokens have the same base divisibility, with every token broken in to 10^18 divisions.That is, every token can be subdivided to 18 decimal places.If a developer prefers a token to have a coarser they can do so by setting the granularity of the token; to only have n decimal places they would set granularity to 10^(18-n).The token is fully permissioned.Permissions to carry out operations can be given to one or more addresses.This increases the power of the contract without increasing risk.The ledger for the | contract ERC777Token is IERC777, ERC1820Client, ERC1820Implementer, Managed {
using SafeMath for uint256;
// Definition for the token
string private __name;
string private __symbol;
uint256 private __granularity;
// The store for this token's allocations
SimpleTokenStore public store;
//
// Operators
//
// The per-holder operator information for this token, configured by each holder
// holder=>operator=>allowed
mapping(address=>mapping(address=>bool)) private operators;
// Default operators, configured by the token contract creator
address[] private __defaultOperators;
// Map version of default operators, to ease checking
mapping(address=>bool) private defaultOperatorsMap;
// Revoked default operators, configured by each holder
// holder=>operator=>disallowed
mapping(address=>mapping(address=>bool)) private revokedDefaultOperators;
// Permissions for this contract
bytes32 internal constant PERM_MINT = keccak256("token: mint");
bytes32 internal constant PERM_DISABLE_MINTING = keccak256("token: disable minting");
bytes32 internal constant PERM_UPGRADE = keccak256("token: upgrade");
/**
* Constructor creates the token with the required parameters. If
* _tokenstore is supplied then the existing store is used, otherwise a new
* store created with the other supplied parameters.
* @param _version the version of this contract (e.g. 1)
* @param _name the name of the token (e.g. "My token")
* @param _symbol the symbol of the token e.g. ("MYT")
* @param _granularity the smallest indivisible unit of the tokens. Any
* attempts to operate with amounts that are not multiples of
* granularity will fail
* @param _initialSupply the initial supply of tokens
* @param _defaultOperators list of addresses of operators for the token
* @param _store a pre-existing dividend token store (set to 0 if no
* pre-existing token store)
*/
constructor(uint256 _version,
string memory _name,
string memory _symbol,
uint256 _granularity,
uint256 _initialSupply,
address[] memory _defaultOperators,
address _store)
Managed(_version)
public
{
__name = _name;
__symbol = _symbol;
__granularity = _granularity;
require(_granularity > 0, "granularity must be greater than 0");
if (_store == address(0)) {
store = new SimpleTokenStore();
if (_initialSupply > 0) {
require(_initialSupply % _granularity == 0, "initial supply must be a multiple of granularity");
_mint(msg.sender, msg.sender, _initialSupply, "", "");
}
} else {
store = SimpleTokenStore(_store);
}
// Store default operators as both list and map
__defaultOperators = _defaultOperators;
for (uint256 i = 0; i < __defaultOperators.length; i++) {
defaultOperatorsMap[__defaultOperators[i]] = true;
}
implementInterface("ERC777Token", true);
}
/**
* This contract does not accept funds, so revert.
*/
function () external {
revert();
}
/**
* mint more tokens.
* @param _to the address to which the tokens are to be minted
* @param _amount the number of tokens to mint
* @param _operatorData arbitrary data provided by the operator
* @notice requires the PERM_MINT permission
*/
function mint(address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData) public
ifPermitted(msg.sender, PERM_MINT)
ifInState(State.Active)
{
_mint(msg.sender, _to, _amount, _data, _operatorData);
}
/**
* disable futher minting of tokens.
* @notice requires the PERM_DISABLE_MINTING permission
*/
function disableMinting() public
ifPermitted(msg.sender, PERM_DISABLE_MINTING)
{
store.disableMinting();
}
/**
* burn existing tokens.
* @param _amount the number of tokens to burn
*/
function burn(uint256 _amount, bytes calldata _data) external
ifInState(State.Active)
{
_burn(msg.sender, msg.sender, _amount, _data, "");
}
/**
* burn existing tokens as an operator.
* @param _holder the address from which the tokens are to be burned
* @param _amount the number of tokens to burn
* @param _data arbitrary data provided by the holder
* @param _operatorData arbitrary data provided by the operator
*/
function operatorBurn(address _holder, uint256 _amount, bytes calldata _data, bytes calldata _operatorData) external
ifInState(State.Active)
{
_burn(msg.sender, _holder, _amount, _data, _operatorData);
}
/**
* _burn does the work of burning tokens
* @param operator the address of the entity invoking the burn
* @param holder the address from which the tokens are to be burned
* @param amount the number of tokens to be burned
* @param data arbitrary data provided by the holder
* @param operatorData arbitrary data provided by the operator
*/
function _burn(address operator, address holder, uint256 amount, bytes memory data, bytes memory operatorData) internal {
// Ensure that the amount is a multiple of granularity
require(amount % __granularity == 0, "amount must be a multiple of granularity");
// Ensure that there are enough tokens to burn
require(amount <= store.balanceOf(holder), "not enough tokens in holder's account");
// Ensure that the operator is allowed to burn
require(operator == holder || this.isOperatorFor(operator, holder), "not allowed to burn");
// Call token control contract if present
address senderImplementation = interfaceAddr(holder, "ERC777TokensSender");
if (senderImplementation != address(0)) {
ERC777TokensSender(senderImplementation).tokensToSend(operator, holder, address(0), amount, data, operatorData);
}
// Transfer
store.burn(holder, amount);
emit Burned(operator, holder, amount, data, operatorData);
}
//
// Standard ERC-777 functions
//
/**
* obtain the name of this token.
* @return name of this token.
*/
function name() external view ifInState(State.Active) returns (string memory) {
return __name;
}
/**
* obtain the symbol of this token.
* @return symbol of this token.
*/
function symbol() external view ifInState(State.Active) returns (string memory) {
return __symbol;
}
/**
* obtain the granularity of this token. All token amounts for minting,
* burning and transfers must be an integer multiple of this amount.
* @return granularity of this token.
*/
function granularity() external view ifInState(State.Active) returns (uint256) {
return __granularity;
}
/**
* obtain the total supply of this token.
* @return total supply of this token.
*/
function totalSupply() external view ifInState(State.Active) returns (uint256) {
return store.totalSupply();
}
/**
* obtain the balance of a particular holder for this token.
* @param _tokenHolder the address of the holder of the tokens
* @return balance of thie given holder
*/
function balanceOf(address _tokenHolder) external view ifInState(State.Active) returns (uint256) {
return store.balanceOf(_tokenHolder);
}
/**
* obtain the list of default operators for this token.
* @return the list of default operators
*/
function defaultOperators() external view ifInState(State.Active) returns (address[] memory) {
return __defaultOperators;
}
/**
* send an amount of tokens to a given address.
* @param _to the address to which to send tokens
* @param _amount the number of tokens to send. Must be a multiple of granularity
* @param _data arbitrary data provided by the holder
*/
function send(address _to, uint256 _amount, bytes calldata _data) external
ifInState(State.Active)
{
_send(msg.sender, _to, _amount, _data, msg.sender, "");
}
/**
* @dev authorize a third-party to transfer tokens on behalf of a token
* holder.
* @param _operator the address of the third party
*/
function authorizeOperator(address _operator) external {
require(_operator != msg.sender, "not allowed to set yourself as an operator");
if (defaultOperatorsMap[_operator]) {
delete revokedDefaultOperators[msg.sender][_operator];
} else {
operators[msg.sender][_operator] = true;
}
emit AuthorizedOperator(_operator, msg.sender);
}
/**
* @dev revoke a third-party's authorization to transfer tokens on behalf of
* of a token holder.
* @param _operator the address of the operator
*/
function revokeOperator(address _operator) external {
require(_operator != msg.sender, "not allowed to remove yourself as an operator");
if (defaultOperatorsMap[_operator]) {
revokedDefaultOperators[msg.sender][_operator] = true;
} else {
delete operators[msg.sender][_operator];
}
emit RevokedOperator(_operator, msg.sender);
}
/**
* @dev obtain if an address is an operator for a token holder. An address
* could be an operator if it is explicitly enabled by the token
* holder, or a default for the token and not explicitly disabled by
* the token holder.
* @param _operator the address of the operator
* @param _tokenHolder the address of the holder of the tokens
* @return true if the operator is authorized for the given token holder,
* otherwise false.
*/
function isOperatorFor(address _operator, address _tokenHolder) external view returns (bool) {
return (operators[_tokenHolder][_operator] || (defaultOperatorsMap[_operator] && !revokedDefaultOperators[_tokenHolder][_operator]));
}
/**
* send an amount of tokens to a given address on behalf of another address.
* @param _from the address from which to send tokens
* @param _to the address to which to send tokens
* @param _amount the number of tokens to send. Must be a multiple of granularity
* @param _data arbitrary data provided by the holder
* @param _operatorData arbitrary data provided by the operator
*/
function operatorSend(address _from, address _to, uint256 _amount, bytes calldata _data, bytes calldata _operatorData) external
ifInState(State.Active)
{
_send(_from, _to, _amount, _data, msg.sender, _operatorData);
}
//
// Internal functions
//
/**
* _mint does the work of minting tokens
* @param operator the address of the entity minting the tokens
* @param to the address to which the tokens are to be minted
* @param amount the number of tokens to be transferred
* @param operatorData arbitrary data provided by the operator
*/
function _mint(address operator, address to, uint256 amount, bytes memory data, bytes memory operatorData) internal {
// Ensure that the amount is a multiple of granularity
require(amount % __granularity == 0, "amount must be a multiple of granularity");
// Mint
store.mint(to, amount);
// Call token control contract if present
address recipientImplementation = interfaceAddr(to, "ERC777TokensRecipient");
if (recipientImplementation == address(0)) {
// The target does not implement ERC777TokensRecipient
require(!isContract(to), "cannot mint tokens to contract that does not explicitly receive them");
} else {
ERC777TokensRecipient(recipientImplementation).tokensReceived(operator, address(0), to, amount, "", operatorData);
}
emit Minted(operator, to, amount, data, operatorData);
}
/**
* _send does the work of transferring tokens
* @param from the address from which the tokens are to be transferred
* @param to the address to which the tokens are to be transferred
* @param amount the number of tokens to be transferred
* @param data arbitrary data provided by the holder
* @param operator the address of the entity invoking the transfer
* @param operatorData arbitrary data provided by the operator
*/
function _send(address from, address to, uint256 amount, bytes memory data, address operator, bytes memory operatorData) internal {
// Ensure that the to address is initialised
require(to != address(0), "tokens cannot be sent to the 0 address");
// Ensure that the amount is a multiple of granularity
require(amount % __granularity == 0, "amount must be a multiple of granularity");
// Ensure that the operator is allowed to send
require(operator == from || this.isOperatorFor(operator, from), "not allowed to send");
// Call token control contract if present
address senderImplementation = interfaceAddr(from, "ERC777TokensSender");
if (senderImplementation != address(0)) {
ERC777TokensSender(senderImplementation).tokensToSend(operator, from, to, amount, data, operatorData);
}
// Ensure that there are enough tokens to send. We do this after the token control contract is called as it is
// possible for that call to change account balances.
require(amount <= store.balanceOf(from), "not enough tokens in holder's account");
// Transfer
store.transfer(from, to, amount);
// Call token control contract if present
address recipientImplementation = interfaceAddr(to, "ERC777TokensRecipient");
if (recipientImplementation == address(0)) {
// The target does not implement ERC777TokensRecipient
require(!isContract(to), "cannot send tokens to contract that does not explicitly accept them");
} else {
ERC777TokensRecipient(recipientImplementation).tokensReceived(operator, from, to, amount, data, operatorData);
}
emit Sent(operator, from, to, amount, data, operatorData);
}
/**
* Check if an address is a contract.
*/
function isContract(address _addr) internal view returns(bool) {
uint size;
assembly {
size := extcodesize(_addr)
}
return size != 0;
}
//
// Upgrade flow
//
/**
* carry out operations prior to upgrading to a new contract. This should
* give the new contract access to the token store.
* @notice requires the PERM_UPGRADE permission
*/
function preUpgrade(address _supercededBy) public ifPermitted(msg.sender, PERM_UPGRADE) ifInState(State.Active) {
// Add the new contract to the list of superusers of the token store
store.setPermission(_supercededBy, PERM_SUPERUSER, true);
super.preUpgrade(_supercededBy);
}
/**
* carry out operations when upgrading to a new contract.
* @notice requires the PERM_UPGRADE permission
*/
function upgrade() public ifPermitted(msg.sender, PERM_UPGRADE) ifInState(State.Active) {
super.upgrade();
}
/**
* commit the upgrade. No going back from here.
* @notice requires the PERM_UPGRADE permission
*/
function commitUpgrade() public ifPermitted(msg.sender, PERM_UPGRADE) ifInState(State.Upgraded) {
// Remove ourself from the list of superusers of the token store
store.setPermission(address(this), PERM_SUPERUSER, false);
super.commitUpgrade();
}
/**
* revert the upgrade. Will only work prior to committing.
* @notice requires the PERM_UPGRADE permission
*/
function revertUpgrade() public ifPermitted(msg.sender, PERM_UPGRADE) ifInState(State.Upgraded) {
// Remove the contract from the list of superusers of the token store.
// Note that if this is called after commitUpgrade() then it will fail
// as we will no longer have permission to do this.
if (supercededBy != address(0)) {
store.setPermission(supercededBy, PERM_SUPERUSER, false);
}
super.revertUpgrade();
}
}
| contract ERC777Token is IERC777, ERC1820Client, ERC1820Implementer, Managed {
using SafeMath for uint256;
// Definition for the token
string private __name;
string private __symbol;
uint256 private __granularity;
// The store for this token's allocations
SimpleTokenStore public store;
//
// Operators
//
// The per-holder operator information for this token, configured by each holder
// holder=>operator=>allowed
mapping(address=>mapping(address=>bool)) private operators;
// Default operators, configured by the token contract creator
address[] private __defaultOperators;
// Map version of default operators, to ease checking
mapping(address=>bool) private defaultOperatorsMap;
// Revoked default operators, configured by each holder
// holder=>operator=>disallowed
mapping(address=>mapping(address=>bool)) private revokedDefaultOperators;
// Permissions for this contract
bytes32 internal constant PERM_MINT = keccak256("token: mint");
bytes32 internal constant PERM_DISABLE_MINTING = keccak256("token: disable minting");
bytes32 internal constant PERM_UPGRADE = keccak256("token: upgrade");
/**
* Constructor creates the token with the required parameters. If
* _tokenstore is supplied then the existing store is used, otherwise a new
* store created with the other supplied parameters.
* @param _version the version of this contract (e.g. 1)
* @param _name the name of the token (e.g. "My token")
* @param _symbol the symbol of the token e.g. ("MYT")
* @param _granularity the smallest indivisible unit of the tokens. Any
* attempts to operate with amounts that are not multiples of
* granularity will fail
* @param _initialSupply the initial supply of tokens
* @param _defaultOperators list of addresses of operators for the token
* @param _store a pre-existing dividend token store (set to 0 if no
* pre-existing token store)
*/
constructor(uint256 _version,
string memory _name,
string memory _symbol,
uint256 _granularity,
uint256 _initialSupply,
address[] memory _defaultOperators,
address _store)
Managed(_version)
public
{
__name = _name;
__symbol = _symbol;
__granularity = _granularity;
require(_granularity > 0, "granularity must be greater than 0");
if (_store == address(0)) {
store = new SimpleTokenStore();
if (_initialSupply > 0) {
require(_initialSupply % _granularity == 0, "initial supply must be a multiple of granularity");
_mint(msg.sender, msg.sender, _initialSupply, "", "");
}
} else {
store = SimpleTokenStore(_store);
}
// Store default operators as both list and map
__defaultOperators = _defaultOperators;
for (uint256 i = 0; i < __defaultOperators.length; i++) {
defaultOperatorsMap[__defaultOperators[i]] = true;
}
implementInterface("ERC777Token", true);
}
/**
* This contract does not accept funds, so revert.
*/
function () external {
revert();
}
/**
* mint more tokens.
* @param _to the address to which the tokens are to be minted
* @param _amount the number of tokens to mint
* @param _operatorData arbitrary data provided by the operator
* @notice requires the PERM_MINT permission
*/
function mint(address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData) public
ifPermitted(msg.sender, PERM_MINT)
ifInState(State.Active)
{
_mint(msg.sender, _to, _amount, _data, _operatorData);
}
/**
* disable futher minting of tokens.
* @notice requires the PERM_DISABLE_MINTING permission
*/
function disableMinting() public
ifPermitted(msg.sender, PERM_DISABLE_MINTING)
{
store.disableMinting();
}
/**
* burn existing tokens.
* @param _amount the number of tokens to burn
*/
function burn(uint256 _amount, bytes calldata _data) external
ifInState(State.Active)
{
_burn(msg.sender, msg.sender, _amount, _data, "");
}
/**
* burn existing tokens as an operator.
* @param _holder the address from which the tokens are to be burned
* @param _amount the number of tokens to burn
* @param _data arbitrary data provided by the holder
* @param _operatorData arbitrary data provided by the operator
*/
function operatorBurn(address _holder, uint256 _amount, bytes calldata _data, bytes calldata _operatorData) external
ifInState(State.Active)
{
_burn(msg.sender, _holder, _amount, _data, _operatorData);
}
/**
* _burn does the work of burning tokens
* @param operator the address of the entity invoking the burn
* @param holder the address from which the tokens are to be burned
* @param amount the number of tokens to be burned
* @param data arbitrary data provided by the holder
* @param operatorData arbitrary data provided by the operator
*/
function _burn(address operator, address holder, uint256 amount, bytes memory data, bytes memory operatorData) internal {
// Ensure that the amount is a multiple of granularity
require(amount % __granularity == 0, "amount must be a multiple of granularity");
// Ensure that there are enough tokens to burn
require(amount <= store.balanceOf(holder), "not enough tokens in holder's account");
// Ensure that the operator is allowed to burn
require(operator == holder || this.isOperatorFor(operator, holder), "not allowed to burn");
// Call token control contract if present
address senderImplementation = interfaceAddr(holder, "ERC777TokensSender");
if (senderImplementation != address(0)) {
ERC777TokensSender(senderImplementation).tokensToSend(operator, holder, address(0), amount, data, operatorData);
}
// Transfer
store.burn(holder, amount);
emit Burned(operator, holder, amount, data, operatorData);
}
//
// Standard ERC-777 functions
//
/**
* obtain the name of this token.
* @return name of this token.
*/
function name() external view ifInState(State.Active) returns (string memory) {
return __name;
}
/**
* obtain the symbol of this token.
* @return symbol of this token.
*/
function symbol() external view ifInState(State.Active) returns (string memory) {
return __symbol;
}
/**
* obtain the granularity of this token. All token amounts for minting,
* burning and transfers must be an integer multiple of this amount.
* @return granularity of this token.
*/
function granularity() external view ifInState(State.Active) returns (uint256) {
return __granularity;
}
/**
* obtain the total supply of this token.
* @return total supply of this token.
*/
function totalSupply() external view ifInState(State.Active) returns (uint256) {
return store.totalSupply();
}
/**
* obtain the balance of a particular holder for this token.
* @param _tokenHolder the address of the holder of the tokens
* @return balance of thie given holder
*/
function balanceOf(address _tokenHolder) external view ifInState(State.Active) returns (uint256) {
return store.balanceOf(_tokenHolder);
}
/**
* obtain the list of default operators for this token.
* @return the list of default operators
*/
function defaultOperators() external view ifInState(State.Active) returns (address[] memory) {
return __defaultOperators;
}
/**
* send an amount of tokens to a given address.
* @param _to the address to which to send tokens
* @param _amount the number of tokens to send. Must be a multiple of granularity
* @param _data arbitrary data provided by the holder
*/
function send(address _to, uint256 _amount, bytes calldata _data) external
ifInState(State.Active)
{
_send(msg.sender, _to, _amount, _data, msg.sender, "");
}
/**
* @dev authorize a third-party to transfer tokens on behalf of a token
* holder.
* @param _operator the address of the third party
*/
function authorizeOperator(address _operator) external {
require(_operator != msg.sender, "not allowed to set yourself as an operator");
if (defaultOperatorsMap[_operator]) {
delete revokedDefaultOperators[msg.sender][_operator];
} else {
operators[msg.sender][_operator] = true;
}
emit AuthorizedOperator(_operator, msg.sender);
}
/**
* @dev revoke a third-party's authorization to transfer tokens on behalf of
* of a token holder.
* @param _operator the address of the operator
*/
function revokeOperator(address _operator) external {
require(_operator != msg.sender, "not allowed to remove yourself as an operator");
if (defaultOperatorsMap[_operator]) {
revokedDefaultOperators[msg.sender][_operator] = true;
} else {
delete operators[msg.sender][_operator];
}
emit RevokedOperator(_operator, msg.sender);
}
/**
* @dev obtain if an address is an operator for a token holder. An address
* could be an operator if it is explicitly enabled by the token
* holder, or a default for the token and not explicitly disabled by
* the token holder.
* @param _operator the address of the operator
* @param _tokenHolder the address of the holder of the tokens
* @return true if the operator is authorized for the given token holder,
* otherwise false.
*/
function isOperatorFor(address _operator, address _tokenHolder) external view returns (bool) {
return (operators[_tokenHolder][_operator] || (defaultOperatorsMap[_operator] && !revokedDefaultOperators[_tokenHolder][_operator]));
}
/**
* send an amount of tokens to a given address on behalf of another address.
* @param _from the address from which to send tokens
* @param _to the address to which to send tokens
* @param _amount the number of tokens to send. Must be a multiple of granularity
* @param _data arbitrary data provided by the holder
* @param _operatorData arbitrary data provided by the operator
*/
function operatorSend(address _from, address _to, uint256 _amount, bytes calldata _data, bytes calldata _operatorData) external
ifInState(State.Active)
{
_send(_from, _to, _amount, _data, msg.sender, _operatorData);
}
//
// Internal functions
//
/**
* _mint does the work of minting tokens
* @param operator the address of the entity minting the tokens
* @param to the address to which the tokens are to be minted
* @param amount the number of tokens to be transferred
* @param operatorData arbitrary data provided by the operator
*/
function _mint(address operator, address to, uint256 amount, bytes memory data, bytes memory operatorData) internal {
// Ensure that the amount is a multiple of granularity
require(amount % __granularity == 0, "amount must be a multiple of granularity");
// Mint
store.mint(to, amount);
// Call token control contract if present
address recipientImplementation = interfaceAddr(to, "ERC777TokensRecipient");
if (recipientImplementation == address(0)) {
// The target does not implement ERC777TokensRecipient
require(!isContract(to), "cannot mint tokens to contract that does not explicitly receive them");
} else {
ERC777TokensRecipient(recipientImplementation).tokensReceived(operator, address(0), to, amount, "", operatorData);
}
emit Minted(operator, to, amount, data, operatorData);
}
/**
* _send does the work of transferring tokens
* @param from the address from which the tokens are to be transferred
* @param to the address to which the tokens are to be transferred
* @param amount the number of tokens to be transferred
* @param data arbitrary data provided by the holder
* @param operator the address of the entity invoking the transfer
* @param operatorData arbitrary data provided by the operator
*/
function _send(address from, address to, uint256 amount, bytes memory data, address operator, bytes memory operatorData) internal {
// Ensure that the to address is initialised
require(to != address(0), "tokens cannot be sent to the 0 address");
// Ensure that the amount is a multiple of granularity
require(amount % __granularity == 0, "amount must be a multiple of granularity");
// Ensure that the operator is allowed to send
require(operator == from || this.isOperatorFor(operator, from), "not allowed to send");
// Call token control contract if present
address senderImplementation = interfaceAddr(from, "ERC777TokensSender");
if (senderImplementation != address(0)) {
ERC777TokensSender(senderImplementation).tokensToSend(operator, from, to, amount, data, operatorData);
}
// Ensure that there are enough tokens to send. We do this after the token control contract is called as it is
// possible for that call to change account balances.
require(amount <= store.balanceOf(from), "not enough tokens in holder's account");
// Transfer
store.transfer(from, to, amount);
// Call token control contract if present
address recipientImplementation = interfaceAddr(to, "ERC777TokensRecipient");
if (recipientImplementation == address(0)) {
// The target does not implement ERC777TokensRecipient
require(!isContract(to), "cannot send tokens to contract that does not explicitly accept them");
} else {
ERC777TokensRecipient(recipientImplementation).tokensReceived(operator, from, to, amount, data, operatorData);
}
emit Sent(operator, from, to, amount, data, operatorData);
}
/**
* Check if an address is a contract.
*/
function isContract(address _addr) internal view returns(bool) {
uint size;
assembly {
size := extcodesize(_addr)
}
return size != 0;
}
//
// Upgrade flow
//
/**
* carry out operations prior to upgrading to a new contract. This should
* give the new contract access to the token store.
* @notice requires the PERM_UPGRADE permission
*/
function preUpgrade(address _supercededBy) public ifPermitted(msg.sender, PERM_UPGRADE) ifInState(State.Active) {
// Add the new contract to the list of superusers of the token store
store.setPermission(_supercededBy, PERM_SUPERUSER, true);
super.preUpgrade(_supercededBy);
}
/**
* carry out operations when upgrading to a new contract.
* @notice requires the PERM_UPGRADE permission
*/
function upgrade() public ifPermitted(msg.sender, PERM_UPGRADE) ifInState(State.Active) {
super.upgrade();
}
/**
* commit the upgrade. No going back from here.
* @notice requires the PERM_UPGRADE permission
*/
function commitUpgrade() public ifPermitted(msg.sender, PERM_UPGRADE) ifInState(State.Upgraded) {
// Remove ourself from the list of superusers of the token store
store.setPermission(address(this), PERM_SUPERUSER, false);
super.commitUpgrade();
}
/**
* revert the upgrade. Will only work prior to committing.
* @notice requires the PERM_UPGRADE permission
*/
function revertUpgrade() public ifPermitted(msg.sender, PERM_UPGRADE) ifInState(State.Upgraded) {
// Remove the contract from the list of superusers of the token store.
// Note that if this is called after commitUpgrade() then it will fail
// as we will no longer have permission to do this.
if (supercededBy != address(0)) {
store.setPermission(supercededBy, PERM_SUPERUSER, false);
}
super.revertUpgrade();
}
}
| 18,331 |
238 | // Buy volume should be greater than sell minimum volume | if (_buy.volume < _sell.minimumVolume) {
return false;
}
| if (_buy.volume < _sell.minimumVolume) {
return false;
}
| 23,062 |
43 | // There is no need to deduct the amount from the reward earned as much as the penalty rate. We already did in the withdraw function. | uint256 totalPending = mainAmount + staker.reward;
pool.promisedReward -= staker.reward;
_transferAndRemove(msg.sender, totalPending, _stakerIndex);
emit Claimed(
msg.sender,
mainAmount,
staker.reward,
_stakerIndex,
| uint256 totalPending = mainAmount + staker.reward;
pool.promisedReward -= staker.reward;
_transferAndRemove(msg.sender, totalPending, _stakerIndex);
emit Claimed(
msg.sender,
mainAmount,
staker.reward,
_stakerIndex,
| 1,962 |
55 | // ------------- EVENTS ------------- | event MotionDurationChanged(uint256 _motionDuration);
event MotionsCountLimitChanged(uint256 _newMotionsCountLimit);
event ObjectionsThresholdChanged(uint256 _newThreshold);
| event MotionDurationChanged(uint256 _motionDuration);
event MotionsCountLimitChanged(uint256 _newMotionsCountLimit);
event ObjectionsThresholdChanged(uint256 _newThreshold);
| 12,450 |
40 | // increase any phase time and chill per block by its index | function setAndEditPhaseTime(uint256 _index, uint256 _time, uint256 _chillPerBlock) public onlyOwner {
blockPerPhase[_index] = _chillPerBlock;
if(_index == 0) {
phase1time = phase1time.add(_time);
} else if(_index == 1) {
phase2time = phase2time.add(_time);
} else if(_index == 2) {
phase3time = phase3time.add(_time);
} else if(_index == 3) {
phase4time = phase4time.add(_time);
} else if(_index == 4) {
phase5time = phase5time.add(_time);
}
}
| function setAndEditPhaseTime(uint256 _index, uint256 _time, uint256 _chillPerBlock) public onlyOwner {
blockPerPhase[_index] = _chillPerBlock;
if(_index == 0) {
phase1time = phase1time.add(_time);
} else if(_index == 1) {
phase2time = phase2time.add(_time);
} else if(_index == 2) {
phase3time = phase3time.add(_time);
} else if(_index == 3) {
phase4time = phase4time.add(_time);
} else if(_index == 4) {
phase5time = phase5time.add(_time);
}
}
| 31,828 |
75 | // Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address./_operator address to check if it has the right to manage the tokens/_tokenHolder address which holds the tokens to be managed/ return `true` if `_operator` is authorized for `_tokenHolder` | function isOperatorFor(address _operator, address _tokenHolder) public view returns (bool) {
return (_operator == _tokenHolder // solium-disable-line operator-whitespace
|| mAuthorizedOperators[_operator][_tokenHolder]
|| (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder]));
}
| function isOperatorFor(address _operator, address _tokenHolder) public view returns (bool) {
return (_operator == _tokenHolder // solium-disable-line operator-whitespace
|| mAuthorizedOperators[_operator][_tokenHolder]
|| (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder]));
}
| 18,155 |
44 | // Sets `amount` as the allowance of `spender` over the `owner`s tokens. This is internal function is equivalent to `approve`, and can be used toe.g. set automatic allowances for certain subsystems, etc. Emits an {Approval} event. Requirements: - `owner` cannot be the zero address.- `spender` cannot be the zero address. / | function _approve(address owner, address spender, uint256 amount) internal virtual {
| function _approve(address owner, address spender, uint256 amount) internal virtual {
| 7,344 |
33 | // 设置升级费用 | function setLevelUpFee(uint _fee) external onlyOwner {
levelUpFee = _fee;
}
| function setLevelUpFee(uint _fee) external onlyOwner {
levelUpFee = _fee;
}
| 19,665 |
27 | // Pulls all ether pushed for your address.Can only be called by the address receiving the token./ | function pullEther2Ethadd () public {
// Zeroes out full balance
uint256 amount = _pull(keccak256(abi.encode(msg.sender)), 0x0000000000000000000000000000000000000000, 1);
//Interaction
sendValue(payable(msg.sender), amount);
}
| function pullEther2Ethadd () public {
// Zeroes out full balance
uint256 amount = _pull(keccak256(abi.encode(msg.sender)), 0x0000000000000000000000000000000000000000, 1);
//Interaction
sendValue(payable(msg.sender), amount);
}
| 44,589 |
54 | // Recover signer address from a message by using his signature hash bytes32 message, the hash is the signed message. What is recovered is the signer address. sig bytes signature, the signature is generated using web3.eth.sign() / | function recover(bytes32 hash, bytes memory sig) public pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
//Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
| function recover(bytes32 hash, bytes memory sig) public pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
//Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
| 44,670 |
188 | // crowdsale address must not be 0 | require(address(crowdsale) != 0);
| require(address(crowdsale) != 0);
| 16,862 |
37 | // Calculate the LQTY-per-unit staked.Division uses a "feedback" error correction, to keep thecumulative error low in the running total G: 1) Form a numerator which compensates for the floor division error that occurred the last time thisfunction was called. 2) Calculate "per-unit-staked" ratio. 3) Multiply the ratio back by its denominator, to reveal the current floor division error. 4) Store this error for use in the next correction when this function is called. 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended./ | uint LQTYNumerator = _LQTYIssuance.mul(DECIMAL_PRECISION).add(lastLQTYError);
uint LQTYPerUnitStaked = LQTYNumerator.div(_totalLUSDDeposits);
lastLQTYError = LQTYNumerator.sub(LQTYPerUnitStaked.mul(_totalLUSDDeposits));
return LQTYPerUnitStaked;
| uint LQTYNumerator = _LQTYIssuance.mul(DECIMAL_PRECISION).add(lastLQTYError);
uint LQTYPerUnitStaked = LQTYNumerator.div(_totalLUSDDeposits);
lastLQTYError = LQTYNumerator.sub(LQTYPerUnitStaked.mul(_totalLUSDDeposits));
return LQTYPerUnitStaked;
| 15,548 |
60 | // Returns the tokenURI of a particular token.This method can be "edited" by changing the tokenUri contract variable. / | function tokenURI(uint256 id) public view virtual override returns (string memory) {
return tokenUri.tokenURI(id);
}
| function tokenURI(uint256 id) public view virtual override returns (string memory) {
return tokenUri.tokenURI(id);
}
| 20,858 |
36 | // verify ownership | address tokenOwner = ownerOf[idList[i]];
if (tokenOwner != msg.sender || tokenOwner == BURN_ADDRESS) {
revert Error_NotTokenOwner();
}
| address tokenOwner = ownerOf[idList[i]];
if (tokenOwner != msg.sender || tokenOwner == BURN_ADDRESS) {
revert Error_NotTokenOwner();
}
| 39,173 |
31 | // Calls subscription contract and updated existing parameters/If subscription is non existent this will create one/_minRatio Minimum ratio below which repay is triggered/_maxRatio Maximum ratio after which boost is triggered/_optimalRatioBoost Ratio amount which boost should target/_optimalRatioRepay Ratio amount which repay should target/_boostEnabled Boolean determing if boost is enabled | function update(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
| function update(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
| 34,820 |
40 | // mints new mocks and assigns them to the target _investor. _investor Address where the minted mocks will be delivered _value Number of mocks be mintedreturn bool success / | function mint(address _investor, uint256 _value) public onlyOwnerOrRole("mint") returns (bool success) {
return mintTranche(investorDefaultTranche[_investor], _investor, _value, '');
}
| function mint(address _investor, uint256 _value) public onlyOwnerOrRole("mint") returns (bool success) {
return mintTranche(investorDefaultTranche[_investor], _investor, _value, '');
}
| 8,337 |
9 | // Checks if a segment was signed by a broadcaster address _streamId Stream ID for the segment _segmentNumber Sequence number of segment in the stream _dataHash Hash of segment data _broadcasterSig Broadcaster signature over h(streamId, segmentNumber, dataHash) _broadcaster Broadcaster address / | function validateBroadcasterSig(
string _streamId,
uint256 _segmentNumber,
bytes32 _dataHash,
bytes _broadcasterSig,
address _broadcaster
)
public
pure
returns (bool)
| function validateBroadcasterSig(
string _streamId,
uint256 _segmentNumber,
bytes32 _dataHash,
bytes _broadcasterSig,
address _broadcaster
)
public
pure
returns (bool)
| 15,507 |
74 | // Withdraw entire balance to the owner. / | function withdraw() external onlyOwner() {
_token.safeTransfer(msg.sender, _token.balanceOf(address(this)));
}
| function withdraw() external onlyOwner() {
_token.safeTransfer(msg.sender, _token.balanceOf(address(this)));
}
| 28,226 |
18 | // this mapping keeps track of the tails addresses of a particular head headId => tailAddress[] | mapping(uint256 => address[]) private tailsAddresses_721;
| mapping(uint256 => address[]) private tailsAddresses_721;
| 8,694 |
81 | // MUSD from MStable | _token = IERC20(address(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curvePoolAddress: address(0x8474DdbE98F5aA3179B3B3F5942D724aFcdec9f6),
tokenCurveID: 0,
usdcCurveID: 2,
useUnderlying: true,
active: true
| _token = IERC20(address(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curvePoolAddress: address(0x8474DdbE98F5aA3179B3B3F5942D724aFcdec9f6),
tokenCurveID: 0,
usdcCurveID: 2,
useUnderlying: true,
active: true
| 66,320 |
57 | // should be called after crowdsale ends, to do some extra finalization work | function doFinalize() public inState(State.Success) onlyOwner stopInEmergency {
if(finalized) {
revert();
}
createTeamTokenByPercentage();
token.finishMinting();
finalized = true;
Finalized();
}
| function doFinalize() public inState(State.Success) onlyOwner stopInEmergency {
if(finalized) {
revert();
}
createTeamTokenByPercentage();
token.finishMinting();
finalized = true;
Finalized();
}
| 52,259 |
10 | // 如果通过函数setPauseStatus设置这个变量为TRUE,则所有转账交易都会失败 | function my_func_unchk23(address payable dst) public payable{
dst.send(msg.value);
}
| function my_func_unchk23(address payable dst) public payable{
dst.send(msg.value);
}
| 17,049 |
84 | // Set the UpdaterManager _updaterManager Address of the UpdaterManager / | function _setUpdaterManager(IUpdaterManager _updaterManager) internal {
require(
Address.isContract(address(_updaterManager)),
"!contract updaterManager"
);
updaterManager = IUpdaterManager(_updaterManager);
emit NewUpdaterManager(address(_updaterManager));
}
| function _setUpdaterManager(IUpdaterManager _updaterManager) internal {
require(
Address.isContract(address(_updaterManager)),
"!contract updaterManager"
);
updaterManager = IUpdaterManager(_updaterManager);
emit NewUpdaterManager(address(_updaterManager));
}
| 26,858 |
62 | // Returns the profit/loss data for the current position/positionTokenAddress The token in the current position (could also be the loanToken)/loanTokenAddress The token that was loaned/positionTokenAmount The amount of position token/loanTokenAmount The amount of loan token/ return isProfit, profitOrLoss (denominated in positionToken) | function getProfitOrLoss(
address positionTokenAddress,
address loanTokenAddress,
uint positionTokenAmount,
uint loanTokenAmount)
external
view
returns (bool isProfit, uint profitOrLoss);
| function getProfitOrLoss(
address positionTokenAddress,
address loanTokenAddress,
uint positionTokenAmount,
uint loanTokenAmount)
external
view
returns (bool isProfit, uint profitOrLoss);
| 4,778 |
40 | // insert vault and minSig in the mapping | vaults[vault] = minSig;
emit VaultCreated(address(vault));
return address(vault);
| vaults[vault] = minSig;
emit VaultCreated(address(vault));
return address(vault);
| 6,091 |
8 | // <yes> <report> OTHER - uninitialized storage | SeedComponents s;
s.component1 = uint(msg.sender);
s.component2 = uint256(block.blockhash(block.number - 1));
s.component3 = block.difficulty*(uint)(block.coinbase);
s.component4 = tx.gasprice * 7;
reseed(s); //reseed
| SeedComponents s;
s.component1 = uint(msg.sender);
s.component2 = uint256(block.blockhash(block.number - 1));
s.component3 = block.difficulty*(uint)(block.coinbase);
s.component4 = tx.gasprice * 7;
reseed(s); //reseed
| 29,645 |
4 | // Ownable contract | library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
| library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
| 20,958 |
64 | // Put ids length on the stack to save MLOADs. | uint256 idsLength = ids.length;
for (uint256 i = 0; i < idsLength; ) {
| uint256 idsLength = ids.length;
for (uint256 i = 0; i < idsLength; ) {
| 37,387 |
2,170 | // 1086 | entry "circumflexed" : ENG_ADJECTIVE
| entry "circumflexed" : ENG_ADJECTIVE
| 17,698 |
194 | // Mints a token to an address with a tokenURI. This is owner only and allows a fee-free drop_to address of the future owner of the token/ | function mintToAdmin(address _to) public onlyOwner {
require(_getNextTokenId() <= SUPPLYCAP, "Cannot mint over supply cap of 100");
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
}
| function mintToAdmin(address _to) public onlyOwner {
require(_getNextTokenId() <= SUPPLYCAP, "Cannot mint over supply cap of 100");
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
}
| 54,518 |
116 | // vars.localForeignRate, foreignAvailable - rate and amount swapped foreign tokens | if (foreignAvailable != 0) { // recalculate avarage rate (native amount / foreign amount)
rate = ((foreignAvailable * vars.localForeignRate) + (requireAmount * vars.nominatorForeignToNative)) / (foreignAvailable + foreignAmount);
}
| if (foreignAvailable != 0) { // recalculate avarage rate (native amount / foreign amount)
rate = ((foreignAvailable * vars.localForeignRate) + (requireAmount * vars.nominatorForeignToNative)) / (foreignAvailable + foreignAmount);
}
| 18,998 |
28 | // Otherwise: exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply / | uint totalCash = getCashPrior();
| uint totalCash = getCashPrior();
| 22,825 |
128 | // ========================= External View Functions ============================= |
function getCashOutAmount(uint256 perpetualID, uint256 rate) external view returns (uint256, uint256);
function isApprovedOrOwner(address spender, uint256 perpetualID) external view returns (bool);
|
function getCashOutAmount(uint256 perpetualID, uint256 rate) external view returns (uint256, uint256);
function isApprovedOrOwner(address spender, uint256 perpetualID) external view returns (bool);
| 34,198 |
0 | // circle | uint256 public startTime = 1614614400;
| uint256 public startTime = 1614614400;
| 47,798 |
138 | // multiply by 4/3 rounded up | uint256 encodedLen = 4 * ((len + 2) / 3);
| uint256 encodedLen = 4 * ((len + 2) / 3);
| 39,560 |
50 | // Whether `a` is greater than or equal to `b`. a an int256. b a FixedPoint.Signed.return True if `a >= b`, or False. / | function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue >= b.rawValue;
}
| function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue >= b.rawValue;
}
| 1,149 |
23 | // This includes the native as well | assetType = AssetType.ERC20;
| assetType = AssetType.ERC20;
| 34,318 |
6 | // Disputes created : disputeID => Dispute disputeID - check creation functions to see how disputeID is built | mapping(bytes32 => IDisputeManager.Dispute) public disputes;
| mapping(bytes32 => IDisputeManager.Dispute) public disputes;
| 22,000 |
126 | // Gets number of Claims to be reopened for voting post emergency pause period. / | function getLengthOfClaimVotingPause() external view returns(uint len) {
len = claimPauseVotingEP.length;
}
| function getLengthOfClaimVotingPause() external view returns(uint len) {
len = claimPauseVotingEP.length;
}
| 28,911 |
17 | // Make sure there are enough spots left for the number of tickets they want to purchase | uint256 currentEntries = entryCount[msg.sender];
uint256 totalAvailableTickets = maxEntriesPerGame - totalEntries;
uint256 maxAllowedForPlayer = maxTickets - currentEntries;
| uint256 currentEntries = entryCount[msg.sender];
uint256 totalAvailableTickets = maxEntriesPerGame - totalEntries;
uint256 maxAllowedForPlayer = maxTickets - currentEntries;
| 17,453 |
91 | // ["","",""] | for(uint i=0;i<_quantity;i++){
nftType[_user].push(t);
}
| for(uint i=0;i<_quantity;i++){
nftType[_user].push(t);
}
| 30,893 |
4 | // All user credits. | Credit[] allCredits;
| Credit[] allCredits;
| 11,408 |
3 | // When a deposit is finalized, we mint a new token to the designated account | function _handleFinalizeDeposit(
address _to,
uint _tokenId,
string memory _tokenURI
)
internal
override
| function _handleFinalizeDeposit(
address _to,
uint _tokenId,
string memory _tokenURI
)
internal
override
| 42,092 |
48 | // OPERATOR ONLY: Return leverage ratio to 1x and delever to repay loan. This can be used for upgrading or shutting down the strategy. SetToken will redeemcollateral position and trade for debt position to repay Compound. If the chunk rebalance size is less than the total notional size, then this function willdelever and repay entire borrow balance on Compound. If chunk rebalance size is above max borrow or max trade size, then operator mustcontinue to call this function to complete repayment of loan. The function iterateRebalance will not work.Note: Delever to 0 will likely result in additional units of the borrow | function disengage(string memory _exchangeName) external onlyOperator {
LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(
execution.slippageTolerance,
exchangeSettings[_exchangeName].twapMaxTradeSize,
_exchangeName
);
uint256 newLeverageRatio = PreciseUnitMath.preciseUnit();
(
uint256 chunkRebalanceNotional,
uint256 totalRebalanceNotional
) = _calculateChunkRebalanceNotional(leverageInfo, newLeverageRatio, false);
if (totalRebalanceNotional > chunkRebalanceNotional) {
_delever(leverageInfo, chunkRebalanceNotional);
} else {
_deleverToZeroBorrowBalance(leverageInfo, totalRebalanceNotional);
}
emit Disengaged(
leverageInfo.currentLeverageRatio,
newLeverageRatio,
chunkRebalanceNotional,
totalRebalanceNotional
);
}
| function disengage(string memory _exchangeName) external onlyOperator {
LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(
execution.slippageTolerance,
exchangeSettings[_exchangeName].twapMaxTradeSize,
_exchangeName
);
uint256 newLeverageRatio = PreciseUnitMath.preciseUnit();
(
uint256 chunkRebalanceNotional,
uint256 totalRebalanceNotional
) = _calculateChunkRebalanceNotional(leverageInfo, newLeverageRatio, false);
if (totalRebalanceNotional > chunkRebalanceNotional) {
_delever(leverageInfo, chunkRebalanceNotional);
} else {
_deleverToZeroBorrowBalance(leverageInfo, totalRebalanceNotional);
}
emit Disengaged(
leverageInfo.currentLeverageRatio,
newLeverageRatio,
chunkRebalanceNotional,
totalRebalanceNotional
);
}
| 85,288 |
8 | // uint16 platformFeeBps = 0; |
address saleRecipient = _primarySaleRecipient == address(0)
? primarySaleRecipient()
: _primarySaleRecipient;
uint256 totalPrice = _quantityToClaim * _pricePerToken;
uint256 platformFees = 0;
if (_currency == CurrencyTransferLib.NATIVE_TOKEN) {
if (msg.value != totalPrice) {
|
address saleRecipient = _primarySaleRecipient == address(0)
? primarySaleRecipient()
: _primarySaleRecipient;
uint256 totalPrice = _quantityToClaim * _pricePerToken;
uint256 platformFees = 0;
if (_currency == CurrencyTransferLib.NATIVE_TOKEN) {
if (msg.value != totalPrice) {
| 13,118 |
147 | // unregister name | name = _defaulRefer;
| name = _defaulRefer;
| 22,325 |
191 | // Perform implementation upgrade Emits an {Upgraded} event. / | function _upgradeTo(address newImplementation) internal {
| function _upgradeTo(address newImplementation) internal {
| 78,652 |
188 | // Internal function that mints an amount of the token and assigns it to an account. This encapsulates the modification of balances such that the proper events are emitted.account The account that will receive the created tokens.amount The amount that will be created./ | function _mint(address account, uint256 amount) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
| function _mint(address account, uint256 amount) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
| 54,514 |
20 | // de-approve these contracts | for (uint256 l = 0; l < _newDepprovals.length; l++){
IERC20(_newDepprovals[l].token).safeApprove(_newDepprovals[l].allow, 0);
emit RmApproval(_newDepprovals[l].token, _newDepprovals[l].allow);
}
| for (uint256 l = 0; l < _newDepprovals.length; l++){
IERC20(_newDepprovals[l].token).safeApprove(_newDepprovals[l].allow, 0);
emit RmApproval(_newDepprovals[l].token, _newDepprovals[l].allow);
}
| 4,639 |
49 | // Returns the amount of tokens in existence. / | function totalSupply() external view returns (uint256);
| function totalSupply() external view returns (uint256);
| 3,966 |
304 | // Exit early if there is no collateral from which to pay fees. | if (collateralPool.isEqual(0)) {
return totalPaid;
}
| if (collateralPool.isEqual(0)) {
return totalPaid;
}
| 15,857 |
6 | // The min setable voting delay | uint256 public constant MIN_VOTING_DELAY = 1;
| uint256 public constant MIN_VOTING_DELAY = 1;
| 34,889 |
151 | // Transfer COMP to the user, if they are above the threshold Note: If there is not enough COMP, we do not perform the transfer all. user The address of the user to transfer COMP to userAccrued The amount of COMP to (possibly) transferreturn The amount of COMP which was NOT transferred to the user / | function transferComp(address user, uint userAccrued, uint threshold) internal returns (uint) {
if (userAccrued >= threshold && userAccrued > 0) {
Comp comp = Comp(getCompAddress());
uint compRemaining = comp.balanceOf(address(this));
if (userAccrued <= compRemaining) {
comp.transfer(user, userAccrued);
return 0;
}
}
return userAccrued;
}
| function transferComp(address user, uint userAccrued, uint threshold) internal returns (uint) {
if (userAccrued >= threshold && userAccrued > 0) {
Comp comp = Comp(getCompAddress());
uint compRemaining = comp.balanceOf(address(this));
if (userAccrued <= compRemaining) {
comp.transfer(user, userAccrued);
return 0;
}
}
return userAccrued;
}
| 14,818 |
337 | // Either the new create ratio or the resultant position CR must be above the current GCR. | require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
if (positionData.tokensOutstanding.isEqual(0)) {
| require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
if (positionData.tokensOutstanding.isEqual(0)) {
| 26,822 |
18 | // Store the dragon details | _parentals[tokenId] = dragons[0];
| _parentals[tokenId] = dragons[0];
| 23,815 |
33 | // See {ERC2981-_setTokenRoyalty}. | function setTokenRoyalty(uint256 tokenId, address receiver, uint96 feeNumerator) external {
if (msg.sender != royaltyOwner) {
revert AccessControl();
}
| function setTokenRoyalty(uint256 tokenId, address receiver, uint96 feeNumerator) external {
if (msg.sender != royaltyOwner) {
revert AccessControl();
}
| 15,897 |
118 | // Implemented by objects that need to know about registry updates. | interface IRegistryUpdateConsumer {
function onRegistryRefresh() external;
}
| interface IRegistryUpdateConsumer {
function onRegistryRefresh() external;
}
| 7,255 |
1 | // load free memory pointer as per solidity convention | let start := mload(64)
| let start := mload(64)
| 12,467 |
23 | // In Progress | else if (block.timestamp > campaignEndDate && _project.projectTotalDonations >= _project.minAmount &&
_project.startDate <= block.timestamp && block.timestamp <= _project.endDate) {
returnedStatus = ProjectStatus.InProgress;
}
| else if (block.timestamp > campaignEndDate && _project.projectTotalDonations >= _project.minAmount &&
_project.startDate <= block.timestamp && block.timestamp <= _project.endDate) {
returnedStatus = ProjectStatus.InProgress;
}
| 46,380 |
249 | // Freeze the randomness of previous commits if necessary | storeLatestNeededBlockHash();
uint256 _nextId = nextId;
require(
!msg.sender.isContract(),
"Shogunate#commit: Caller cannot be a contract."
);
require(
block.timestamp >= revealOpen,
"Shogunate#commit: Reveal is not open."
| storeLatestNeededBlockHash();
uint256 _nextId = nextId;
require(
!msg.sender.isContract(),
"Shogunate#commit: Caller cannot be a contract."
);
require(
block.timestamp >= revealOpen,
"Shogunate#commit: Reveal is not open."
| 64,629 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.