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
|
---|---|---|---|---|
55 | // allow autonomousConverter and tokenPorter to mint token and assign to address/_from /_value Amount to be destroyed | function destroy(address _from, uint _value) public returns (bool) {
require(msg.sender == autonomousConverter || msg.sender == address(tokenPorter));
_balanceOf[_from] = _balanceOf[_from].sub(_value);
_totalSupply = _totalSupply.sub(_value);
emit Destroy(_from, _value);
emit Transfer(_from, 0x0, _value);
return true;
}
| function destroy(address _from, uint _value) public returns (bool) {
require(msg.sender == autonomousConverter || msg.sender == address(tokenPorter));
_balanceOf[_from] = _balanceOf[_from].sub(_value);
_totalSupply = _totalSupply.sub(_value);
emit Destroy(_from, _value);
emit Transfer(_from, 0x0, _value);
return true;
}
| 49,418 |
90 | // 46 | entry "so-so" : ENG_ADVERB
| entry "so-so" : ENG_ADVERB
| 20,883 |
29 | // Request whitelist upgrade target Address of new whitelisted contract functionSig function signature as bytes4 list `true` to whitelist, `false` otherwise / | function reqSetWhitelistCall(address target, bytes4 functionSig, bool list) external onlyOwner {
whitelistRequests[target][functionSig][list] = now;
emit RequestSetWhitelistCall(target, functionSig, list);
}
| function reqSetWhitelistCall(address target, bytes4 functionSig, bool list) external onlyOwner {
whitelistRequests[target][functionSig][list] = now;
emit RequestSetWhitelistCall(target, functionSig, list);
}
| 40,786 |
2 | // {IBEP20-approve}, and its usage is discouraged. Whenever possible, use {safeIncreaseAllowance} and{safeDecreaseAllowance} instead. / | function safeApprove(
IBEP20 token,
address spender,
uint256 value
) internal {
| function safeApprove(
IBEP20 token,
address spender,
uint256 value
) internal {
| 2,414 |
260 | // ============ Internal Functions ============ / This is the function that will be called postLoan i.e. Encode the logic to handle your flashloaned funds here | function callFunction(
address _sender,
Account.Info memory _account,
bytes memory _data
)
public
override
{
IssuanceArbData memory issueArbData = abi.decode(_data, (IssuanceArbData));
| function callFunction(
address _sender,
Account.Info memory _account,
bytes memory _data
)
public
override
{
IssuanceArbData memory issueArbData = abi.decode(_data, (IssuanceArbData));
| 33,148 |
58 | // 1 (ฮ๐ช+, ฮ๐ฉ๐-), user declares ฮ๐ช+ : State = Live | function mintAndSwapCollateralToDerivative(
address _pool,
uint256 _collateralAmount,
address _tokenIn, // Unwanted Derivative to be swaped
uint256 _minAmountOut
| function mintAndSwapCollateralToDerivative(
address _pool,
uint256 _collateralAmount,
address _tokenIn, // Unwanted Derivative to be swaped
uint256 _minAmountOut
| 78,949 |
3 | // Mapping from settingId to SettingValue | mapping (uint256 => SettingValue) internal settingValues;
| mapping (uint256 => SettingValue) internal settingValues;
| 28,218 |
73 | // Add=0, Replace=1, Remove=2 |
struct FacetCut {
address facetAddress;
FacetCutAction action;
bytes4[] functionSelectors;
}
|
struct FacetCut {
address facetAddress;
FacetCutAction action;
bytes4[] functionSelectors;
}
| 14,630 |
28 | // Evaluate if the init transition of the first block is invalid_initTransitionProof The inclusion proof of the disputed initial transition. _firstBlock The first rollup block / | function _invalidInitTransition(dt.TransitionProof calldata _initTransitionProof, dt.Block calldata _firstBlock)
private
returns (bool)
| function _invalidInitTransition(dt.TransitionProof calldata _initTransitionProof, dt.Block calldata _firstBlock)
private
returns (bool)
| 5,815 |
295 | // Max deposit limit needs to be under the limit | uint256 internal constant MAX_DEPOSIT_LIMIT = 0;
| uint256 internal constant MAX_DEPOSIT_LIMIT = 0;
| 67,900 |
4 | // Sets the contract address for a signature verification algorithm. Callable only by the owner. id The algorithm ID algo The address of the algorithm contract. / | function setAlgorithm(uint8 id, Algorithm algo) public owner_only {
algorithms[id] = algo;
emit AlgorithmUpdated(id, address(algo));
}
| function setAlgorithm(uint8 id, Algorithm algo) public owner_only {
algorithms[id] = algo;
emit AlgorithmUpdated(id, address(algo));
}
| 7,168 |
6 | // Removes the specified address from the list of administrators./ _address The address to remove from the administrator list. | function removeAdmin(address _address) external onlyAdmin returns(bool) {
require(_address != address(0), "Invalid address.");
require(admins[_address], "This address isn't an administrator.");
//The owner cannot be removed as admin.
require(_address != owner, "The owner cannot be added or removed to or from the administrator list.");
admins[_address] = false;
emit AdminRemoved(_address);
return true;
}
| function removeAdmin(address _address) external onlyAdmin returns(bool) {
require(_address != address(0), "Invalid address.");
require(admins[_address], "This address isn't an administrator.");
//The owner cannot be removed as admin.
require(_address != owner, "The owner cannot be added or removed to or from the administrator list.");
admins[_address] = false;
emit AdminRemoved(_address);
return true;
}
| 32,852 |
336 | // Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's, and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1. | * NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.
*
* This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
* by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting
* power can be queried through the public accessors {getVotes} and {getPastVotes}.
*
* By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
* requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
*
* _Available since v4.2._
*/
abstract contract ERC20Votes is ERC20Permit, IERC5805 {
struct Checkpoint {
uint32 fromBlock;
uint224 votes;
}
bytes32 private constant _DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping(address => address) private _delegates;
mapping(address => Checkpoint[]) private _checkpoints;
Checkpoint[] private _totalSupplyCheckpoints;
/**
* @dev Clock used for flagging checkpoints. Can be overridden to implement timestamp based checkpoints (and voting).
*/
function clock() public view virtual override returns (uint48) {
return SafeCast.toUint48(block.number);
}
/**
* @dev Description of the clock
*/
// solhint-disable-next-line func-name-mixedcase
function CLOCK_MODE() public view virtual override returns (string memory) {
// Check that the clock was not modified
require(clock() == block.number, "ERC20Votes: broken clock mode");
return "mode=blocknumber&from=default";
}
/**
* @dev Get the `pos`-th checkpoint for `account`.
*/
function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) {
return _checkpoints[account][pos];
}
/**
* @dev Get number of checkpoints for `account`.
*/
function numCheckpoints(address account) public view virtual returns (uint32) {
return SafeCast.toUint32(_checkpoints[account].length);
}
/**
* @dev Get the address `account` is currently delegating to.
*/
function delegates(address account) public view virtual override returns (address) {
return _delegates[account];
}
/**
* @dev Gets the current votes balance for `account`
*/
function getVotes(address account) public view virtual override returns (uint256) {
uint256 pos = _checkpoints[account].length;
unchecked {
return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
}
}
/**
* @dev Retrieve the number of votes for `account` at the end of `timepoint`.
*
* Requirements:
*
* - `timepoint` must be in the past
*/
function getPastVotes(address account, uint256 timepoint) public view virtual override returns (uint256) {
require(timepoint < clock(), "ERC20Votes: future lookup");
return _checkpointsLookup(_checkpoints[account], timepoint);
}
/**
* @dev Retrieve the `totalSupply` at the end of `timepoint`. Note, this value is the sum of all balances.
* It is NOT the sum of all the delegated votes!
*
* Requirements:
*
* - `timepoint` must be in the past
*/
function getPastTotalSupply(uint256 timepoint) public view virtual override returns (uint256) {
require(timepoint < clock(), "ERC20Votes: future lookup");
return _checkpointsLookup(_totalSupplyCheckpoints, timepoint);
}
/**
* @dev Lookup a value in a list of (sorted) checkpoints.
*/
function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 timepoint) private view returns (uint256) {
// We run a binary search to look for the last (most recent) checkpoint taken before (or at) `timepoint`.
//
// Initially we check if the block is recent to narrow the search range.
// During the loop, the index of the wanted checkpoint remains in the range [low-1, high).
// With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.
// - If the middle checkpoint is after `timepoint`, we look in [low, mid)
// - If the middle checkpoint is before or equal to `timepoint`, we look in [mid+1, high)
// Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not
// out of bounds (in which case we're looking too far in the past and the result is 0).
// Note that if the latest checkpoint available is exactly for `timepoint`, we end up with an index that is
// past the end of the array, so we technically don't find a checkpoint after `timepoint`, but it works out
// the same.
uint256 length = ckpts.length;
uint256 low = 0;
uint256 high = length;
if (length > 5) {
uint256 mid = length - Math.sqrt(length);
if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) {
high = mid;
} else {
low = mid + 1;
}
}
while (low < high) {
uint256 mid = Math.average(low, high);
if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) {
high = mid;
} else {
low = mid + 1;
}
}
unchecked {
return high == 0 ? 0 : _unsafeAccess(ckpts, high - 1).votes;
}
}
/**
* @dev Delegate votes from the sender to `delegatee`.
*/
function delegate(address delegatee) public virtual override {
_delegate(_msgSender(), delegatee);
}
/**
* @dev Delegates votes from signer to `delegatee`
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= expiry, "ERC20Votes: signature expired");
address signer = ECDSA.recover(
_hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
v,
r,
s
);
require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce");
_delegate(signer, delegatee);
}
/**
* @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).
*/
function _maxSupply() internal view virtual returns (uint224) {
return type(uint224).max;
}
/**
* @dev Snapshots the totalSupply after it has been increased.
*/
function _mint(address account, uint256 amount) internal virtual override {
super._mint(account, amount);
require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes");
_writeCheckpoint(_totalSupplyCheckpoints, _add, amount);
}
/**
* @dev Snapshots the totalSupply after it has been decreased.
*/
function _burn(address account, uint256 amount) internal virtual override {
super._burn(account, amount);
_writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount);
}
/**
* @dev Move voting power when tokens are transferred.
*
* Emits a {IVotes-DelegateVotesChanged} event.
*/
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._afterTokenTransfer(from, to, amount);
_moveVotingPower(delegates(from), delegates(to), amount);
}
/**
* @dev Change delegation for `delegator` to `delegatee`.
*
* Emits events {IVotes-DelegateChanged} and {IVotes-DelegateVotesChanged}.
*/
function _delegate(address delegator, address delegatee) internal virtual {
address currentDelegate = delegates(delegator);
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveVotingPower(currentDelegate, delegatee, delegatorBalance);
}
function _moveVotingPower(address src, address dst, uint256 amount) private {
if (src != dst && amount > 0) {
if (src != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount);
emit DelegateVotesChanged(src, oldWeight, newWeight);
}
if (dst != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount);
emit DelegateVotesChanged(dst, oldWeight, newWeight);
}
}
}
function _writeCheckpoint(
Checkpoint[] storage ckpts,
function(uint256, uint256) view returns (uint256) op,
uint256 delta
) private returns (uint256 oldWeight, uint256 newWeight) {
uint256 pos = ckpts.length;
unchecked {
Checkpoint memory oldCkpt = pos == 0 ? Checkpoint(0, 0) : _unsafeAccess(ckpts, pos - 1);
oldWeight = oldCkpt.votes;
newWeight = op(oldWeight, delta);
if (pos > 0 && oldCkpt.fromBlock == clock()) {
_unsafeAccess(ckpts, pos - 1).votes = SafeCast.toUint224(newWeight);
} else {
ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(clock()), votes: SafeCast.toUint224(newWeight)}));
}
}
}
function _add(uint256 a, uint256 b) private pure returns (uint256) {
return a + b;
}
function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
return a - b;
}
/**
* @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds.
*/
function _unsafeAccess(Checkpoint[] storage ckpts, uint256 pos) private pure returns (Checkpoint storage result) {
assembly {
mstore(0, ckpts.slot)
result.slot := add(keccak256(0, 0x20), pos)
}
}
}
| * NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.
*
* This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
* by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting
* power can be queried through the public accessors {getVotes} and {getPastVotes}.
*
* By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
* requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
*
* _Available since v4.2._
*/
abstract contract ERC20Votes is ERC20Permit, IERC5805 {
struct Checkpoint {
uint32 fromBlock;
uint224 votes;
}
bytes32 private constant _DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping(address => address) private _delegates;
mapping(address => Checkpoint[]) private _checkpoints;
Checkpoint[] private _totalSupplyCheckpoints;
/**
* @dev Clock used for flagging checkpoints. Can be overridden to implement timestamp based checkpoints (and voting).
*/
function clock() public view virtual override returns (uint48) {
return SafeCast.toUint48(block.number);
}
/**
* @dev Description of the clock
*/
// solhint-disable-next-line func-name-mixedcase
function CLOCK_MODE() public view virtual override returns (string memory) {
// Check that the clock was not modified
require(clock() == block.number, "ERC20Votes: broken clock mode");
return "mode=blocknumber&from=default";
}
/**
* @dev Get the `pos`-th checkpoint for `account`.
*/
function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) {
return _checkpoints[account][pos];
}
/**
* @dev Get number of checkpoints for `account`.
*/
function numCheckpoints(address account) public view virtual returns (uint32) {
return SafeCast.toUint32(_checkpoints[account].length);
}
/**
* @dev Get the address `account` is currently delegating to.
*/
function delegates(address account) public view virtual override returns (address) {
return _delegates[account];
}
/**
* @dev Gets the current votes balance for `account`
*/
function getVotes(address account) public view virtual override returns (uint256) {
uint256 pos = _checkpoints[account].length;
unchecked {
return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
}
}
/**
* @dev Retrieve the number of votes for `account` at the end of `timepoint`.
*
* Requirements:
*
* - `timepoint` must be in the past
*/
function getPastVotes(address account, uint256 timepoint) public view virtual override returns (uint256) {
require(timepoint < clock(), "ERC20Votes: future lookup");
return _checkpointsLookup(_checkpoints[account], timepoint);
}
/**
* @dev Retrieve the `totalSupply` at the end of `timepoint`. Note, this value is the sum of all balances.
* It is NOT the sum of all the delegated votes!
*
* Requirements:
*
* - `timepoint` must be in the past
*/
function getPastTotalSupply(uint256 timepoint) public view virtual override returns (uint256) {
require(timepoint < clock(), "ERC20Votes: future lookup");
return _checkpointsLookup(_totalSupplyCheckpoints, timepoint);
}
/**
* @dev Lookup a value in a list of (sorted) checkpoints.
*/
function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 timepoint) private view returns (uint256) {
// We run a binary search to look for the last (most recent) checkpoint taken before (or at) `timepoint`.
//
// Initially we check if the block is recent to narrow the search range.
// During the loop, the index of the wanted checkpoint remains in the range [low-1, high).
// With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.
// - If the middle checkpoint is after `timepoint`, we look in [low, mid)
// - If the middle checkpoint is before or equal to `timepoint`, we look in [mid+1, high)
// Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not
// out of bounds (in which case we're looking too far in the past and the result is 0).
// Note that if the latest checkpoint available is exactly for `timepoint`, we end up with an index that is
// past the end of the array, so we technically don't find a checkpoint after `timepoint`, but it works out
// the same.
uint256 length = ckpts.length;
uint256 low = 0;
uint256 high = length;
if (length > 5) {
uint256 mid = length - Math.sqrt(length);
if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) {
high = mid;
} else {
low = mid + 1;
}
}
while (low < high) {
uint256 mid = Math.average(low, high);
if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) {
high = mid;
} else {
low = mid + 1;
}
}
unchecked {
return high == 0 ? 0 : _unsafeAccess(ckpts, high - 1).votes;
}
}
/**
* @dev Delegate votes from the sender to `delegatee`.
*/
function delegate(address delegatee) public virtual override {
_delegate(_msgSender(), delegatee);
}
/**
* @dev Delegates votes from signer to `delegatee`
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= expiry, "ERC20Votes: signature expired");
address signer = ECDSA.recover(
_hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
v,
r,
s
);
require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce");
_delegate(signer, delegatee);
}
/**
* @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).
*/
function _maxSupply() internal view virtual returns (uint224) {
return type(uint224).max;
}
/**
* @dev Snapshots the totalSupply after it has been increased.
*/
function _mint(address account, uint256 amount) internal virtual override {
super._mint(account, amount);
require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes");
_writeCheckpoint(_totalSupplyCheckpoints, _add, amount);
}
/**
* @dev Snapshots the totalSupply after it has been decreased.
*/
function _burn(address account, uint256 amount) internal virtual override {
super._burn(account, amount);
_writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount);
}
/**
* @dev Move voting power when tokens are transferred.
*
* Emits a {IVotes-DelegateVotesChanged} event.
*/
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._afterTokenTransfer(from, to, amount);
_moveVotingPower(delegates(from), delegates(to), amount);
}
/**
* @dev Change delegation for `delegator` to `delegatee`.
*
* Emits events {IVotes-DelegateChanged} and {IVotes-DelegateVotesChanged}.
*/
function _delegate(address delegator, address delegatee) internal virtual {
address currentDelegate = delegates(delegator);
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveVotingPower(currentDelegate, delegatee, delegatorBalance);
}
function _moveVotingPower(address src, address dst, uint256 amount) private {
if (src != dst && amount > 0) {
if (src != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount);
emit DelegateVotesChanged(src, oldWeight, newWeight);
}
if (dst != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount);
emit DelegateVotesChanged(dst, oldWeight, newWeight);
}
}
}
function _writeCheckpoint(
Checkpoint[] storage ckpts,
function(uint256, uint256) view returns (uint256) op,
uint256 delta
) private returns (uint256 oldWeight, uint256 newWeight) {
uint256 pos = ckpts.length;
unchecked {
Checkpoint memory oldCkpt = pos == 0 ? Checkpoint(0, 0) : _unsafeAccess(ckpts, pos - 1);
oldWeight = oldCkpt.votes;
newWeight = op(oldWeight, delta);
if (pos > 0 && oldCkpt.fromBlock == clock()) {
_unsafeAccess(ckpts, pos - 1).votes = SafeCast.toUint224(newWeight);
} else {
ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(clock()), votes: SafeCast.toUint224(newWeight)}));
}
}
}
function _add(uint256 a, uint256 b) private pure returns (uint256) {
return a + b;
}
function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
return a - b;
}
/**
* @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds.
*/
function _unsafeAccess(Checkpoint[] storage ckpts, uint256 pos) private pure returns (Checkpoint storage result) {
assembly {
mstore(0, ckpts.slot)
result.slot := add(keccak256(0, 0x20), pos)
}
}
}
| 26,892 |
10 | // Store & retrieve a bytes1val Value to return/ | function getBytes1(bytes1 val) public pure returns (bytes1) {
return val;
}
| function getBytes1(bytes1 val) public pure returns (bytes1) {
return val;
}
| 16,403 |
42 | // Deactivate a previously activated failover Only the owner can call this function / | function deactivateFailover(bytes32 symbolHash) external onlyOwner {
require(prices[symbolHash].failoverActive, "Not active");
prices[symbolHash].failoverActive = false;
emit FailoverDeactivated(symbolHash);
}
| function deactivateFailover(bytes32 symbolHash) external onlyOwner {
require(prices[symbolHash].failoverActive, "Not active");
prices[symbolHash].failoverActive = false;
emit FailoverDeactivated(symbolHash);
}
| 16,868 |
24 | // Override of `balanceOf` to transform between internal units (wei) and rebased units (cents of WEUR). / | function balanceOf(address account) public view override returns (uint256) {
if (base == 0) {
return 0;
}
return ERC20.balanceOf(account) / base / 10_000;
}
| function balanceOf(address account) public view override returns (uint256) {
if (base == 0) {
return 0;
}
return ERC20.balanceOf(account) / base / 10_000;
}
| 32,518 |
31 | // In this case, the market is skewed long so its free to short. | if (longSupply > shortSupply) {
return (0, rateIsInvalid);
}
| if (longSupply > shortSupply) {
return (0, rateIsInvalid);
}
| 41,563 |
2 | // First, we'll compute what percentage of the Pool the protocol should own due to charging protocol fees on swap fees and yield. | (
uint256 expectedProtocolOwnershipPercentage,
uint256 currentInvariantWithLastJoinExitAmp
) = _getProtocolPoolOwnershipPercentage(balances, lastJoinExitAmp, lastPostJoinExitInvariant);
| (
uint256 expectedProtocolOwnershipPercentage,
uint256 currentInvariantWithLastJoinExitAmp
) = _getProtocolPoolOwnershipPercentage(balances, lastJoinExitAmp, lastPostJoinExitInvariant);
| 21,200 |
121 | // returns amount of token left to distribute | function getRemainingTokens(uint256 rewardTokenIndex) external view returns(uint256) {
if (rewardPeriodFinishes[rewardTokenIndex] <= block.timestamp) {
return 0;
} else {
uint256 amount = (rewardPeriodFinishes[rewardTokenIndex] - block.timestamp) * rewardSpeeds[rewardTokenIndex];
uint256 bal = IERC20(rewardTokenAddresses[rewardTokenIndex]).balanceOf(address(this));
uint256 totalOwed = unwithdrawnAccruedRewards[rewardTokenIndex];
uint256 rewardSpeed = rewardSpeeds[rewardTokenIndex];
if (rewardSpeed != 0 && accrualBlockTimestamp < rewardPeriodFinishes[rewardTokenIndex]) {
uint256 blockTimestampDelta = (min(block.timestamp, rewardPeriodFinishes[rewardTokenIndex]) - accrualBlockTimestamp);
uint256 accrued = (rewardSpeeds[rewardTokenIndex] * blockTimestampDelta);
uint256 remainingToDistribute = (bal > totalOwed) ? (bal - totalOwed) : 0;
if (accrued > remainingToDistribute) {
accrued = remainingToDistribute;
}
totalOwed += accrued;
}
if (rewardTokenIndex == stakedTokenRewardIndex) {
totalOwed += totalSupplies;
if (bal > totalOwed) {
return (bal - totalOwed);
} else {
return 0;
}
}
if (bal > totalOwed) {
bal -= totalOwed;
} else {
bal = 0;
}
return min(amount, bal);
}
}
| function getRemainingTokens(uint256 rewardTokenIndex) external view returns(uint256) {
if (rewardPeriodFinishes[rewardTokenIndex] <= block.timestamp) {
return 0;
} else {
uint256 amount = (rewardPeriodFinishes[rewardTokenIndex] - block.timestamp) * rewardSpeeds[rewardTokenIndex];
uint256 bal = IERC20(rewardTokenAddresses[rewardTokenIndex]).balanceOf(address(this));
uint256 totalOwed = unwithdrawnAccruedRewards[rewardTokenIndex];
uint256 rewardSpeed = rewardSpeeds[rewardTokenIndex];
if (rewardSpeed != 0 && accrualBlockTimestamp < rewardPeriodFinishes[rewardTokenIndex]) {
uint256 blockTimestampDelta = (min(block.timestamp, rewardPeriodFinishes[rewardTokenIndex]) - accrualBlockTimestamp);
uint256 accrued = (rewardSpeeds[rewardTokenIndex] * blockTimestampDelta);
uint256 remainingToDistribute = (bal > totalOwed) ? (bal - totalOwed) : 0;
if (accrued > remainingToDistribute) {
accrued = remainingToDistribute;
}
totalOwed += accrued;
}
if (rewardTokenIndex == stakedTokenRewardIndex) {
totalOwed += totalSupplies;
if (bal > totalOwed) {
return (bal - totalOwed);
} else {
return 0;
}
}
if (bal > totalOwed) {
bal -= totalOwed;
} else {
bal = 0;
}
return min(amount, bal);
}
}
| 3,935 |
150 | // _path = abi.encodePacked(remoteAddress, localAddress) this function set the trusted path for the cross-chain communication | function setTrustedRemote(
uint16 _remoteChainId,
bytes calldata _path
| function setTrustedRemote(
uint16 _remoteChainId,
bytes calldata _path
| 12,563 |
7 | // written when we get a keep result | uint256 fundingProofTimerStart; // start of the funding proof period. reused for funding fraud proof period
bytes32 signingGroupPubkeyX; // The X coordinate of the signing group's pubkey
bytes32 signingGroupPubkeyY; // The Y coordinate of the signing group's pubkey
| uint256 fundingProofTimerStart; // start of the funding proof period. reused for funding fraud proof period
bytes32 signingGroupPubkeyX; // The X coordinate of the signing group's pubkey
bytes32 signingGroupPubkeyY; // The Y coordinate of the signing group's pubkey
| 11,461 |
78 | // Wake up the reentrancy guard | _reentrancyMutexForTransfers = 1;
uint256 maxTransferAmount = tokenInterface.balanceOf(address(this));
require(maxTransferAmount > 0, "Insufficient balance");
uint256 total = 0;
for (uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0) && addresses[i] != address(this), "Invalid address for transfer");
require(amounts[i] > 0 && amounts[i] <= maxTransferAmount, "Invalid transfer amount");
require(_whitelistInterface.isWhitelistedAddress(addresses[i]), "Address not whitelisted");
| _reentrancyMutexForTransfers = 1;
uint256 maxTransferAmount = tokenInterface.balanceOf(address(this));
require(maxTransferAmount > 0, "Insufficient balance");
uint256 total = 0;
for (uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0) && addresses[i] != address(this), "Invalid address for transfer");
require(amounts[i] > 0 && amounts[i] <= maxTransferAmount, "Invalid transfer amount");
require(_whitelistInterface.isWhitelistedAddress(addresses[i]), "Address not whitelisted");
| 24,556 |
128 | // Returns the number of vesting schedules managed by this contract. return the number of vesting schedules/ | function getVestingSchedulesCount()
public
view
| function getVestingSchedulesCount()
public
view
| 20,879 |
42 | // Library used to query support of an interface declared via {IERC165}. As per the EIP-165 spec, no interface should ever match 0xffffffff | bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
| bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
| 2,976 |
35 | // tokenCap_ Max amount of tokens to be sold / | constructor(uint256 tokenCap_) {
require(tokenCap_ > 0, "CappedTokenSoldHelper: zero cap");
_tokenCap = tokenCap_;
}
| constructor(uint256 tokenCap_) {
require(tokenCap_ > 0, "CappedTokenSoldHelper: zero cap");
_tokenCap = tokenCap_;
}
| 86,099 |
6 | // Returns the number of elements in the list self stored linked list from contractreturn uint256 / | function range(List storage self) internal view returns (uint256) {
uint256 i;
uint256 num;
(, i) = adj(self, HEAD, NEXT);
while (i != HEAD) {
(, i) = adj(self, i, NEXT);
num++;
}
return num;
}
| function range(List storage self) internal view returns (uint256) {
uint256 i;
uint256 num;
(, i) = adj(self, HEAD, NEXT);
while (i != HEAD) {
(, i) = adj(self, i, NEXT);
num++;
}
return num;
}
| 23,115 |
139 | // Sets `adminRole` as ``role``'s admin role. | * Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
| * Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
| 2,017 |
19 | // Transfer margin right -> left if needed | if (rightFill[1] != 0) {
require(_leftOrder.takerMarginAddress == _rightOrder.makerMarginAddress, "MATCH:NOT_VALID_SWAP");
IERC20 takerMarginToken = IERC20(_leftOrder.takerMarginAddress);
require(takerMarginToken.allowance(_rightOrder.makerAddress, address(tokenSpender)) >= rightFill[1], "MATCH:NOT_ENOUGH_ALLOWED_MARGIN");
tokenSpender.claimTokens(takerMarginToken, _rightOrder.makerAddress, _leftOrder.makerAddress, rightFill[1]);
}
| if (rightFill[1] != 0) {
require(_leftOrder.takerMarginAddress == _rightOrder.makerMarginAddress, "MATCH:NOT_VALID_SWAP");
IERC20 takerMarginToken = IERC20(_leftOrder.takerMarginAddress);
require(takerMarginToken.allowance(_rightOrder.makerAddress, address(tokenSpender)) >= rightFill[1], "MATCH:NOT_ENOUGH_ALLOWED_MARGIN");
tokenSpender.claimTokens(takerMarginToken, _rightOrder.makerAddress, _leftOrder.makerAddress, rightFill[1]);
}
| 2,740 |
19 | // PIGGY-MODIFY: Checks if the account should be allowed to borrow the underlying asset of the given market pToken The market to verify the borrow against borrower The account which would borrow the asset borrowAmount The amount of underlying the account would borrowreturn 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) / | function borrowAllowed(
| function borrowAllowed(
| 27,317 |
3 | // Packs the remaining 17 bytes of `implementation` with the bytecode after the address. | mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance := create(0, 0x09, 0x37)
| mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance := create(0, 0x09, 0x37)
| 609 |
12 | // Gets the locators provided an array of server accounts/stakers an array of server accounts/ return locators an array of server locators. Positions are relative to stakers input array | function getLocators(address[] calldata stakers)
external
view
returns (string[] memory locators)
| function getLocators(address[] calldata stakers)
external
view
returns (string[] memory locators)
| 41,507 |
116 | // Get a reference to the number of tickets that need to be printed. If there's no funding cycle, there's no tickets to print. The reserved rate is in bits 8-15 of the metadata. | amount = _reservedTicketAmountFrom(
_processedTicketTrackerOf[_projectId],
uint256(uint8(_fundingCycle.metadata >> 8)),
_totalTickets
);
| amount = _reservedTicketAmountFrom(
_processedTicketTrackerOf[_projectId],
uint256(uint8(_fundingCycle.metadata >> 8)),
_totalTickets
);
| 16,926 |
33 | // ============================== AgToken ====================================== |
function updateStocksUsers(uint256 amount, address poolManager) external;
|
function updateStocksUsers(uint256 amount, address poolManager) external;
| 31,551 |
205 | // Set a minimum amount of OUSD in a mint or redeem that triggers arebase _threshold OUSD amount with 18 fixed decimals. / | function setRebaseThreshold(uint256 _threshold) external onlyGovernor {
rebaseThreshold = _threshold;
}
| function setRebaseThreshold(uint256 _threshold) external onlyGovernor {
rebaseThreshold = _threshold;
}
| 37,492 |
145 | // Multiplies two exponentials, returning a new exponential. / | function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
| function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
| 6,199 |
7 | // verify (tokenId, creator, hash, previousHash, uri) has been signed by a signer | _verifyMint(tokenId, creator, currentHash, previousHash, uri, proof);
| _verifyMint(tokenId, creator, currentHash, previousHash, uri, proof);
| 4,326 |
276 | // Note: we can't use "currentEthInvested" for this calculation, we must use:currentEthInvested + ethTowardsICOPriceTokens This is because a split-buy essentially needs to simulate two separate buys - including the currentEthInvested update that comes BEFORE variable price tokens are bought! |
uint simulatedEthBeforeInvested = toPowerOfThreeHalves(tokenSupply.div(MULTIPLIER * 1e6)).mul(2).div(3) + ethTowardsICOPriceTokens;
uint simulatedEthAfterInvested = simulatedEthBeforeInvested + ethTowardsVariablePriceTokens;
|
uint simulatedEthBeforeInvested = toPowerOfThreeHalves(tokenSupply.div(MULTIPLIER * 1e6)).mul(2).div(3) + ethTowardsICOPriceTokens;
uint simulatedEthAfterInvested = simulatedEthBeforeInvested + ethTowardsVariablePriceTokens;
| 24,416 |
23 | // Helper contracts to facilitate cross chain actions between HubPool and SpokePool for a specific network. | struct CrossChainContract {
address adapter;
address spokePool;
}
| struct CrossChainContract {
address adapter;
address spokePool;
}
| 29,551 |
14 | // bytes32 _id = keccak256(abi.encodePacked(_studentid)); | students[_wallet] = Student(_studentid, name, surname, _wallet, 0);
studentCount++;
| students[_wallet] = Student(_studentid, name, surname, _wallet, 0);
studentCount++;
| 37,766 |
68 | // Internal function to set the ACO Pool fee. newAcoPoolFee Value of the new ACO Pool fee. It is a percentage value (100000 is 100%). / | function _setAcoPoolFee(uint256 newAcoPoolFee) internal virtual {
emit SetAcoPoolFee(acoPoolFee, newAcoPoolFee);
acoPoolFee = newAcoPoolFee;
}
| function _setAcoPoolFee(uint256 newAcoPoolFee) internal virtual {
emit SetAcoPoolFee(acoPoolFee, newAcoPoolFee);
acoPoolFee = newAcoPoolFee;
}
| 26,034 |
3 | // TODO | bytes32 name = "ETH";
admin = Admin(false, name, msg.sender);
| bytes32 name = "ETH";
admin = Admin(false, name, msg.sender);
| 29,024 |
119 | // Crowdsale(uint256 _rate, address _wallet, ERC20 _token) | constructor(ERC20 _token, uint16 _initialEtherUsdRate, address _wallet, address _tokensWallet,
uint256 _presaleOpeningTime, uint256 _presaleClosingTime, uint256 _openingTime, uint256 _closingTime
) public
TimedPresaleCrowdsale(_presaleOpeningTime, _presaleClosingTime, _openingTime, _closingTime)
| constructor(ERC20 _token, uint16 _initialEtherUsdRate, address _wallet, address _tokensWallet,
uint256 _presaleOpeningTime, uint256 _presaleClosingTime, uint256 _openingTime, uint256 _closingTime
) public
TimedPresaleCrowdsale(_presaleOpeningTime, _presaleClosingTime, _openingTime, _closingTime)
| 14,443 |
108 | // calculate relativeRewardPerBlock | relativeRewardPerBlock = (setup.rewardPerBlock * ((mainTokenAmount * 1e18) / _setupsInfo[_setups[setupIndex].infoIndex].maxStakeable)) / 1e18;
| relativeRewardPerBlock = (setup.rewardPerBlock * ((mainTokenAmount * 1e18) / _setupsInfo[_setups[setupIndex].infoIndex].maxStakeable)) / 1e18;
| 40,085 |
33 | // We add half the scale before dividing so that we get rounding instead of truncation.See "Listing 6" and text above it at https:accu.org/index.php/journals/1717 Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. | (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
| (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
| 4,726 |
13 | // We send the tokens here | transferTokens(
msg.sender,
payable(loans[loanId].borrower),
loans[loanId].currency,
loans[loanId].loanAmount,
loans[loanId].loanAmount.div(lenderFee).div(discount)
);
emit LoanApproved(
msg.sender,
| transferTokens(
msg.sender,
payable(loans[loanId].borrower),
loans[loanId].currency,
loans[loanId].loanAmount,
loans[loanId].loanAmount.div(lenderFee).div(discount)
);
emit LoanApproved(
msg.sender,
| 15,140 |
16 | // - The host can begin the tournament when they like/- The tournament can only be started if there are more than one registrants | function startTournament()
public
notStopped
onlyHost
moreThanOnePlayer
| function startTournament()
public
notStopped
onlyHost
moreThanOnePlayer
| 4,566 |
64 | // Price call entry configuration structure | struct Config {
// Single query fee๏ผ0.0001 ether, DIMI_ETHER). 100
uint16 singleFee;
// Double query fee๏ผ0.0001 ether, DIMI_ETHER). 100
uint16 doubleFee;
// The normal state flag of the call address. 0
uint8 normalFlag;
}
| struct Config {
// Single query fee๏ผ0.0001 ether, DIMI_ETHER). 100
uint16 singleFee;
// Double query fee๏ผ0.0001 ether, DIMI_ETHER). 100
uint16 doubleFee;
// The normal state flag of the call address. 0
uint8 normalFlag;
}
| 74,780 |
23 | // Although 1inch will accept all gems, this check is a sanity check, just in case | if (gem.balanceOf(address(this)) > 0) {
| if (gem.balanceOf(address(this)) > 0) {
| 27,503 |
37 | // create assertion | createAssertion(vmHash, inboxSize);
| createAssertion(vmHash, inboxSize);
| 23,636 |
2 | // Set Open Status / | function setOpenStatus(bool status) external onlyRole(MANAGER_ROLE) {
openStatus = status;
emit SetOpenStatus(status);
}
| function setOpenStatus(bool status) external onlyRole(MANAGER_ROLE) {
openStatus = status;
emit SetOpenStatus(status);
}
| 16,179 |
0 | // Global state. | AggregatorV3Interface public immutable override chainlinkOracle;
uint8 public immutable override oracleDecimals;
uint256 public immutable initialEpochStartTimestamp; // Timestamp that epoch 0 STARTED at.
uint256 public immutable MINIMUM_EXECUTION_WAIT_THRESHOLD; // This value can only be upgraded via contract upgrade.
uint256 public immutable EPOCH_LENGTH; // No mechanism exists currently to upgrade this value. Additional contract work+testing needed to make this have flexibility.
| AggregatorV3Interface public immutable override chainlinkOracle;
uint8 public immutable override oracleDecimals;
uint256 public immutable initialEpochStartTimestamp; // Timestamp that epoch 0 STARTED at.
uint256 public immutable MINIMUM_EXECUTION_WAIT_THRESHOLD; // This value can only be upgraded via contract upgrade.
uint256 public immutable EPOCH_LENGTH; // No mechanism exists currently to upgrade this value. Additional contract work+testing needed to make this have flexibility.
| 36,396 |
31 | // PRIVILEGED FUNCTION. Adds a new valid keeper to the list_keeper Address of the keeper / | function addKeeper(address _keeper) external override {
_onlyGovernanceOrEmergency();
require(!keeperList[_keeper] && _keeper != address(0), 'Incorrect address');
keeperList[_keeper] = true;
}
| function addKeeper(address _keeper) external override {
_onlyGovernanceOrEmergency();
require(!keeperList[_keeper] && _keeper != address(0), 'Incorrect address');
keeperList[_keeper] = true;
}
| 72,367 |
4 | // Accumulate rewards for an user. | function updateUserRewards(address user) public returns (uint128) {
return _updateUserRewards(user);
}
| function updateUserRewards(address user) public returns (uint128) {
return _updateUserRewards(user);
}
| 43,466 |
121 | // early sell logic | bool isBuy = from == uniswapV2Pair;
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
} else {
| bool isBuy = from == uniswapV2Pair;
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
} else {
| 16,164 |
94 | // Set the start block. | function setStartBlock(uint256 arg) public onlyOwner {
if(arg == 0){
startBlock = block.timestamp;
}else{
| function setStartBlock(uint256 arg) public onlyOwner {
if(arg == 0){
startBlock = block.timestamp;
}else{
| 42,877 |
32 | // this can be 0 when pool is not initialized | if (rewardParams.averagePeriodInSeconds > 0) {
result.twapPeriodInSeconds = rewardParams.averagePeriodInSeconds;
result.maxProfitablePrice = rewardParams.expectedAvgEth;
uint256 twapPeriodWeightedPrice = (result.profitablePrice * (MAX_TWAP_PERIOD - rewardParams.averagePeriodInSeconds) + rewardParams.expectedAvgEth * rewardParams.averagePeriodInSeconds) / MAX_TWAP_PERIOD;
uint256 rewardablePrice = Math.min(
rewardParams.numEth,
twapPeriodWeightedPrice
);
result.rewardableProfit = rewardablePrice > result.profitablePrice
? rewardablePrice - result.profitablePrice
| if (rewardParams.averagePeriodInSeconds > 0) {
result.twapPeriodInSeconds = rewardParams.averagePeriodInSeconds;
result.maxProfitablePrice = rewardParams.expectedAvgEth;
uint256 twapPeriodWeightedPrice = (result.profitablePrice * (MAX_TWAP_PERIOD - rewardParams.averagePeriodInSeconds) + rewardParams.expectedAvgEth * rewardParams.averagePeriodInSeconds) / MAX_TWAP_PERIOD;
uint256 rewardablePrice = Math.min(
rewardParams.numEth,
twapPeriodWeightedPrice
);
result.rewardableProfit = rewardablePrice > result.profitablePrice
? rewardablePrice - result.profitablePrice
| 27,929 |
95 | // transfer | _updateAccountSnapshot(from);
_updateAccountSnapshot(to);
| _updateAccountSnapshot(from);
_updateAccountSnapshot(to);
| 4,950 |
300 | // If there is no mint/redeem, and the new total balance >= old one, then the weight must be non-increasing and thus there is no penalty. | if (amounts[i] == 0 && newTotalBalance >= oldTotalBalance) {
continue;
}
| if (amounts[i] == 0 && newTotalBalance >= oldTotalBalance) {
continue;
}
| 29,236 |
8 | // }if (!stringsEqual(newDNI, "-1")){ | DNI = newDNI;
| DNI = newDNI;
| 8,394 |
201 | // Decrease the total bond supply by redeeming bonds. Parameters ---------------- |redemption_epochs|: An array of bonds to be redeemed. The bonds are identified by their redemption epochs. |epoch_id|: The current epoch ID. |coin|: The JohnLawCoin contract. The ownership needs to be transferred to this contract. Returns ---------------- A tuple of two values: - The number of redeemed bonds. - The number of expired bonds. | function decreaseBondSupply(address sender, uint[] memory redemption_epochs,
uint epoch_id, JohnLawCoin_v2 coin)
| function decreaseBondSupply(address sender, uint[] memory redemption_epochs,
uint epoch_id, JohnLawCoin_v2 coin)
| 20,868 |
0 | // default role | string SUPER_ADMIN_ROLE = "SUPER_ADMIN";
string MODERATOR_ROLE = "MODERATOR";
string ADMIN_ROLE = "ADMIN";
| string SUPER_ADMIN_ROLE = "SUPER_ADMIN";
string MODERATOR_ROLE = "MODERATOR";
string ADMIN_ROLE = "ADMIN";
| 27,950 |
234 | // Tries to returns the value associated with `key`.O(1).Does not revert if `key` is not in the map. _Available since v3.4._ / | function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
| function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
| 6,210 |
272 | // ERC20 implementation internal function backing transfer() and transferFrom() validates the transfer before allowing it. NOTE: This is not standard ERC20 behavior / | function _transfer(address _from, address _to, uint256 _amount) internal whenTransferAllowed(_from, _amount) {
executeTransferInternal(_from, _to, _amount);
}
| function _transfer(address _from, address _to, uint256 _amount) internal whenTransferAllowed(_from, _amount) {
executeTransferInternal(_from, _to, _amount);
}
| 6,917 |
13 | // Calculate the hash of a ring. | function calculateRinghash(
uint ringSize,
uint8[] vList,
bytes32[] rList,
bytes32[] sList
)
public
pure
returns (bytes32)
| function calculateRinghash(
uint ringSize,
uint8[] vList,
bytes32[] rList,
bytes32[] sList
)
public
pure
returns (bytes32)
| 10,288 |
14 | // Prize bank. this is how much prize money the next goose will win. / | uint256 public prizeBank = 0;
| uint256 public prizeBank = 0;
| 23,689 |
12 | // function cancelOrdersUpTo(uint256) | bytes4 constant internal CANCEL_ORDERS_UP_TO_SELECTOR = 0x4f9559b1;
| bytes4 constant internal CANCEL_ORDERS_UP_TO_SELECTOR = 0x4f9559b1;
| 34,224 |
9 | // Triggers stopped state. sender Address which executes pause. Requirements: - The contract must not be paused. / | function _pause(address sender) internal virtual whenNotPaused {
_paused = true;
emit Paused(sender);
}
| function _pause(address sender) internal virtual whenNotPaused {
_paused = true;
emit Paused(sender);
}
| 28,768 |
0 | // The first key is the delegator and the second key a id.The value is the address of the delegate | mapping (address => mapping (bytes32 => address)) public delegation;
| mapping (address => mapping (bytes32 => address)) public delegation;
| 24,400 |
0 | // Returns the subtraction of two unsigned integers, reverting onoverflow (when the result is negative). Counterpart to Solidity's `-` operator. Requirements: - Subtraction cannot overflow. / | function safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
return safeSub(a, b, "SafeMath: subtraction overflow");
}
| function safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
return safeSub(a, b, "SafeMath: subtraction overflow");
}
| 18,649 |
4 | // Hash of expected fulfillment parameters are kept to verify that/ the fulfillment will be done with the correct parameters | mapping(bytes32 => bytes32) private requestIdToFulfillmentParameters;
| mapping(bytes32 => bytes32) private requestIdToFulfillmentParameters;
| 19,390 |
13 | // Daily Limit Module - Allows to transfer limited amounts of ERC20 tokens and Ether without confirmations./Stefan George - <[email protected]> | contract DailyLimitModule is Module {
string public constant NAME = "Daily Limit Module";
string public constant VERSION = "0.1.0";
// dailyLimits mapping maps token address to daily limit settings.
mapping (address => DailyLimit) public dailyLimits;
struct DailyLimit {
uint256 dailyLimit;
uint256 spentToday;
uint256 lastDay;
}
/// @dev Setup function sets initial storage of contract.
/// @param tokens List of token addresses. Ether is represented with address 0x0.
/// @param _dailyLimits List of daily limits in smalles units (e.g. Wei for Ether).
function setup(address[] memory tokens, uint256[] memory _dailyLimits)
public
{
setManager();
for (uint256 i = 0; i < tokens.length; i++)
dailyLimits[tokens[i]].dailyLimit = _dailyLimits[i];
}
/// @dev Allows to update the daily limit for a specified token. This can only be done via a Safe transaction.
/// @param token Token contract address.
/// @param dailyLimit Daily limit in smallest token unit.
function changeDailyLimit(address token, uint256 dailyLimit)
public
authorized
{
dailyLimits[token].dailyLimit = dailyLimit;
}
/// @dev Returns if Safe transaction is a valid daily limit transaction.
/// @param token Address of the token that should be transfered (0 for Ether)
/// @param to Address to which the tokens should be transfered
/// @param amount Amount of tokens (or Ether) that should be transfered
/// @return Returns if transaction can be executed.
function executeDailyLimit(address token, address to, uint256 amount)
public
{
// Only Safe owners are allowed to execute daily limit transactions.
require(OwnerManager(address(manager)).isOwner(msg.sender), "Method can only be called by an owner");
require(to != address(0), "Invalid to address provided");
require(amount > 0, "Invalid amount provided");
// Validate that transfer is not exceeding daily limit.
require(isUnderLimit(token, amount), "Daily limit has been reached");
dailyLimits[token].spentToday += amount;
if (token == address(0)) {
require(manager.execTransactionFromModule(to, amount, "", Enum.Operation.Call), "Could not execute ether transfer");
} else {
bytes memory data = abi.encodeWithSignature("transfer(address,uint256)", to, amount);
require(manager.execTransactionFromModule(token, 0, data, Enum.Operation.Call), "Could not execute token transfer");
}
}
function isUnderLimit(address token, uint256 amount)
internal
returns (bool)
{
DailyLimit storage dailyLimit = dailyLimits[token];
if (today() > dailyLimit.lastDay) {
dailyLimit.lastDay = today();
dailyLimit.spentToday = 0;
}
if (dailyLimit.spentToday + amount <= dailyLimit.dailyLimit &&
dailyLimit.spentToday + amount > dailyLimit.spentToday)
return true;
return false;
}
/// @dev Returns last midnight as Unix timestamp.
/// @return Unix timestamp.
function today()
public
view
returns (uint)
{
return now - (now % 1 days);
}
}
| contract DailyLimitModule is Module {
string public constant NAME = "Daily Limit Module";
string public constant VERSION = "0.1.0";
// dailyLimits mapping maps token address to daily limit settings.
mapping (address => DailyLimit) public dailyLimits;
struct DailyLimit {
uint256 dailyLimit;
uint256 spentToday;
uint256 lastDay;
}
/// @dev Setup function sets initial storage of contract.
/// @param tokens List of token addresses. Ether is represented with address 0x0.
/// @param _dailyLimits List of daily limits in smalles units (e.g. Wei for Ether).
function setup(address[] memory tokens, uint256[] memory _dailyLimits)
public
{
setManager();
for (uint256 i = 0; i < tokens.length; i++)
dailyLimits[tokens[i]].dailyLimit = _dailyLimits[i];
}
/// @dev Allows to update the daily limit for a specified token. This can only be done via a Safe transaction.
/// @param token Token contract address.
/// @param dailyLimit Daily limit in smallest token unit.
function changeDailyLimit(address token, uint256 dailyLimit)
public
authorized
{
dailyLimits[token].dailyLimit = dailyLimit;
}
/// @dev Returns if Safe transaction is a valid daily limit transaction.
/// @param token Address of the token that should be transfered (0 for Ether)
/// @param to Address to which the tokens should be transfered
/// @param amount Amount of tokens (or Ether) that should be transfered
/// @return Returns if transaction can be executed.
function executeDailyLimit(address token, address to, uint256 amount)
public
{
// Only Safe owners are allowed to execute daily limit transactions.
require(OwnerManager(address(manager)).isOwner(msg.sender), "Method can only be called by an owner");
require(to != address(0), "Invalid to address provided");
require(amount > 0, "Invalid amount provided");
// Validate that transfer is not exceeding daily limit.
require(isUnderLimit(token, amount), "Daily limit has been reached");
dailyLimits[token].spentToday += amount;
if (token == address(0)) {
require(manager.execTransactionFromModule(to, amount, "", Enum.Operation.Call), "Could not execute ether transfer");
} else {
bytes memory data = abi.encodeWithSignature("transfer(address,uint256)", to, amount);
require(manager.execTransactionFromModule(token, 0, data, Enum.Operation.Call), "Could not execute token transfer");
}
}
function isUnderLimit(address token, uint256 amount)
internal
returns (bool)
{
DailyLimit storage dailyLimit = dailyLimits[token];
if (today() > dailyLimit.lastDay) {
dailyLimit.lastDay = today();
dailyLimit.spentToday = 0;
}
if (dailyLimit.spentToday + amount <= dailyLimit.dailyLimit &&
dailyLimit.spentToday + amount > dailyLimit.spentToday)
return true;
return false;
}
/// @dev Returns last midnight as Unix timestamp.
/// @return Unix timestamp.
function today()
public
view
returns (uint)
{
return now - (now % 1 days);
}
}
| 1,905 |
173 | // Selector of `log(string,string,uint256)`. | mstore(0x00, 0x5821efa1)
mstore(0x20, 0x60)
mstore(0x40, 0xa0)
mstore(0x60, p2)
writeString(0x80, p0)
writeString(0xc0, p1)
| mstore(0x00, 0x5821efa1)
mstore(0x20, 0x60)
mstore(0x40, 0xa0)
mstore(0x60, p2)
writeString(0x80, p0)
writeString(0xc0, p1)
| 30,519 |
167 | // whether the token can already be traded | bool public tradingEnabled;
| bool public tradingEnabled;
| 10,724 |
208 | // BaseERC20Token Implementation of the BaseERC20Token / | contract BaseERC20Token is ERC20Detailed, ERC20Capped, ERC20Burnable, OperatorRole, TokenRecover {
event MintFinished();
event TransferEnabled();
// indicates if minting is finished
bool private _mintingFinished = false;
// indicates if transfer is enabled
bool private _transferEnabled = false;
/**
* @dev Tokens can be minted only before minting finished.
*/
modifier canMint() {
require(!_mintingFinished);
_;
}
/**
* @dev Tokens can be moved only after if transfer enabled or if you are an approved operator.
*/
modifier canTransfer(address from) {
require(_transferEnabled || isOperator(from));
_;
}
/**
* @param name Name of the token
* @param symbol A symbol to be used as ticker
* @param decimals Number of decimals. All the operations are done using the smallest and indivisible token unit
* @param cap Maximum number of tokens mintable
* @param initialSupply Initial token supply
*/
constructor(
string memory name,
string memory symbol,
uint8 decimals,
uint256 cap,
uint256 initialSupply
)
public
ERC20Detailed(name, symbol, decimals)
ERC20Capped(cap)
{
if (initialSupply > 0) {
_mint(owner(), initialSupply);
}
}
/**
* @return if minting is finished or not.
*/
function mintingFinished() public view returns (bool) {
return _mintingFinished;
}
/**
* @return if transfer is enabled or not.
*/
function transferEnabled() public view returns (bool) {
return _transferEnabled;
}
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public canMint returns (bool) {
return super.mint(to, value);
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return A boolean that indicates if the operation was successful.
*/
function transfer(address to, uint256 value) public canTransfer(msg.sender) returns (bool) {
return super.transfer(to, value);
}
/**
* @dev Transfer tokens from one address to another.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 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) public canTransfer(from) returns (bool) {
return super.transferFrom(from, to, value);
}
/**
* @dev Function to stop minting new tokens.
*/
function finishMinting() public onlyOwner canMint {
_mintingFinished = true;
emit MintFinished();
}
/**
* @dev Function to enable transfers.
*/
function enableTransfer() public onlyOwner {
_transferEnabled = true;
emit TransferEnabled();
}
/**
* @dev remove the `operator` role from address
* @param account Address you want to remove role
*/
function removeOperator(address account) public onlyOwner {
_removeOperator(account);
}
/**
* @dev remove the `minter` role from address
* @param account Address you want to remove role
*/
function removeMinter(address account) public onlyOwner {
_removeMinter(account);
}
}
| contract BaseERC20Token is ERC20Detailed, ERC20Capped, ERC20Burnable, OperatorRole, TokenRecover {
event MintFinished();
event TransferEnabled();
// indicates if minting is finished
bool private _mintingFinished = false;
// indicates if transfer is enabled
bool private _transferEnabled = false;
/**
* @dev Tokens can be minted only before minting finished.
*/
modifier canMint() {
require(!_mintingFinished);
_;
}
/**
* @dev Tokens can be moved only after if transfer enabled or if you are an approved operator.
*/
modifier canTransfer(address from) {
require(_transferEnabled || isOperator(from));
_;
}
/**
* @param name Name of the token
* @param symbol A symbol to be used as ticker
* @param decimals Number of decimals. All the operations are done using the smallest and indivisible token unit
* @param cap Maximum number of tokens mintable
* @param initialSupply Initial token supply
*/
constructor(
string memory name,
string memory symbol,
uint8 decimals,
uint256 cap,
uint256 initialSupply
)
public
ERC20Detailed(name, symbol, decimals)
ERC20Capped(cap)
{
if (initialSupply > 0) {
_mint(owner(), initialSupply);
}
}
/**
* @return if minting is finished or not.
*/
function mintingFinished() public view returns (bool) {
return _mintingFinished;
}
/**
* @return if transfer is enabled or not.
*/
function transferEnabled() public view returns (bool) {
return _transferEnabled;
}
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public canMint returns (bool) {
return super.mint(to, value);
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return A boolean that indicates if the operation was successful.
*/
function transfer(address to, uint256 value) public canTransfer(msg.sender) returns (bool) {
return super.transfer(to, value);
}
/**
* @dev Transfer tokens from one address to another.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 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) public canTransfer(from) returns (bool) {
return super.transferFrom(from, to, value);
}
/**
* @dev Function to stop minting new tokens.
*/
function finishMinting() public onlyOwner canMint {
_mintingFinished = true;
emit MintFinished();
}
/**
* @dev Function to enable transfers.
*/
function enableTransfer() public onlyOwner {
_transferEnabled = true;
emit TransferEnabled();
}
/**
* @dev remove the `operator` role from address
* @param account Address you want to remove role
*/
function removeOperator(address account) public onlyOwner {
_removeOperator(account);
}
/**
* @dev remove the `minter` role from address
* @param account Address you want to remove role
*/
function removeMinter(address account) public onlyOwner {
_removeMinter(account);
}
}
| 33,434 |
14 | // Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or throughinteracting with Pools using Internal Balance. Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETHaddress. / | event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta);
| event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta);
| 21,974 |
30 | // See {IERC721Receiver-onERC721Received}. / | function onERC721Received(
address,
address from,
uint256 id,
bytes calldata data
) external override nonReentrant returns(bytes4) {
_onERC721Received(from, id, data);
return this.onERC721Received.selector;
}
| function onERC721Received(
address,
address from,
uint256 id,
bytes calldata data
) external override nonReentrant returns(bytes4) {
_onERC721Received(from, id, data);
return this.onERC721Received.selector;
}
| 19,666 |
100 | // Start Investing Send part of the funds offline and calculate the minimum amount of fund needed to keep the fund functioning and calculate the maximum amount of fund allowed to be withdrawn per period. | function start() initialized isBincentive public {
// Send some USDT offline
uint256 amountSentOffline = currentInvestedAmount.mul(percentageOffchainFund).div(100);
checkBalanceTransfer(bincentiveCold, amountSentOffline);
minimumFund = totalSupply().mul(percentageMinimumFund).div(100);
// Start the contract
fundStatus = 4;
emit StartFund(now, investors.length, currentInvestedAmount, totalSupply());
}
| function start() initialized isBincentive public {
// Send some USDT offline
uint256 amountSentOffline = currentInvestedAmount.mul(percentageOffchainFund).div(100);
checkBalanceTransfer(bincentiveCold, amountSentOffline);
minimumFund = totalSupply().mul(percentageMinimumFund).div(100);
// Start the contract
fundStatus = 4;
emit StartFund(now, investors.length, currentInvestedAmount, totalSupply());
}
| 41,057 |
33 | // returns the recipient's address and amount is the value to be transferred | if (signature == _BURN) {
| if (signature == _BURN) {
| 35,455 |
19 | // timelock to raise deployment limit | uint256 public immutable timelockInBlocks = 6600;
| uint256 public immutable timelockInBlocks = 6600;
| 38,880 |
54 | // get an instance of Investor using the input variables and push into the array of investors, returns the index | uint index = investors.push(Investor(msg.sender, now)) - 1;
_AddrsToInvestorNo[msg.sender] = index; // to get the index for an address
| uint index = investors.push(Investor(msg.sender, now)) - 1;
_AddrsToInvestorNo[msg.sender] = index; // to get the index for an address
| 45,216 |
42 | // Decrease the amount of tokens that an owner allowed to a spender.approve should be called when allowed_[_spender] == 0. To decrementallowed value is better to use this function to avoid 2 calls (and wait untilthe first transaction is mined)Emits an Approval event. spender The address which will spend the funds. value The amount of tokens to decrease the allowance by. / | function decrease_allowance(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowance[msg.sender][spender] = _allowance[msg.sender][spender].sub(value);
emit Approval(msg.sender, spender, _allowance[msg.sender][spender]);
return true;
}
| function decrease_allowance(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowance[msg.sender][spender] = _allowance[msg.sender][spender].sub(value);
emit Approval(msg.sender, spender, _allowance[msg.sender][spender]);
return true;
}
| 23,013 |
24 | // Adds a new contract that can create vesting positions | function setVester(address vester, bool status) public onlyOwner {
vesters[vester] = status;
emit LogVester(vester, status);
}
| function setVester(address vester, bool status) public onlyOwner {
vesters[vester] = status;
emit LogVester(vester, status);
}
| 59,142 |
139 | // Initialize the new money market name_ ERC-20 name of this token symbol_ ERC-20 symbol of this token decimals_ ERC-20 decimal precision of this token / | function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
| function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
| 24,907 |
29 | // first member, e.g. `struct { bytes data; }` | function pptr(
ReturndataPointer rdPtr
) internal pure returns (ReturndataPointer rdPtrChild) {
rdPtrChild = rdPtr.offset(rdPtr.readUint256() & OffsetOrLengthMask);
}
| function pptr(
ReturndataPointer rdPtr
) internal pure returns (ReturndataPointer rdPtrChild) {
rdPtrChild = rdPtr.offset(rdPtr.readUint256() & OffsetOrLengthMask);
}
| 12,632 |
4 | // return address of module factory / | function factory() external view virtual returns (address);
| function factory() external view virtual returns (address);
| 17,293 |
51 | // Push the branch into the list of new nodes. | newNodes[totalNewNodes] = newBranch;
totalNewNodes += 1;
| newNodes[totalNewNodes] = newBranch;
totalNewNodes += 1;
| 26,460 |
24 | // Change now. |
for (uint256 i = 0;
i < IAssetManager(registry.assetManager()).getIndexesByCategoryLength(category_);
++i) {
uint16 index = uint16(IAssetManager(registry.assetManager()).getIndexesByCategory(category_, i));
bool has = hasIndex(basketIndexes_, index);
if (has && !userBasket[_msgSender()][index]) {
userBasket[_msgSender()][index] = true;
} else if (!has && userBasket[_msgSender()][index]) {
|
for (uint256 i = 0;
i < IAssetManager(registry.assetManager()).getIndexesByCategoryLength(category_);
++i) {
uint16 index = uint16(IAssetManager(registry.assetManager()).getIndexesByCategory(category_, i));
bool has = hasIndex(basketIndexes_, index);
if (has && !userBasket[_msgSender()][index]) {
userBasket[_msgSender()][index] = true;
} else if (!has && userBasket[_msgSender()][index]) {
| 36,120 |
41 | // If the transfer fails then attempt to transfer from escrow instead. This should revert if `msg.sender` is not the owner of this NFT. | _transferFromEscrow(nftContract, tokenId, offer.buyer, msg.sender);
| _transferFromEscrow(nftContract, tokenId, offer.buyer, msg.sender);
| 30,009 |
7 | // Most of the math operations below are simple additions. In the places that there is more complex operation there is a comment explaining why it is safe. Also, byteslib operations have proper require. | unchecked {
bytes memory encoded = vm.payload;
(
uint index,
uint nAttestations,
uint attestationSize
) = parseBatchAttestationHeader(encoded);
| unchecked {
bytes memory encoded = vm.payload;
(
uint index,
uint nAttestations,
uint attestationSize
) = parseBatchAttestationHeader(encoded);
| 12,851 |
38 | // The amount to withdraw should not be more important than the perpetual's `cashOutAmount` and `margin` | (amount < cashOutAmount) &&
(amount < perpetual.margin) &&
| (amount < cashOutAmount) &&
(amount < perpetual.margin) &&
| 31,002 |
112 | // Wrappers over Solidity's uintXX/intXX casting operators with added overflowchecks. Downcasting from uint256/int256 in Solidity does not revert on overflow. This caneasily result in undesired exploitation or bugs, since developers usuallyassume that overflows raise errors. `SafeCast` restores this intuition byreverting the transaction when such an operation overflows. Using this library instead of the unchecked operations eliminates an entireclass of bugs, so it's recommended to use it always. | * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
| * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
| 6,937 |
31 | // There is no challenge against the proposal. The processBy date for the proposal has not passed, but the proposal's appExpirty date has passed. | set(prop.name, prop.value);
emit _ProposalAccepted(_propID, prop.name, prop.value);
delete proposals[_propID];
require(token.transfer(propOwner, propDeposit));
| set(prop.name, prop.value);
emit _ProposalAccepted(_propID, prop.name, prop.value);
delete proposals[_propID];
require(token.transfer(propOwner, propDeposit));
| 37,485 |
117 | // @live: | function getBalance(bytes32 _stashName) public isStashOwner(_stashName) constant returns (int) {
Stash stash = Stash(stashRegistry[_stashName]);
return stash.getBalance();
}
| function getBalance(bytes32 _stashName) public isStashOwner(_stashName) constant returns (int) {
Stash stash = Stash(stashRegistry[_stashName]);
return stash.getBalance();
}
| 32,593 |
372 | // Only execute cumulative factor logic after LIP-36 upgrade round After LIP-36 upgrade round the following code block should only be executed if _endRound is the current round See claimEarnings() and autoClaimEarnings() | if (_endRound >= lip36Round) {
| if (_endRound >= lip36Round) {
| 35,709 |
63 | // ITokenStorage Token storage interfaceCyril Lapinte - <[email protected]> / | abstract contract ITokenStorage {
enum TransferCode {
UNKNOWN,
OK,
INVALID_SENDER,
NO_RECIPIENT,
INSUFFICIENT_TOKENS,
LOCKED,
FROZEN,
RULE,
INVALID_RATE,
NON_REGISTRED_SENDER,
NON_REGISTRED_RECEIVER,
LIMITED_EMISSION,
LIMITED_RECEPTION
}
enum Scope {
DEFAULT
}
enum AuditStorageMode {
ADDRESS,
USER_ID,
SHARED
}
enum AuditTriggerMode {
UNDEFINED,
NONE,
SENDER_ONLY,
RECEIVER_ONLY,
BOTH
}
address internal constant ANY_ADDRESSES = address(0x416e79416464726573736573); // "AnyAddresses"
event OracleDefined(
IUserRegistry userRegistry,
IRatesProvider ratesProvider,
address currency);
event TokenDelegateDefined(uint256 indexed delegateId, address delegate, uint256[] configurations);
event TokenDelegateRemoved(uint256 indexed delegateId);
event AuditConfigurationDefined(
uint256 indexed configurationId,
uint256 scopeId,
AuditTriggerMode mode,
uint256[] senderKeys,
uint256[] receiverKeys,
IRatesProvider ratesProvider,
address currency);
event AuditTriggersDefined(
uint256 indexed configurationId,
address[] senders,
address[] receivers,
AuditTriggerMode[] modes);
event AuditsRemoved(address scope, uint256 scopeId);
event SelfManaged(address indexed holder, bool active);
event Minted(address indexed token, uint256 amount);
event MintFinished(address indexed token);
event Burned(address indexed token, uint256 amount);
event RulesDefined(address indexed token, IRule[] rules);
event LockDefined(
address indexed lock,
address sender,
address receiver,
uint256 startAt,
uint256 endAt
);
event Seize(address indexed token, address account, uint256 amount);
event Freeze(address address_, uint256 until);
event ClaimDefined(
address indexed token,
address indexed claim,
uint256 claimAt);
event TokenLocksDefined(
address indexed token,
address[] locks);
event TokenDefined(
address indexed token,
string name,
string symbol,
uint256 decimals);
event LogTransferData(
address token, address caller, address sender, address receiver,
uint256 senderId, uint256[] senderKeys, bool senderFetched,
uint256 receiverId, uint256[] receiverKeys, bool receiverFetched,
uint256 value, uint256 convertedValue);
event LogTransferAuditData(
uint256 auditConfigurationId, uint256 scopeId,
address currency, IRatesProvider ratesProvider,
bool senderAuditRequired, bool receiverAuditRequired);
event LogAuditData(
uint64 createdAt, uint64 lastTransactionAt,
uint256 cumulatedEmission, uint256 cumulatedReception
);
}
| abstract contract ITokenStorage {
enum TransferCode {
UNKNOWN,
OK,
INVALID_SENDER,
NO_RECIPIENT,
INSUFFICIENT_TOKENS,
LOCKED,
FROZEN,
RULE,
INVALID_RATE,
NON_REGISTRED_SENDER,
NON_REGISTRED_RECEIVER,
LIMITED_EMISSION,
LIMITED_RECEPTION
}
enum Scope {
DEFAULT
}
enum AuditStorageMode {
ADDRESS,
USER_ID,
SHARED
}
enum AuditTriggerMode {
UNDEFINED,
NONE,
SENDER_ONLY,
RECEIVER_ONLY,
BOTH
}
address internal constant ANY_ADDRESSES = address(0x416e79416464726573736573); // "AnyAddresses"
event OracleDefined(
IUserRegistry userRegistry,
IRatesProvider ratesProvider,
address currency);
event TokenDelegateDefined(uint256 indexed delegateId, address delegate, uint256[] configurations);
event TokenDelegateRemoved(uint256 indexed delegateId);
event AuditConfigurationDefined(
uint256 indexed configurationId,
uint256 scopeId,
AuditTriggerMode mode,
uint256[] senderKeys,
uint256[] receiverKeys,
IRatesProvider ratesProvider,
address currency);
event AuditTriggersDefined(
uint256 indexed configurationId,
address[] senders,
address[] receivers,
AuditTriggerMode[] modes);
event AuditsRemoved(address scope, uint256 scopeId);
event SelfManaged(address indexed holder, bool active);
event Minted(address indexed token, uint256 amount);
event MintFinished(address indexed token);
event Burned(address indexed token, uint256 amount);
event RulesDefined(address indexed token, IRule[] rules);
event LockDefined(
address indexed lock,
address sender,
address receiver,
uint256 startAt,
uint256 endAt
);
event Seize(address indexed token, address account, uint256 amount);
event Freeze(address address_, uint256 until);
event ClaimDefined(
address indexed token,
address indexed claim,
uint256 claimAt);
event TokenLocksDefined(
address indexed token,
address[] locks);
event TokenDefined(
address indexed token,
string name,
string symbol,
uint256 decimals);
event LogTransferData(
address token, address caller, address sender, address receiver,
uint256 senderId, uint256[] senderKeys, bool senderFetched,
uint256 receiverId, uint256[] receiverKeys, bool receiverFetched,
uint256 value, uint256 convertedValue);
event LogTransferAuditData(
uint256 auditConfigurationId, uint256 scopeId,
address currency, IRatesProvider ratesProvider,
bool senderAuditRequired, bool receiverAuditRequired);
event LogAuditData(
uint64 createdAt, uint64 lastTransactionAt,
uint256 cumulatedEmission, uint256 cumulatedReception
);
}
| 47,351 |
27 | // assumption: this can be caleld without gas - like a getter | function calculateCurrDynamicPrice() public view returns (uint){
uint currDynamicPrice;
uint periodLengthSecs=screenstate.PriceDecreasePeriodLengthSecs;
uint ellapsedPeriodsSinceLastBid= (now - screenstate.currTopBidTimeStamp)/periodLengthSecs;
uint totalDecrease=((screenstate.currTopBid*screenstate.periodPercentagePriceDecrease*ellapsedPeriodsSinceLastBid)/100);
if(totalDecrease>screenstate.currTopBid){
currDynamicPrice=0;
}else{
currDynamicPrice= screenstate.currTopBid-totalDecrease;
}
return currDynamicPrice;
}
| function calculateCurrDynamicPrice() public view returns (uint){
uint currDynamicPrice;
uint periodLengthSecs=screenstate.PriceDecreasePeriodLengthSecs;
uint ellapsedPeriodsSinceLastBid= (now - screenstate.currTopBidTimeStamp)/periodLengthSecs;
uint totalDecrease=((screenstate.currTopBid*screenstate.periodPercentagePriceDecrease*ellapsedPeriodsSinceLastBid)/100);
if(totalDecrease>screenstate.currTopBid){
currDynamicPrice=0;
}else{
currDynamicPrice= screenstate.currTopBid-totalDecrease;
}
return currDynamicPrice;
}
| 17,313 |
5,212 | // 2608 | entry "monogenically" : ENG_ADVERB
| entry "monogenically" : ENG_ADVERB
| 23,444 |
155 | // subtract SignedDecimal.signedDecimal by Decimal.decimal, using SignedSafeMath directly | function subD(SignedDecimal.signedDecimal memory x, Decimal.decimal memory y)
internal
pure
convertible(y)
returns (SignedDecimal.signedDecimal memory)
| function subD(SignedDecimal.signedDecimal memory x, Decimal.decimal memory y)
internal
pure
convertible(y)
returns (SignedDecimal.signedDecimal memory)
| 2,457 |
219 | // Gets the whole debt of the Safe/_safeEngine Address of Vat contract/_usr Address of the Dai holder/_urn Urn of the Safe/_collType CollType of the Safe | function getAllDebt(address _safeEngine, address _usr, address _urn, bytes32 _collType) internal view returns (uint daiAmount) {
(, uint rate,,,,) = ISAFEEngine(_safeEngine).collateralTypes(_collType);
(, uint art) = ISAFEEngine(_safeEngine).safes(_collType, _urn);
uint dai = ISAFEEngine(_safeEngine).coinBalance(_usr);
uint rad = sub(mul(art, rate), dai);
daiAmount = rad / RAY;
daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount;
}
| function getAllDebt(address _safeEngine, address _usr, address _urn, bytes32 _collType) internal view returns (uint daiAmount) {
(, uint rate,,,,) = ISAFEEngine(_safeEngine).collateralTypes(_collType);
(, uint art) = ISAFEEngine(_safeEngine).safes(_collType, _urn);
uint dai = ISAFEEngine(_safeEngine).coinBalance(_usr);
uint rad = sub(mul(art, rate), dai);
daiAmount = rad / RAY;
daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount;
}
| 26,010 |
20 | // Check if the order is fully fulfilled | if (order.availableTokens == 0) {
order.state = OrderState.Fulfilled;
}
| if (order.availableTokens == 0) {
order.state = OrderState.Fulfilled;
}
| 26,834 |