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 |
|---|---|---|---|---|
243 | // interface | import {IOracle} from "../interfaces/IOracle.sol";
//lib
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
library Power2Base {
using SafeMath for uint256;
uint32 private constant TWAP_PERIOD = 420 seconds;
uint256 private constant INDEX_SCALE = 1e4;
uint256 private constant ONE = 1e18;
uint256 private constant ONE_ONE = 1e36;
/**
* @notice return the scaled down index of the power perp in USD, scaled by 18 decimals
* @param _period period of time for the twap in seconds (cannot be longer than maximum period for the pool)
* @param _oracle oracle address
* @param _ethQuoteCurrencyPool uniswap v3 pool for weth / quoteCurrency
* @param _weth weth address
* @param _quoteCurrency quoteCurrency address
* @return for squeeth, return ethPrice^2
*/
function _getIndex(
uint32 _period,
address _oracle,
address _ethQuoteCurrencyPool,
address _weth,
address _quoteCurrency
) internal view returns (uint256) {
uint256 ethQuoteCurrencyPrice = _getScaledTwap(
_oracle,
_ethQuoteCurrencyPool,
_weth,
_quoteCurrency,
_period,
false
);
return ethQuoteCurrencyPrice.mul(ethQuoteCurrencyPrice).div(ONE);
}
/**
* @notice return the unscaled index of the power perp in USD, scaled by 18 decimals
* @param _period period of time for the twap in seconds (cannot be longer than maximum period for the pool)
* @param _oracle oracle address
* @param _ethQuoteCurrencyPool uniswap v3 pool for weth / quoteCurrency
* @param _weth weth address
* @param _quoteCurrency quoteCurrency address
* @return for squeeth, return ethPrice^2
*/
function _getUnscaledIndex(
uint32 _period,
address _oracle,
address _ethQuoteCurrencyPool,
address _weth,
address _quoteCurrency
) internal view returns (uint256) {
uint256 ethQuoteCurrencyPrice = _getTwap(_oracle, _ethQuoteCurrencyPool, _weth, _quoteCurrency, _period, false);
return ethQuoteCurrencyPrice.mul(ethQuoteCurrencyPrice).div(ONE);
}
/**
* @notice return the mark price of power perp in quoteCurrency, scaled by 18 decimals
* @param _period period of time for the twap in seconds (cannot be longer than maximum period for the pool)
* @param _oracle oracle address
* @param _wSqueethEthPool uniswap v3 pool for wSqueeth / weth
* @param _ethQuoteCurrencyPool uniswap v3 pool for weth / quoteCurrency
* @param _weth weth address
* @param _quoteCurrency quoteCurrency address
* @param _wSqueeth wSqueeth address
* @param _normalizationFactor current normalization factor
* @return for squeeth, return ethPrice * squeethPriceInEth
*/
function _getDenormalizedMark(
uint32 _period,
address _oracle,
address _wSqueethEthPool,
address _ethQuoteCurrencyPool,
address _weth,
address _quoteCurrency,
address _wSqueeth,
uint256 _normalizationFactor
) internal view returns (uint256) {
uint256 ethQuoteCurrencyPrice = _getScaledTwap(
_oracle,
_ethQuoteCurrencyPool,
_weth,
_quoteCurrency,
_period,
false
);
uint256 wsqueethEthPrice = _getTwap(_oracle, _wSqueethEthPool, _wSqueeth, _weth, _period, false);
return wsqueethEthPrice.mul(ethQuoteCurrencyPrice).div(_normalizationFactor);
}
/**
* @notice get the fair collateral value for a _debtAmount of wSqueeth
* @dev the actual amount liquidator can get should have a 10% bonus on top of this value.
* @param _debtAmount wSqueeth amount paid by liquidator
* @param _oracle oracle address
* @param _wSqueethEthPool uniswap v3 pool for wSqueeth / weth
* @param _wSqueeth wSqueeth address
* @param _weth weth address
* @return returns value of debt in ETH
*/
function _getDebtValueInEth(
uint256 _debtAmount,
address _oracle,
address _wSqueethEthPool,
address _wSqueeth,
address _weth
) internal view returns (uint256) {
uint256 wSqueethPrice = _getTwap(_oracle, _wSqueethEthPool, _wSqueeth, _weth, TWAP_PERIOD, false);
return _debtAmount.mul(wSqueethPrice).div(ONE);
}
/**
* @notice request twap from our oracle, scaled down by INDEX_SCALE
* @param _oracle oracle address
* @param _pool uniswap v3 pool address
* @param _base base currency. to get eth/usd price, eth is base token
* @param _quote quote currency. to get eth/usd price, usd is the quote currency
* @param _period number of seconds in the past to start calculating time-weighted average.
* @param _checkPeriod check that period is not longer than maximum period for the pool to prevent reverts
* @return twap price scaled down by INDEX_SCALE
*/
function _getScaledTwap(
address _oracle,
address _pool,
address _base,
address _quote,
uint32 _period,
bool _checkPeriod
) internal view returns (uint256) {
uint256 twap = _getTwap(_oracle, _pool, _base, _quote, _period, _checkPeriod);
return twap.div(INDEX_SCALE);
}
/**
* @notice request twap from our oracle
* @dev this will revert if period is > max period for the pool
* @param _oracle oracle address
* @param _pool uniswap v3 pool address
* @param _base base currency. to get eth/quoteCurrency price, eth is base token
* @param _quote quote currency. to get eth/quoteCurrency price, quoteCurrency is the quote currency
* @param _period number of seconds in the past to start calculating time-weighted average
* @param _checkPeriod check that period is not longer than maximum period for the pool to prevent reverts
* @return human readable price. scaled by 1e18
*/
function _getTwap(
address _oracle,
address _pool,
address _base,
address _quote,
uint32 _period,
bool _checkPeriod
) internal view returns (uint256) {
// period reaching this point should be check, otherwise might revert
return IOracle(_oracle).getTwap(_pool, _base, _quote, _period, _checkPeriod);
}
/**
* @notice get the index value of wsqueeth in wei, used when system settles
* @dev the index of squeeth is ethPrice^2, so each squeeth will need to pay out {ethPrice} eth
* @param _wsqueethAmount amount of wsqueeth used in settlement
* @param _indexPriceForSettlement index price for settlement
* @param _normalizationFactor current normalization factor
* @return amount in wei that should be paid to the token holder
*/
function _getLongSettlementValue(
uint256 _wsqueethAmount,
uint256 _indexPriceForSettlement,
uint256 _normalizationFactor
) internal pure returns (uint256) {
return _wsqueethAmount.mul(_normalizationFactor).mul(_indexPriceForSettlement).div(ONE_ONE);
}
}
| import {IOracle} from "../interfaces/IOracle.sol";
//lib
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
library Power2Base {
using SafeMath for uint256;
uint32 private constant TWAP_PERIOD = 420 seconds;
uint256 private constant INDEX_SCALE = 1e4;
uint256 private constant ONE = 1e18;
uint256 private constant ONE_ONE = 1e36;
/**
* @notice return the scaled down index of the power perp in USD, scaled by 18 decimals
* @param _period period of time for the twap in seconds (cannot be longer than maximum period for the pool)
* @param _oracle oracle address
* @param _ethQuoteCurrencyPool uniswap v3 pool for weth / quoteCurrency
* @param _weth weth address
* @param _quoteCurrency quoteCurrency address
* @return for squeeth, return ethPrice^2
*/
function _getIndex(
uint32 _period,
address _oracle,
address _ethQuoteCurrencyPool,
address _weth,
address _quoteCurrency
) internal view returns (uint256) {
uint256 ethQuoteCurrencyPrice = _getScaledTwap(
_oracle,
_ethQuoteCurrencyPool,
_weth,
_quoteCurrency,
_period,
false
);
return ethQuoteCurrencyPrice.mul(ethQuoteCurrencyPrice).div(ONE);
}
/**
* @notice return the unscaled index of the power perp in USD, scaled by 18 decimals
* @param _period period of time for the twap in seconds (cannot be longer than maximum period for the pool)
* @param _oracle oracle address
* @param _ethQuoteCurrencyPool uniswap v3 pool for weth / quoteCurrency
* @param _weth weth address
* @param _quoteCurrency quoteCurrency address
* @return for squeeth, return ethPrice^2
*/
function _getUnscaledIndex(
uint32 _period,
address _oracle,
address _ethQuoteCurrencyPool,
address _weth,
address _quoteCurrency
) internal view returns (uint256) {
uint256 ethQuoteCurrencyPrice = _getTwap(_oracle, _ethQuoteCurrencyPool, _weth, _quoteCurrency, _period, false);
return ethQuoteCurrencyPrice.mul(ethQuoteCurrencyPrice).div(ONE);
}
/**
* @notice return the mark price of power perp in quoteCurrency, scaled by 18 decimals
* @param _period period of time for the twap in seconds (cannot be longer than maximum period for the pool)
* @param _oracle oracle address
* @param _wSqueethEthPool uniswap v3 pool for wSqueeth / weth
* @param _ethQuoteCurrencyPool uniswap v3 pool for weth / quoteCurrency
* @param _weth weth address
* @param _quoteCurrency quoteCurrency address
* @param _wSqueeth wSqueeth address
* @param _normalizationFactor current normalization factor
* @return for squeeth, return ethPrice * squeethPriceInEth
*/
function _getDenormalizedMark(
uint32 _period,
address _oracle,
address _wSqueethEthPool,
address _ethQuoteCurrencyPool,
address _weth,
address _quoteCurrency,
address _wSqueeth,
uint256 _normalizationFactor
) internal view returns (uint256) {
uint256 ethQuoteCurrencyPrice = _getScaledTwap(
_oracle,
_ethQuoteCurrencyPool,
_weth,
_quoteCurrency,
_period,
false
);
uint256 wsqueethEthPrice = _getTwap(_oracle, _wSqueethEthPool, _wSqueeth, _weth, _period, false);
return wsqueethEthPrice.mul(ethQuoteCurrencyPrice).div(_normalizationFactor);
}
/**
* @notice get the fair collateral value for a _debtAmount of wSqueeth
* @dev the actual amount liquidator can get should have a 10% bonus on top of this value.
* @param _debtAmount wSqueeth amount paid by liquidator
* @param _oracle oracle address
* @param _wSqueethEthPool uniswap v3 pool for wSqueeth / weth
* @param _wSqueeth wSqueeth address
* @param _weth weth address
* @return returns value of debt in ETH
*/
function _getDebtValueInEth(
uint256 _debtAmount,
address _oracle,
address _wSqueethEthPool,
address _wSqueeth,
address _weth
) internal view returns (uint256) {
uint256 wSqueethPrice = _getTwap(_oracle, _wSqueethEthPool, _wSqueeth, _weth, TWAP_PERIOD, false);
return _debtAmount.mul(wSqueethPrice).div(ONE);
}
/**
* @notice request twap from our oracle, scaled down by INDEX_SCALE
* @param _oracle oracle address
* @param _pool uniswap v3 pool address
* @param _base base currency. to get eth/usd price, eth is base token
* @param _quote quote currency. to get eth/usd price, usd is the quote currency
* @param _period number of seconds in the past to start calculating time-weighted average.
* @param _checkPeriod check that period is not longer than maximum period for the pool to prevent reverts
* @return twap price scaled down by INDEX_SCALE
*/
function _getScaledTwap(
address _oracle,
address _pool,
address _base,
address _quote,
uint32 _period,
bool _checkPeriod
) internal view returns (uint256) {
uint256 twap = _getTwap(_oracle, _pool, _base, _quote, _period, _checkPeriod);
return twap.div(INDEX_SCALE);
}
/**
* @notice request twap from our oracle
* @dev this will revert if period is > max period for the pool
* @param _oracle oracle address
* @param _pool uniswap v3 pool address
* @param _base base currency. to get eth/quoteCurrency price, eth is base token
* @param _quote quote currency. to get eth/quoteCurrency price, quoteCurrency is the quote currency
* @param _period number of seconds in the past to start calculating time-weighted average
* @param _checkPeriod check that period is not longer than maximum period for the pool to prevent reverts
* @return human readable price. scaled by 1e18
*/
function _getTwap(
address _oracle,
address _pool,
address _base,
address _quote,
uint32 _period,
bool _checkPeriod
) internal view returns (uint256) {
// period reaching this point should be check, otherwise might revert
return IOracle(_oracle).getTwap(_pool, _base, _quote, _period, _checkPeriod);
}
/**
* @notice get the index value of wsqueeth in wei, used when system settles
* @dev the index of squeeth is ethPrice^2, so each squeeth will need to pay out {ethPrice} eth
* @param _wsqueethAmount amount of wsqueeth used in settlement
* @param _indexPriceForSettlement index price for settlement
* @param _normalizationFactor current normalization factor
* @return amount in wei that should be paid to the token holder
*/
function _getLongSettlementValue(
uint256 _wsqueethAmount,
uint256 _indexPriceForSettlement,
uint256 _normalizationFactor
) internal pure returns (uint256) {
return _wsqueethAmount.mul(_normalizationFactor).mul(_indexPriceForSettlement).div(ONE_ONE);
}
}
| 3,857 |
18 | // Pass the kitty to the ZombieFeeding machine | function feedOnKitty(uint _zombieId, uint _kittyId) public {
// Get the value of the Kitty's DNA
uint kittyDna;
(,,,,,,,,,kittyDna) = kittyContract.getKitty(_kittyId);
// Parse that info to the function including the keyword "kitty"
feedAndMultiply(_zombieId, kittyDna, "kitty");
}
| function feedOnKitty(uint _zombieId, uint _kittyId) public {
// Get the value of the Kitty's DNA
uint kittyDna;
(,,,,,,,,,kittyDna) = kittyContract.getKitty(_kittyId);
// Parse that info to the function including the keyword "kitty"
feedAndMultiply(_zombieId, kittyDna, "kitty");
}
| 15,501 |
314 | // If the start round is greater than the end round, we've already claimed for the end round so we do not need to execute the LIP-36 earnings claiming algorithm. This could be the case if: - _endRound < lip36Round i.e. we are not claiming through the lip36Round - _endRound == lip36Round AND startRound = lip36Round + 1 i.e we already claimed through the lip36Round | if (startRound > _endRound) {
return (stake, fees);
}
| if (startRound > _endRound) {
return (stake, fees);
}
| 43,546 |
310 | // Allows anyone to transfer all given tokens in a Loot Box to the associated ERC721 owner./A Loot Box contract will be counterfactually created, tokens transferred to the ERC721 owner, then destroyed./erc721 The address of the ERC721/tokenId The ERC721 token id/erc20s An array of ERC20 tokens whose entire balance should be transferred/erc721s An array of structs defining ERC721 tokens that should be transferred/erc1155s An array of struct defining ERC1155 tokens that should be transferred | function plunder(
address erc721,
uint256 tokenId,
IERC20Upgradeable[] calldata erc20s,
LootBox.WithdrawERC721[] calldata erc721s,
LootBox.WithdrawERC1155[] calldata erc1155s
| function plunder(
address erc721,
uint256 tokenId,
IERC20Upgradeable[] calldata erc20s,
LootBox.WithdrawERC721[] calldata erc721s,
LootBox.WithdrawERC1155[] calldata erc1155s
| 82,654 |
2 | // _pools | mapping(address => Pool) private _pools;
| mapping(address => Pool) private _pools;
| 25,099 |
26 | // Company will take a cut of 2% when an order is claimed. | uint constant ORDER_CUT = 2;
| uint constant ORDER_CUT = 2;
| 42,983 |
10 | // This require is handled by generateMessageToSign() require(destination != address(this)); | require(address(this).balance >= value, "3");
require(
_validSignature(
destination,
value,
v1, r1, s1,
v2, r2, s2
),
"4");
spendNonce = spendNonce + 1;
| require(address(this).balance >= value, "3");
require(
_validSignature(
destination,
value,
v1, r1, s1,
v2, r2, s2
),
"4");
spendNonce = spendNonce + 1;
| 11,794 |
109 | // ======== STATE VARIABLES ======== /IConvexRewards public rewardPool;Convex reward contract | IAnyswapRouter public immutable anyswapRouter; // anyswap router
ICurve3Pool public curve3Pool; // Curve 3Pool
address public rewardCollector;
mapping(address => tokenData) public tokenInfo; // info for deposited tokens
| IAnyswapRouter public immutable anyswapRouter; // anyswap router
ICurve3Pool public curve3Pool; // Curve 3Pool
address public rewardCollector;
mapping(address => tokenData) public tokenInfo; // info for deposited tokens
| 48,890 |
34 | // bubble up the error | revert(string(error));
| revert(string(error));
| 58,740 |
63 | // 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);
}
| 8,076 |
60 | // Check that current validators, powers, and signatures (v,r,s) set is well-formed | require(
_currentValset.validators.length == _currentValset.powers.length &&
_currentValset.validators.length == _v.length &&
_currentValset.validators.length == _r.length &&
_currentValset.validators.length == _s.length,
"Malformed current validator set"
);
| require(
_currentValset.validators.length == _currentValset.powers.length &&
_currentValset.validators.length == _v.length &&
_currentValset.validators.length == _r.length &&
_currentValset.validators.length == _s.length,
"Malformed current validator set"
);
| 2,676 |
4 | // According to EIP-1052, 0x0 is the value returned for not-yet created accounts and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned for accounts without code, i.e. `keccak256('')` | bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
| bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
| 23 |
16 | // Returns the credit rate of a controlled token/controlledToken The controlled token to retrieve the credit rates for/ return creditLimitMantissa The credit limit fraction.This number is used to calculate both the credit limit and early exit fee./ return creditRateMantissa The credit rate. This is the amount of tokens that accrue per second. | function creditPlanOf(
address controlledToken
)
external
view
returns (
uint128 creditLimitMantissa,
uint128 creditRateMantissa
);
| function creditPlanOf(
address controlledToken
)
external
view
returns (
uint128 creditLimitMantissa,
uint128 creditRateMantissa
);
| 7,730 |
23 | // Modifier to allow calls only after the option start block. Ensures that certain functions can only be called after the option has started. / | modifier onlyStart() {
require(block.number >= startBlock, "Option: only after start block");
_;
}
| modifier onlyStart() {
require(block.number >= startBlock, "Option: only after start block");
_;
}
| 25,613 |
8 | // Get the current allowance from `owner` for `spender` owner The address of the account which owns the tokens to be spent spender The address of the account which may transfer tokensreturn The number of tokens allowed to be spent / | function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
| function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
| 45,634 |
44 | // Uses `StakeManager` to decide if the Relay Manager can be considered staked or not.Returns if the stake's token, amount and delay satisfy all requirements, reverts otherwise. / | function verifyRelayManagerStaked(address relayManager) external view;
| function verifyRelayManagerStaked(address relayManager) external view;
| 23,760 |
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 amount of tokens to be transferred/ | function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
| function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
| 21,576 |
16 | // Claim bones from BoneLockers Since it could be a lot of pending rewards items parameters are used limit tx size _boneLocker BoneLocker to claim, pass zero address to claim from current _maxBoneLockerRewardsAtOneClaim max amount of rewards items to claim from BoneLocker, pass 0 to claim all rewards / | function claimRewardFromBoneLocker(IBoneLocker _boneLocker, uint256 _maxBoneLockerRewardsAtOneClaim) public nonReentrant {
WSSLPUserProxy userProxy = _requireUserProxy(msg.sender);
userProxy.claimRewardFromBoneLocker(msg.sender, _boneLocker, _maxBoneLockerRewardsAtOneClaim, feeReceiver, feePercent);
}
| function claimRewardFromBoneLocker(IBoneLocker _boneLocker, uint256 _maxBoneLockerRewardsAtOneClaim) public nonReentrant {
WSSLPUserProxy userProxy = _requireUserProxy(msg.sender);
userProxy.claimRewardFromBoneLocker(msg.sender, _boneLocker, _maxBoneLockerRewardsAtOneClaim, feeReceiver, feePercent);
}
| 52,288 |
17 | // ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------ | constructor() public {
owner = msg.sender;
balances[owner] = totalSupply();
emit Transfer(address(0), owner, totalSupply());
}
| constructor() public {
owner = msg.sender;
balances[owner] = totalSupply();
emit Transfer(address(0), owner, totalSupply());
}
| 6,084 |
41 | // If the latest observation occurred in the past, then no tick-changing trades have happened in this block therefore the tick in `slot0` is the same as at the beginning of the current block. We don't need to check if this observation is initialized - it is guaranteed to be. | (uint32 observationTimestamp, int56 tickCumulative, , ) = IUniswapV3Pool(pool).observations(observationIndex);
if (observationTimestamp != uint32(block.timestamp)) {
return tick;
}
| (uint32 observationTimestamp, int56 tickCumulative, , ) = IUniswapV3Pool(pool).observations(observationIndex);
if (observationTimestamp != uint32(block.timestamp)) {
return tick;
}
| 18,175 |
4 | // general public | require(msg.value >= cost * _mintAmount);
| require(msg.value >= cost * _mintAmount);
| 20,050 |
2 | // Tokens balance | tokensBalances = new TokenBalance[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
tokensBalances[i] = TokenBalance(
_tokens[i].balanceOf(_user),
_tokens[i].allowance(_user, _tokenSpender)
);
}
| tokensBalances = new TokenBalance[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
tokensBalances[i] = TokenBalance(
_tokens[i].balanceOf(_user),
_tokens[i].allowance(_user, _tokenSpender)
);
}
| 35,787 |
29 | // Perform basic checks | Config memory _config = DFPconfig;
require(_config.unlocked, "DFP: Locked");
require(tokens.length == 16, "DFP: Bad tokens array length");
require(maxAmounts.length == 16, "DFP: Bad maxAmount array length");
| Config memory _config = DFPconfig;
require(_config.unlocked, "DFP: Locked");
require(tokens.length == 16, "DFP: Bad tokens array length");
require(maxAmounts.length == 16, "DFP: Bad maxAmount array length");
| 22,569 |
130 | // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. | require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
| require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
| 62,918 |
24 | // Return the current wallet instance that will serve as the execution/context for transformations./ return wallet The wallet instance. | function getTransformWallet()
public
override
view
returns (IFlashWallet wallet)
| function getTransformWallet()
public
override
view
returns (IFlashWallet wallet)
| 20,774 |
12 | // Send the caller (`msg.sender`) all ether they own. | function withdrawFunds() {
externalEnter();
withdrawFundsRP();
externalLeave();
}
| function withdrawFunds() {
externalEnter();
withdrawFundsRP();
externalLeave();
}
| 42,332 |
104 | // If this is a fast liquidity path, we should handle deducting from applicable routers' liquidity. If this is a slow liquidity path, the transfer must have been reconciled (if we've reached this point), and the funds would have been custodied in this contract. The exact custodied amount is untracked in state (since the amount is hashed in the transfer ID itself) - thus, no updates are required. | if (_isFast) {
uint256 pathLen = _args.routers.length;
| if (_isFast) {
uint256 pathLen = _args.routers.length;
| 14,073 |
14 | // Record account | accountCount.push(PeronDatas[1]);
| accountCount.push(PeronDatas[1]);
| 13,574 |
10 | // After asset are deposited in the vault, we stake it in theunderlying staked asset and mint new vault tokens. / | function deposit(uint256 _amount, address _receiver)
public
virtual
whenNotPaused
nonReentrant
| function deposit(uint256 _amount, address _receiver)
public
virtual
whenNotPaused
nonReentrant
| 25,059 |
110 | // Make sure the content exist | require (contentIndex[_contentId] > 0);
Content memory _content = contents[contentIndex[_contentId]];
return (
_content.creator,
_content.fileSize,
_content.contentUsageType,
_content.taoId,
_content.taoContentState,
_content.updateTAOContentStateV,
_content.updateTAOContentStateR,
| require (contentIndex[_contentId] > 0);
Content memory _content = contents[contentIndex[_contentId]];
return (
_content.creator,
_content.fileSize,
_content.contentUsageType,
_content.taoId,
_content.taoContentState,
_content.updateTAOContentStateV,
_content.updateTAOContentStateR,
| 16,511 |
258 | // price = supplymultiplier | return dvdTotalSupply().roundedDiv(DIVIDER);
| return dvdTotalSupply().roundedDiv(DIVIDER);
| 44,815 |
310 | // Prevent resetting the logic name for standalone test deployments. | require(logicName() == "", "LOGIC_NAME_ALREADY_SET");
require(
_getSettings().versionsRegistry().hasLogicVersion(aLogicName),
"LOGIC_NAME_NOT_EXIST"
);
bytes32 slot = LOGIC_NAME_SLOT;
assembly {
sstore(slot, aLogicName)
}
| require(logicName() == "", "LOGIC_NAME_ALREADY_SET");
require(
_getSettings().versionsRegistry().hasLogicVersion(aLogicName),
"LOGIC_NAME_NOT_EXIST"
);
bytes32 slot = LOGIC_NAME_SLOT;
assembly {
sstore(slot, aLogicName)
}
| 11,607 |
10 | // padding with '=' | switch mod(mload(data), 3)
| switch mod(mload(data), 3)
| 27,792 |
4 | // Constructor | constructor () public {
addCandidate("Candidate 1");
addCandidate("Candidate 2");
}
| constructor () public {
addCandidate("Candidate 1");
addCandidate("Candidate 2");
}
| 15,920 |
29 | // Calculate the unclaimed prize amount for the given tokenID and prizeTier | _prizeUSDC = prizeAmount - tokenIdToPrizeTierToClaimedUSDC[tokenID][prizeTier];
if(_prizeUSDC > 0){
| _prizeUSDC = prizeAmount - tokenIdToPrizeTierToClaimedUSDC[tokenID][prizeTier];
if(_prizeUSDC > 0){
| 22,711 |
225 | // 5. Work out the total amount owing on the loan. | uint total = loan.amount.add(loan.accruedInterest);
| uint total = loan.amount.add(loan.accruedInterest);
| 29,986 |
109 | // Invalid fixed code | return ErrorCode.ERR_INVALID_LENGTH_OR_DISTANCE_CODE;
| return ErrorCode.ERR_INVALID_LENGTH_OR_DISTANCE_CODE;
| 27,774 |
9 | // For accounts that are not whales and are buying less than or equal to their current balance, keep blocksPerPeriod unchanged | else if (!_isWhale[account] && amount <= balanceOf(account)) {
_locked[account].blocksPerPeriod = _locked[account].blocksPerPeriod;
}
| else if (!_isWhale[account] && amount <= balanceOf(account)) {
_locked[account].blocksPerPeriod = _locked[account].blocksPerPeriod;
}
| 19,504 |
5 | // Keeps track if user has reacted / | mapping(uint => mapping(address => bool)) public memberHasReacted;
| mapping(uint => mapping(address => bool)) public memberHasReacted;
| 18,445 |
19 | // GET THE PRICE AFTER DISCOUNT REFERAL CODE BENEFIT / | function actualPrice(uint channel_id) public view returns(uint _actualPrice){
uint price = channels[channel_id].subscription_price;
_actualPrice = price.sub(Helper.calcRefBenefit(price, refPrice));
}
| function actualPrice(uint channel_id) public view returns(uint _actualPrice){
uint price = channels[channel_id].subscription_price;
_actualPrice = price.sub(Helper.calcRefBenefit(price, refPrice));
}
| 35,980 |
129 | // The first epoch must be called by the owner of the contract | require(msg.sender == owner, "not authorized (first epochs)");
| require(msg.sender == owner, "not authorized (first epochs)");
| 4,567 |
54 | // Events/ Event for token purchase logging | event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 tokens);
| event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 tokens);
| 51,799 |
45 | // Transfer tokens from one address to another. from The address which you want to transfer tokens from. to The address which you want to transfer to. value The amount of tokens to be transferred.return A boolean that indicates if the operation was successful. / | function transferFrom(address from, address to, uint256 value) external override returns (bool) {
require( _isOperator(msg.sender, from)
|| (value <= _allowed[from][msg.sender]), "53"); // 0x53 insufficient allowance
if(_allowed[from][msg.sender] >= value) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
} else {
_allowed[from][msg.sender] = 0;
}
_transferByDefaultPartitions(msg.sender, from, to, value, "");
return true;
}
| function transferFrom(address from, address to, uint256 value) external override returns (bool) {
require( _isOperator(msg.sender, from)
|| (value <= _allowed[from][msg.sender]), "53"); // 0x53 insufficient allowance
if(_allowed[from][msg.sender] >= value) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
} else {
_allowed[from][msg.sender] = 0;
}
_transferByDefaultPartitions(msg.sender, from, to, value, "");
return true;
}
| 37,089 |
28 | // Register a future flight for insuring./ | function registerFlight(address airlineAddress,
string memory flight,
uint256 timestamp
)
public
requireIsOperational
returns (string memory)
| function registerFlight(address airlineAddress,
string memory flight,
uint256 timestamp
)
public
requireIsOperational
returns (string memory)
| 17,477 |
21 | // Internal function to perform rebalance/etf The etf expected to rebalance/bPool The underlying pool of the etf/rebalanceInfo Key information to perform rebalance/token1Received The amount received after exchange by a swap router | function _rebalance(
IETF etf,
IBpool bPool,
IRebalanceAdapter.RebalanceInfo calldata rebalanceInfo,
uint256 token1Received
| function _rebalance(
IETF etf,
IBpool bPool,
IRebalanceAdapter.RebalanceInfo calldata rebalanceInfo,
uint256 token1Received
| 23,304 |
34 | // Increase social loss per contract on given side.side Side of position. loss Amount of loss to handle. / | function handleSocialLoss(LibTypes.Side side, int256 loss) internal {
require(side != LibTypes.Side.FLAT, "side can't be flat");
require(totalSize(side) > 0, "size cannot be 0");
require(loss >= 0, "loss must be positive");
int256 newSocialLoss = loss.wdiv(totalSize(side).toInt256());
int256 newLossPerContract = socialLossPerContracts[uint256(side)].add(newSocialLoss);
socialLossPerContracts[uint256(side)] = newLossPerContract;
emit SocialLoss(side, newLossPerContract);
}
| function handleSocialLoss(LibTypes.Side side, int256 loss) internal {
require(side != LibTypes.Side.FLAT, "side can't be flat");
require(totalSize(side) > 0, "size cannot be 0");
require(loss >= 0, "loss must be positive");
int256 newSocialLoss = loss.wdiv(totalSize(side).toInt256());
int256 newLossPerContract = socialLossPerContracts[uint256(side)].add(newSocialLoss);
socialLossPerContracts[uint256(side)] = newLossPerContract;
emit SocialLoss(side, newLossPerContract);
}
| 29,434 |
13 | // not a contract swap |
if (automatedMarketMakerPairs[from]) {
|
if (automatedMarketMakerPairs[from]) {
| 8,170 |
40 | // check if next j iteration takes us below zero | if ( rule.step > j ) {
break;
}
| if ( rule.step > j ) {
break;
}
| 34,061 |
7 | // thrown when function called by non-protocol owner / | error SimpleVault__NotProtocolOwner();
| error SimpleVault__NotProtocolOwner();
| 37,261 |
4 | // emitted when a expired call option is burned | event ExpiredCallBurned(uint256 optionId);
| event ExpiredCallBurned(uint256 optionId);
| 39,611 |
25 | // Return WETH Address. / | function getAddressWETH() internal pure returns (address) {
return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
}
| function getAddressWETH() internal pure returns (address) {
return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
}
| 11,721 |
116 | // Allocation constants | uint constant ADVISORY_SHARE = 18500000*(10**9); //FIXED
uint constant BOUNTY_SHARE = 3700000*(10**9); // FIXED
uint constant COMMUNITY_SHARE = 37000000*(10**9); //FIXED
uint constant COMPANY_SHARE = 33300000*(10**9); //FIXED
uint constant PRESALE_SHARE = 7856217611546440; // FIXED;
| uint constant ADVISORY_SHARE = 18500000*(10**9); //FIXED
uint constant BOUNTY_SHARE = 3700000*(10**9); // FIXED
uint constant COMMUNITY_SHARE = 37000000*(10**9); //FIXED
uint constant COMPANY_SHARE = 33300000*(10**9); //FIXED
uint constant PRESALE_SHARE = 7856217611546440; // FIXED;
| 30,096 |
62 | // Returns the address of the current developer. / developer() => 0xca4b208b | function developer() public view virtual returns (address) {
return _developer;
}
| function developer() public view virtual returns (address) {
return _developer;
}
| 14,454 |
0 | // Model a Item | struct Item {
uint id;
string item_name;
uint quantityInitial;
uint quantitySold;
uint quantityInStock;
}
| struct Item {
uint id;
string item_name;
uint quantityInitial;
uint quantitySold;
uint quantityInStock;
}
| 12,573 |
55 | // ,-.`-'/|\ |,-----------------------./ \ |ZoraProtocolFeeSettings|ModuleOwner `-----------+-----------' |setFeeParams()| |--------------------------->| || |----. || set fee parameters |<---' || |----. || emit ProtocolFeeUpdated() |<---'ModuleOwner ,-----------+-----------.,-. |ZoraProtocolFeeSettings|`-' `-----------------------'/|\ |/ \/Sets fee parameters for ZORA protocol./_module The module to apply the fee settings to/_feeRecipient The fee recipient address to send fees to/_feeBps The bps of transaction value to send to the fee recipient | function setFeeParams(
address _module,
address _feeRecipient,
uint16 _feeBps
| function setFeeParams(
address _module,
address _feeRecipient,
uint16 _feeBps
| 57,051 |
19 | // ------------------------------------------------------------------------ Transfer the balance from token owner's account to `to` account - Owner's account must have sufficient balance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------ | function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(msg.sender, to, tokens);
return true;
}
| function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(msg.sender, to, tokens);
return true;
}
| 2,793 |
24 | // Emits a {Transfer} event with `to` set to the zero address. Requirements - `account` cannot be the zero address.- `account` must have at least `amount` tokens. / | function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
| function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
| 11,167 |
32 | // CRV SWAP HERE from steth -> eth 0 = ETH, 1 = STETH We are setting 1, which is the smallest possible value for the _minAmountOut parameter However it is fine because we check that the totalETHOut >= minETHOut at the end which makes sandwich attacks not possible | uint256 ethAmountOutFromSwap =
ICRV(crvPool).exchange(1, 0, stEthAmount, 1);
return ethAmountOutFromSwap;
| uint256 ethAmountOutFromSwap =
ICRV(crvPool).exchange(1, 0, stEthAmount, 1);
return ethAmountOutFromSwap;
| 48,082 |
128 | // Deposit `_value` additional tokens for `_tokenId` without modifying the unlock time/_value Amount of tokens to deposit and add to the lock | function increase_amount(uint _tokenId, uint _value) external nonreentrant {
assert(_isApprovedOrOwner(msg.sender, _tokenId));
LockedBalance memory _locked = locked[_tokenId];
assert(_value > 0); // dev: need non-zero value
require(_locked.amount > 0, 'No existing lock found');
require(_locked.end > block.timestamp, 'Cannot add to expired lock. Withdraw');
_deposit_for(_tokenId, _value, 0, _locked, DepositType.INCREASE_LOCK_AMOUNT);
}
| function increase_amount(uint _tokenId, uint _value) external nonreentrant {
assert(_isApprovedOrOwner(msg.sender, _tokenId));
LockedBalance memory _locked = locked[_tokenId];
assert(_value > 0); // dev: need non-zero value
require(_locked.amount > 0, 'No existing lock found');
require(_locked.end > block.timestamp, 'Cannot add to expired lock. Withdraw');
_deposit_for(_tokenId, _value, 0, _locked, DepositType.INCREASE_LOCK_AMOUNT);
}
| 12,696 |
31 | // Mapping from user to number of tokens. | mapping(address => uint256) public totalBalance;
| mapping(address => uint256) public totalBalance;
| 50,549 |
153 | // called from 'executeProposal' changing admin key by backup's proposal requires 30 days delay | function changeAdminKeyByBackup(address payable _account, address _pkNew) external allowSelfCallsOnly {
require(_pkNew != address(0), "0x0 is invalid");
address pk = accountStorage.getKeyData(_account, 0);
require(pk != _pkNew, "identical admin key exists");
require(accountStorage.getDelayDataHash(_account, CHANGE_ADMIN_KEY_BY_BACKUP) == 0, "delay data already exists");
bytes32 hash = keccak256(abi.encodePacked('changeAdminKeyByBackup', _account, _pkNew));
accountStorage.setDelayData(_account, CHANGE_ADMIN_KEY_BY_BACKUP, hash, now + DELAY_CHANGE_ADMIN_KEY_BY_BACKUP);
emit ChangeAdminKeyByBackup(_account, _pkNew);
}
| function changeAdminKeyByBackup(address payable _account, address _pkNew) external allowSelfCallsOnly {
require(_pkNew != address(0), "0x0 is invalid");
address pk = accountStorage.getKeyData(_account, 0);
require(pk != _pkNew, "identical admin key exists");
require(accountStorage.getDelayDataHash(_account, CHANGE_ADMIN_KEY_BY_BACKUP) == 0, "delay data already exists");
bytes32 hash = keccak256(abi.encodePacked('changeAdminKeyByBackup', _account, _pkNew));
accountStorage.setDelayData(_account, CHANGE_ADMIN_KEY_BY_BACKUP, hash, now + DELAY_CHANGE_ADMIN_KEY_BY_BACKUP);
emit ChangeAdminKeyByBackup(_account, _pkNew);
}
| 37,498 |
51 | // Adds _credits to a wallet's credit balance in walletRewards | function addCredits(address _wallet, uint256 _credits) external {
require(isAdmin(address(msg.sender)), "Sender does not have admin rights!");
walletRewards[_wallet] = walletRewards[_wallet].add(_credits);
}
| function addCredits(address _wallet, uint256 _credits) external {
require(isAdmin(address(msg.sender)), "Sender does not have admin rights!");
walletRewards[_wallet] = walletRewards[_wallet].add(_credits);
}
| 28,880 |
6 | // Return pollsreturn polls / | function getPoll() view external returns(Poll[] memory){
return polls;
}
| function getPoll() view external returns(Poll[] memory){
return polls;
}
| 16,530 |
32 | // overflow and undeflow checked by SafeMath Library | _balanceOf[_from] = _balanceOf[_from].sub(_value); // Subtract from the sender
_balanceOf[_to] = _balanceOf[_to].add(_value); // Add the same to the recipient
| _balanceOf[_from] = _balanceOf[_from].sub(_value); // Subtract from the sender
_balanceOf[_to] = _balanceOf[_to].add(_value); // Add the same to the recipient
| 23,003 |
151 | // 获取将要更新后的原生代币的余额(预判) | function getCashAfter(address underlying, uint256 transferInAmount)
external
view
returns (uint256)
| function getCashAfter(address underlying, uint256 transferInAmount)
external
view
returns (uint256)
| 31,167 |
27 | // Deposit original tokens, receive proxy tokens 1:1This method requires token approval.amount of tokens to deposit / | function mutateTokens(address from, uint amount) public returns (bool)
| function mutateTokens(address from, uint amount) public returns (bool)
| 43,176 |
62 | // Assets You Are In //PIGGY-MODIFY: Add assets to be included in account liquidity calculation pTokens The list of addresses of the cToken markets to be enabledreturn Success indicator for whether each corresponding market was entered / | function enterMarkets(address[] calldata pTokens) external returns (uint[] memory);
| function enterMarkets(address[] calldata pTokens) external returns (uint[] memory);
| 5,070 |
94 | // Clear accessory eligible list / | function clearEligibleList (uint256 accessoryId)
public
onlyAccessoryManager(accessoryId)
| function clearEligibleList (uint256 accessoryId)
public
onlyAccessoryManager(accessoryId)
| 41,024 |
54 | // Fail if redeem not allowed // Verify market's block number equals current block number //We calculate the new total supply and redeemer balance, checking for underflow: totalSupplyNew = totalSupply - redeemTokens accountTokensNew = accountTokens[redeemer] - redeemTokens / | (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
| (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
| 13,753 |
1 | // setPublicChainlinkToken();no need to use Pointer here, just set the token address with setChainlinkToken | setChainlinkToken(_linkToken);
oracle = _oracle;
jobId = _jobId;
fee = 1 * 10 ** 18; // 1 LINK
| setChainlinkToken(_linkToken);
oracle = _oracle;
jobId = _jobId;
fee = 1 * 10 ** 18; // 1 LINK
| 48,453 |
40 | // This contract will hold all tokens that were unsold during ICO. Goldmint Team should be able to withdraw them and sell only after 1 year is passed afterICO is finished. | contract GoldmintUnsold is SafeMath {
address public creator;
address public teamAccountAddress;
address public icoContractAddress;
uint64 public icoIsFinishedDate;
MNTP public mntToken;
function GoldmintUnsold(address _teamAccountAddress,address _mntTokenAddress){
creator = msg.sender;
teamAccountAddress = _teamAccountAddress;
mntToken = MNTP(_mntTokenAddress);
}
modifier onlyCreator() {
require(msg.sender==creator);
_;
}
modifier onlyIcoContract() {
require(msg.sender==icoContractAddress);
_;
}
// Setters/Getters
function setIcoContractAddress(address _icoContractAddress) onlyCreator {
icoContractAddress = _icoContractAddress;
}
function finishIco() public onlyIcoContract {
icoIsFinishedDate = uint64(now);
}
// can be called by anyone...
function withdrawTokens() public {
// Check if 1 year is passed
uint64 oneYearPassed = icoIsFinishedDate + 365 days;
require(uint(now) >= oneYearPassed);
// Transfer all tokens from this contract to the teamAccountAddress
uint total = mntToken.balanceOf(this);
mntToken.transfer(teamAccountAddress,total);
}
// Do not allow to send money directly to this contract
function() payable {
revert();
}
}
| contract GoldmintUnsold is SafeMath {
address public creator;
address public teamAccountAddress;
address public icoContractAddress;
uint64 public icoIsFinishedDate;
MNTP public mntToken;
function GoldmintUnsold(address _teamAccountAddress,address _mntTokenAddress){
creator = msg.sender;
teamAccountAddress = _teamAccountAddress;
mntToken = MNTP(_mntTokenAddress);
}
modifier onlyCreator() {
require(msg.sender==creator);
_;
}
modifier onlyIcoContract() {
require(msg.sender==icoContractAddress);
_;
}
// Setters/Getters
function setIcoContractAddress(address _icoContractAddress) onlyCreator {
icoContractAddress = _icoContractAddress;
}
function finishIco() public onlyIcoContract {
icoIsFinishedDate = uint64(now);
}
// can be called by anyone...
function withdrawTokens() public {
// Check if 1 year is passed
uint64 oneYearPassed = icoIsFinishedDate + 365 days;
require(uint(now) >= oneYearPassed);
// Transfer all tokens from this contract to the teamAccountAddress
uint total = mntToken.balanceOf(this);
mntToken.transfer(teamAccountAddress,total);
}
// Do not allow to send money directly to this contract
function() payable {
revert();
}
}
| 35,163 |
0 | // Adding only the ERC-20 function we need | interface DaiToken {
function transfer(address dst, uint wad) external returns (bool);
function balanceOf(address guy) external view returns (uint);
function transferFrom(address src, address dst, uint wad) external returns (bool);
function approve(address usr, uint wad) external returns (bool);
}
| interface DaiToken {
function transfer(address dst, uint wad) external returns (bool);
function balanceOf(address guy) external view returns (uint);
function transferFrom(address src, address dst, uint wad) external returns (bool);
function approve(address usr, uint wad) external returns (bool);
}
| 36,706 |
57 | // Maps underlying addresses to guardian role. / | mapping(address => bool) public isGuardian;
| mapping(address => bool) public isGuardian;
| 23,965 |
20 | // gets category action details/ | function categoryAction(uint _categoryId)
| function categoryAction(uint _categoryId)
| 49,744 |
2 | // Rewards accumulated per unit of time. | uint256 public rewardsPerUnitTime;
| uint256 public rewardsPerUnitTime;
| 13,112 |
51 | // uint maxTokens = (token.balanceOf(this) + withdrawnTokens)(now - startDate) / disbursementPeriod; | if (withdrawnTokens >= maxTokens || startDate > now)
return 0;
if (SafeMath.sub(maxTokens, withdrawnTokens) > token.totalSupply())
return token.totalSupply();
return SafeMath.sub(maxTokens, withdrawnTokens);
| if (withdrawnTokens >= maxTokens || startDate > now)
return 0;
if (SafeMath.sub(maxTokens, withdrawnTokens) > token.totalSupply())
return token.totalSupply();
return SafeMath.sub(maxTokens, withdrawnTokens);
| 39,787 |
13 | // Deposit ETH to specific account with time-lock./account The owner of deposited tokens./releaseTime Timestamp to release the fund./ return True if it is successful, revert otherwise. | function depositETH (
address account,
uint256 releaseTime
| function depositETH (
address account,
uint256 releaseTime
| 12,462 |
50 | // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. | require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
| require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
| 4,265 |
387 | // Sells the owedToken from the lender (and from the deposit if in owedToken) using theexchangeWrapper, then puts the resulting heldToken into the vault. Only trades formaxHeldTokenToBuy of heldTokens at most. / | function doSell(
MarginState.State storage state,
Tx transaction,
bytes orderData,
uint256 maxHeldTokenToBuy
)
internal
returns (uint256)
| function doSell(
MarginState.State storage state,
Tx transaction,
bytes orderData,
uint256 maxHeldTokenToBuy
)
internal
returns (uint256)
| 31,474 |
64 | // Returns whether the SetToken has an external position for a given component (ifof position modules is > 0) / | function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) {
return _setToken.getExternalPositionModules(_component).length > 0;
}
| function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) {
return _setToken.getExternalPositionModules(_component).length > 0;
}
| 5,445 |
29 | // переводим токены магазину address(this) - адресс контракта BibaCity | token.transferFrom(msg.sender, address(this), _amountToSell);
| token.transferFrom(msg.sender, address(this), _amountToSell);
| 30,722 |
187 | // Emitted when a user stakes nft token. sender User address. nftId The nft id. timestamp The time when stake nft. / | event NftStaked(
| event NftStaked(
| 72,511 |
8 | // The current validator set and their powers | address[] memory _currentValidators,
uint256[] memory _currentPowers,
| address[] memory _currentValidators,
uint256[] memory _currentPowers,
| 67,744 |
130 | // uint256 initialETHBalance = address(this).balance; |
swapTokensForEth(totalTokensToSwap);
uint256 ethBalance = address(this).balance;
uint256 ethForDev1 = ethBalance.mul(tokensForDev1).div(totalTokensToSwap);
uint256 ethForDev2 = ethBalance.mul(tokensForDev2).div(totalTokensToSwap);
uint256 ethForDev3 = ethBalance.mul(tokensForDev3).div(totalTokensToSwap);
uint256 ethForDev4 = ethBalance.mul(tokensForDev4).div(totalTokensToSwap);
|
swapTokensForEth(totalTokensToSwap);
uint256 ethBalance = address(this).balance;
uint256 ethForDev1 = ethBalance.mul(tokensForDev1).div(totalTokensToSwap);
uint256 ethForDev2 = ethBalance.mul(tokensForDev2).div(totalTokensToSwap);
uint256 ethForDev3 = ethBalance.mul(tokensForDev3).div(totalTokensToSwap);
uint256 ethForDev4 = ethBalance.mul(tokensForDev4).div(totalTokensToSwap);
| 22,036 |
11 | // Check is in case the stake amount increases | require(
_tellor.balanceOf(msg.sender) >= _tellor.uints(_STAKE_AMOUNT),
"balance must be greater than stake amount"
);
| require(
_tellor.balanceOf(msg.sender) >= _tellor.uints(_STAKE_AMOUNT),
"balance must be greater than stake amount"
);
| 35,213 |
2 | // Factory contract name | function contractName() external pure override returns (string memory) {
return "Redeem Minter Factory";
}
| function contractName() external pure override returns (string memory) {
return "Redeem Minter Factory";
}
| 2,788 |
8 | // Set the address of the token contract. Must be called by creator of this. Can only be set once. _legendsToken Address of the token contract. / | function setTokenContract(LegendsToken _legendsToken) external isCreator tokenContractNotSet {
legendsToken = _legendsToken;
}
| function setTokenContract(LegendsToken _legendsToken) external isCreator tokenContractNotSet {
legendsToken = _legendsToken;
}
| 39,321 |
35 | // Constructor that initializes the validators smart contract with the validators metadata registration/ database smart contract./registry_ IOrbsValidatorsRegistry The address of the validators metadata registration database./validatorsLimit_ uint Maximum number of validators list maximum size. | constructor(IOrbsValidatorsRegistry registry_, uint validatorsLimit_) public {
require(registry_ != IOrbsValidatorsRegistry(0), "Registry contract address 0");
require(validatorsLimit_ > 0, "Limit must be positive");
require(validatorsLimit_ <= MAX_VALIDATOR_LIMIT, "Limit is too high");
validatorsLimit = validatorsLimit_;
orbsValidatorsRegistry = registry_;
}
| constructor(IOrbsValidatorsRegistry registry_, uint validatorsLimit_) public {
require(registry_ != IOrbsValidatorsRegistry(0), "Registry contract address 0");
require(validatorsLimit_ > 0, "Limit must be positive");
require(validatorsLimit_ <= MAX_VALIDATOR_LIMIT, "Limit is too high");
validatorsLimit = validatorsLimit_;
orbsValidatorsRegistry = registry_;
}
| 32,181 |
17 | // trigger the event | BookRoomEvent(_id, room.owner, msg.sender, room.name, room.description, room.size, _price);
| BookRoomEvent(_id, room.owner, msg.sender, room.name, room.description, room.size, _price);
| 6,549 |
9 | // The block number when snp mining starts. | uint256 public startBlock;
| uint256 public startBlock;
| 4,154 |
88 | // emit Wined(msg.sender , reward,roomIdx ,players.getNameByAddr(msg.sender) ); | }else{
| }else{
| 10,308 |
112 | // are we in a round? | if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
| if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
| 3,008 |
57 | // If the amount being transfered is more than the balance of the account the transfer throws | uint previousBalanceFrom = balanceOfAt(_from, block.number);
require(previousBalanceFrom >= _amount);
| uint previousBalanceFrom = balanceOfAt(_from, block.number);
require(previousBalanceFrom >= _amount);
| 50,649 |
38 | // Creates Registry paymentAddress The address of the payment contract used when creating insurance contracts / | function PolicyRegistry(address paymentAddress) public {
IXTPayment = IXTPaymentContract(paymentAddress);
}
| function PolicyRegistry(address paymentAddress) public {
IXTPayment = IXTPaymentContract(paymentAddress);
}
| 19,023 |
3 | // fallback function | function () external payable {
}
| function () external payable {
}
| 15,704 |
126 | // A token inheriting from ERC20Rewards will reward token holders with a rewards token./ The rewarded amount will be a fixed wei per second, distributed proportionally to token holders/ by the size of their holdings. | contract ERC20Rewards is AccessControl, ERC20Permit {
using MinimalTransferHelper for IERC20;
using CastU256U32 for uint256;
using CastU256U128 for uint256;
event RewardsTokenSet(IERC20 token);
event RewardsSet(uint32 start, uint32 end, uint256 rate);
event RewardsPerTokenUpdated(uint256 accumulated);
event UserRewardsUpdated(address user, uint256 userRewards, uint256 paidRewardPerToken);
event Claimed(address receiver, uint256 claimed);
struct RewardsPeriod {
uint32 start; // Start time for the current rewardsToken schedule
uint32 end; // End time for the current rewardsToken schedule
}
struct RewardsPerToken {
uint128 accumulated; // Accumulated rewards per token for the period, scaled up by 1e18
uint32 lastUpdated; // Last time the rewards per token accumulator was updated
uint96 rate; // Wei rewarded per second among all token holders
}
struct UserRewards {
uint128 accumulated; // Accumulated rewards for the user until the checkpoint
uint128 checkpoint; // RewardsPerToken the last time the user rewards were updated
}
IERC20 public rewardsToken; // Token used as rewards
RewardsPeriod public rewardsPeriod; // Period in which rewards are accumulated by users
RewardsPerToken public rewardsPerToken; // Accumulator to track rewards per token
mapping (address => UserRewards) public rewards; // Rewards accumulated by users
constructor(string memory name, string memory symbol, uint8 decimals)
ERC20Permit(name, symbol, decimals)
{ }
/// @dev Return the earliest of two timestamps
function earliest(uint32 x, uint32 y) internal pure returns (uint32 z) {
z = (x < y) ? x : y;
}
/// @dev Set a rewards token.
/// @notice Careful, this can only be done once.
function setRewardsToken(IERC20 rewardsToken_)
external
auth
{
require(rewardsToken == IERC20(address(0)), "Rewards token already set");
rewardsToken = rewardsToken_;
emit RewardsTokenSet(rewardsToken_);
}
/// @dev Set a rewards schedule
function setRewards(uint32 start, uint32 end, uint96 rate)
external
auth
{
require(
start <= end,
"Incorrect input"
);
require(
rewardsToken != IERC20(address(0)),
"Rewards token not set"
);
// A new rewards program can be set if one is not running
require(
block.timestamp.u32() < rewardsPeriod.start || block.timestamp.u32() > rewardsPeriod.end,
"Ongoing rewards"
);
rewardsPeriod.start = start;
rewardsPeriod.end = end;
// If setting up a new rewards program, the rewardsPerToken.accumulated is used and built upon
// New rewards start accumulating from the new rewards program start
// Any unaccounted rewards from last program can still be added to the user rewards
// Any unclaimed rewards can still be claimed
rewardsPerToken.lastUpdated = start;
rewardsPerToken.rate = rate;
emit RewardsSet(start, end, rate);
}
/// @dev Update the rewards per token accumulator.
/// @notice Needs to be called on each liquidity event
function _updateRewardsPerToken() internal {
RewardsPerToken memory rewardsPerToken_ = rewardsPerToken;
RewardsPeriod memory rewardsPeriod_ = rewardsPeriod;
uint256 totalSupply_ = _totalSupply;
// We skip the update if the program hasn't started
if (block.timestamp.u32() < rewardsPeriod_.start) return;
// Find out the unaccounted time
uint32 end = earliest(block.timestamp.u32(), rewardsPeriod_.end);
uint256 unaccountedTime = end - rewardsPerToken_.lastUpdated; // Cast to uint256 to avoid overflows later on
if (unaccountedTime == 0) return; // We skip the storage changes if already updated in the same block
// Calculate and update the new value of the accumulator. unaccountedTime casts it into uint256, which is desired.
// If the first mint happens mid-program, we don't update the accumulator, no one gets the rewards for that period.
if (totalSupply_ != 0) rewardsPerToken_.accumulated = (rewardsPerToken_.accumulated + 1e18 * unaccountedTime * rewardsPerToken_.rate / totalSupply_).u128(); // The rewards per token are scaled up for precision
rewardsPerToken_.lastUpdated = end;
rewardsPerToken = rewardsPerToken_;
emit RewardsPerTokenUpdated(rewardsPerToken_.accumulated);
}
/// @dev Accumulate rewards for an user.
/// @notice Needs to be called on each liquidity event, or when user balances change.
function _updateUserRewards(address user) internal returns (uint128) {
UserRewards memory userRewards_ = rewards[user];
RewardsPerToken memory rewardsPerToken_ = rewardsPerToken;
// Calculate and update the new value user reserves. _balanceOf[user] casts it into uint256, which is desired.
userRewards_.accumulated = (userRewards_.accumulated + _balanceOf[user] * (rewardsPerToken_.accumulated - userRewards_.checkpoint) / 1e18).u128(); // We must scale down the rewards by the precision factor
userRewards_.checkpoint = rewardsPerToken_.accumulated;
rewards[user] = userRewards_;
emit UserRewardsUpdated(user, userRewards_.accumulated, userRewards_.checkpoint);
return userRewards_.accumulated;
}
/// @dev Mint tokens, after accumulating rewards for an user and update the rewards per token accumulator.
function _mint(address dst, uint256 wad)
internal virtual override
returns (bool)
{
_updateRewardsPerToken();
_updateUserRewards(dst);
return super._mint(dst, wad);
}
/// @dev Burn tokens, after accumulating rewards for an user and update the rewards per token accumulator.
function _burn(address src, uint256 wad)
internal virtual override
returns (bool)
{
_updateRewardsPerToken();
_updateUserRewards(src);
return super._burn(src, wad);
}
/// @dev Transfer tokens, after updating rewards for source and destination.
function _transfer(address src, address dst, uint wad) internal virtual override returns (bool) {
_updateRewardsPerToken();
_updateUserRewards(src);
_updateUserRewards(dst);
return super._transfer(src, dst, wad);
}
/// @dev Claim all rewards from caller into a given address
function claim(address to)
external
returns (uint256 claiming)
{
_updateRewardsPerToken();
claiming = _updateUserRewards(msg.sender);
rewards[msg.sender].accumulated = 0; // A Claimed event implies the rewards were set to zero
rewardsToken.safeTransfer(to, claiming);
emit Claimed(to, claiming);
}
}
| contract ERC20Rewards is AccessControl, ERC20Permit {
using MinimalTransferHelper for IERC20;
using CastU256U32 for uint256;
using CastU256U128 for uint256;
event RewardsTokenSet(IERC20 token);
event RewardsSet(uint32 start, uint32 end, uint256 rate);
event RewardsPerTokenUpdated(uint256 accumulated);
event UserRewardsUpdated(address user, uint256 userRewards, uint256 paidRewardPerToken);
event Claimed(address receiver, uint256 claimed);
struct RewardsPeriod {
uint32 start; // Start time for the current rewardsToken schedule
uint32 end; // End time for the current rewardsToken schedule
}
struct RewardsPerToken {
uint128 accumulated; // Accumulated rewards per token for the period, scaled up by 1e18
uint32 lastUpdated; // Last time the rewards per token accumulator was updated
uint96 rate; // Wei rewarded per second among all token holders
}
struct UserRewards {
uint128 accumulated; // Accumulated rewards for the user until the checkpoint
uint128 checkpoint; // RewardsPerToken the last time the user rewards were updated
}
IERC20 public rewardsToken; // Token used as rewards
RewardsPeriod public rewardsPeriod; // Period in which rewards are accumulated by users
RewardsPerToken public rewardsPerToken; // Accumulator to track rewards per token
mapping (address => UserRewards) public rewards; // Rewards accumulated by users
constructor(string memory name, string memory symbol, uint8 decimals)
ERC20Permit(name, symbol, decimals)
{ }
/// @dev Return the earliest of two timestamps
function earliest(uint32 x, uint32 y) internal pure returns (uint32 z) {
z = (x < y) ? x : y;
}
/// @dev Set a rewards token.
/// @notice Careful, this can only be done once.
function setRewardsToken(IERC20 rewardsToken_)
external
auth
{
require(rewardsToken == IERC20(address(0)), "Rewards token already set");
rewardsToken = rewardsToken_;
emit RewardsTokenSet(rewardsToken_);
}
/// @dev Set a rewards schedule
function setRewards(uint32 start, uint32 end, uint96 rate)
external
auth
{
require(
start <= end,
"Incorrect input"
);
require(
rewardsToken != IERC20(address(0)),
"Rewards token not set"
);
// A new rewards program can be set if one is not running
require(
block.timestamp.u32() < rewardsPeriod.start || block.timestamp.u32() > rewardsPeriod.end,
"Ongoing rewards"
);
rewardsPeriod.start = start;
rewardsPeriod.end = end;
// If setting up a new rewards program, the rewardsPerToken.accumulated is used and built upon
// New rewards start accumulating from the new rewards program start
// Any unaccounted rewards from last program can still be added to the user rewards
// Any unclaimed rewards can still be claimed
rewardsPerToken.lastUpdated = start;
rewardsPerToken.rate = rate;
emit RewardsSet(start, end, rate);
}
/// @dev Update the rewards per token accumulator.
/// @notice Needs to be called on each liquidity event
function _updateRewardsPerToken() internal {
RewardsPerToken memory rewardsPerToken_ = rewardsPerToken;
RewardsPeriod memory rewardsPeriod_ = rewardsPeriod;
uint256 totalSupply_ = _totalSupply;
// We skip the update if the program hasn't started
if (block.timestamp.u32() < rewardsPeriod_.start) return;
// Find out the unaccounted time
uint32 end = earliest(block.timestamp.u32(), rewardsPeriod_.end);
uint256 unaccountedTime = end - rewardsPerToken_.lastUpdated; // Cast to uint256 to avoid overflows later on
if (unaccountedTime == 0) return; // We skip the storage changes if already updated in the same block
// Calculate and update the new value of the accumulator. unaccountedTime casts it into uint256, which is desired.
// If the first mint happens mid-program, we don't update the accumulator, no one gets the rewards for that period.
if (totalSupply_ != 0) rewardsPerToken_.accumulated = (rewardsPerToken_.accumulated + 1e18 * unaccountedTime * rewardsPerToken_.rate / totalSupply_).u128(); // The rewards per token are scaled up for precision
rewardsPerToken_.lastUpdated = end;
rewardsPerToken = rewardsPerToken_;
emit RewardsPerTokenUpdated(rewardsPerToken_.accumulated);
}
/// @dev Accumulate rewards for an user.
/// @notice Needs to be called on each liquidity event, or when user balances change.
function _updateUserRewards(address user) internal returns (uint128) {
UserRewards memory userRewards_ = rewards[user];
RewardsPerToken memory rewardsPerToken_ = rewardsPerToken;
// Calculate and update the new value user reserves. _balanceOf[user] casts it into uint256, which is desired.
userRewards_.accumulated = (userRewards_.accumulated + _balanceOf[user] * (rewardsPerToken_.accumulated - userRewards_.checkpoint) / 1e18).u128(); // We must scale down the rewards by the precision factor
userRewards_.checkpoint = rewardsPerToken_.accumulated;
rewards[user] = userRewards_;
emit UserRewardsUpdated(user, userRewards_.accumulated, userRewards_.checkpoint);
return userRewards_.accumulated;
}
/// @dev Mint tokens, after accumulating rewards for an user and update the rewards per token accumulator.
function _mint(address dst, uint256 wad)
internal virtual override
returns (bool)
{
_updateRewardsPerToken();
_updateUserRewards(dst);
return super._mint(dst, wad);
}
/// @dev Burn tokens, after accumulating rewards for an user and update the rewards per token accumulator.
function _burn(address src, uint256 wad)
internal virtual override
returns (bool)
{
_updateRewardsPerToken();
_updateUserRewards(src);
return super._burn(src, wad);
}
/// @dev Transfer tokens, after updating rewards for source and destination.
function _transfer(address src, address dst, uint wad) internal virtual override returns (bool) {
_updateRewardsPerToken();
_updateUserRewards(src);
_updateUserRewards(dst);
return super._transfer(src, dst, wad);
}
/// @dev Claim all rewards from caller into a given address
function claim(address to)
external
returns (uint256 claiming)
{
_updateRewardsPerToken();
claiming = _updateUserRewards(msg.sender);
rewards[msg.sender].accumulated = 0; // A Claimed event implies the rewards were set to zero
rewardsToken.safeTransfer(to, claiming);
emit Claimed(to, claiming);
}
}
| 47,302 |
14 | // Transfers control of the contract to a newOwner.newOwner The address to transfer ownership to./ | function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| 5,863 |
3 | // 펌웨어 업데이트 관련 | mapping (uint => Firmware) firmwares; // fileid => Firmware
| mapping (uint => Firmware) firmwares; // fileid => Firmware
| 11,522 |
26 | // Updates the maximum hope amount per user./ | function setMaxHopePerUser(uint256 _maxHopePerUser) external onlyOwner {
maxHopePerUser = _maxHopePerUser;
}
| function setMaxHopePerUser(uint256 _maxHopePerUser) external onlyOwner {
maxHopePerUser = _maxHopePerUser;
}
| 20,268 |
2 | // 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.value The amount that will be created./ | function _mint(address account, uint256 value) internal {
super._mint(account, value);
_addAccount(account);
}
| function _mint(address account, uint256 value) internal {
super._mint(account, value);
_addAccount(account);
}
| 24,619 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.