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 |
|---|---|---|---|---|
223 | // ends the round. manages paying out winner/splitting up pot / | function endRound(Star3Ddatasets.EventReturns memory _eventData_)
private
returns (Star3Ddatasets.EventReturns)
| function endRound(Star3Ddatasets.EventReturns memory _eventData_)
private
returns (Star3Ddatasets.EventReturns)
| 33,383 |
148 | // sell quote case quote input + base output | if (baseBalance < _BASE_RESERVE_) {
uint256 quoteInput = quoteBalance.sub(uint256(_QUOTE_RESERVE_));
(
uint256 receiveBaseAmount,
uint256 mtFee,
PMMPricing.RState newRState,
uint256 newQuoteTarget
) = querySellQuote(tx.origin, quoteInput); // revert if quoteBalance<quoteReserve
require(
uint256(_BASE_RESERVE_).sub(baseBalance) <= receiveBaseAmount,
| if (baseBalance < _BASE_RESERVE_) {
uint256 quoteInput = quoteBalance.sub(uint256(_QUOTE_RESERVE_));
(
uint256 receiveBaseAmount,
uint256 mtFee,
PMMPricing.RState newRState,
uint256 newQuoteTarget
) = querySellQuote(tx.origin, quoteInput); // revert if quoteBalance<quoteReserve
require(
uint256(_BASE_RESERVE_).sub(baseBalance) <= receiveBaseAmount,
| 66,823 |
190 | // Returns the downcasted int40 from int256, reverting onoverflow (when the input is less than smallest int40 orgreater than largest int40). Counterpart to Solidity's `int40` operator. Requirements: - input must fit into 40 bits _Available since v4.7._ / | function toInt40(int256 value) internal pure returns (int40) {
require(value >= type(int40).min && value <= type(int40).max, "SafeCast: value doesn't fit in 40 bits");
return int40(value);
}
| function toInt40(int256 value) internal pure returns (int40) {
require(value >= type(int40).min && value <= type(int40).max, "SafeCast: value doesn't fit in 40 bits");
return int40(value);
}
| 970 |
44 | // 给用户转账 | safeTransferUser(handle.user, amount);
| safeTransferUser(handle.user, amount);
| 17,323 |
30 | // Delegates vote to an address. _add is the address to delegate vote to. / | function delegateVote(address _add) external isMemberAndcheckPause checkPendingRewards {
require(ms.masterInitialized(),'not initialized.');
require(allDelegation[followerDelegation[_add]].leader == address(0),'already delegate');
if (followerDelegation[msg.sender] > 0) {
require((allDelegation[followerDelegation[msg.sender]].lastUpd).add(tokenHoldingTime) < now,'time ls now');
}
require(!alreadyDelegated(msg.sender),'already delegated');
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.Owner)),'only member');
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)),'only member');
require(followerCount[_add] < maxFollowers,'follower count over');
if (allVotesByMember[msg.sender].length > 0) {
require((allVotes[allVotesByMember[msg.sender][allVotesByMember[msg.sender].length - 1]].dateAdd).add(tokenHoldingTime)
< now,'time ls now');
}
require(ms.isMember(_add),'delegate only member');
require(isOpenForDelegation[_add],'delegate must open');
allDelegation.push(DelegateVote(msg.sender, _add, now));
followerDelegation[msg.sender] = allDelegation.length - 1;
leaderDelegation[_add].push(allDelegation.length - 1);
followerCount[_add]++;
lastRewardClaimed[msg.sender] = allVotesByMember[_add].length;
}
| function delegateVote(address _add) external isMemberAndcheckPause checkPendingRewards {
require(ms.masterInitialized(),'not initialized.');
require(allDelegation[followerDelegation[_add]].leader == address(0),'already delegate');
if (followerDelegation[msg.sender] > 0) {
require((allDelegation[followerDelegation[msg.sender]].lastUpd).add(tokenHoldingTime) < now,'time ls now');
}
require(!alreadyDelegated(msg.sender),'already delegated');
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.Owner)),'only member');
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)),'only member');
require(followerCount[_add] < maxFollowers,'follower count over');
if (allVotesByMember[msg.sender].length > 0) {
require((allVotes[allVotesByMember[msg.sender][allVotesByMember[msg.sender].length - 1]].dateAdd).add(tokenHoldingTime)
< now,'time ls now');
}
require(ms.isMember(_add),'delegate only member');
require(isOpenForDelegation[_add],'delegate must open');
allDelegation.push(DelegateVote(msg.sender, _add, now));
followerDelegation[msg.sender] = allDelegation.length - 1;
leaderDelegation[_add].push(allDelegation.length - 1);
followerCount[_add]++;
lastRewardClaimed[msg.sender] = allVotesByMember[_add].length;
}
| 12,043 |
15 | // 添加每日兑换 | function addDateInfo(uint256 _outTokenCapacity) public onlyOwner {
outTokenCapacity = _outTokenCapacity;
}
| function addDateInfo(uint256 _outTokenCapacity) public onlyOwner {
outTokenCapacity = _outTokenCapacity;
}
| 12,236 |
3 | // Emitted when Keep3rKeeperFundablewithdraw is called/_keeper The caller of Keep3rKeeperFundablewithdraw function/_bond The asset to withdraw from the bonding pool/_amount The amount of funds withdrawn | event Withdrawal(address indexed _keeper, address indexed _bond, uint256 _amount);
| event Withdrawal(address indexed _keeper, address indexed _bond, uint256 _amount);
| 393 |
66 | // Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. a a FixedPoint. b a uint256.return the difference of `a` and `b`. / | function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
| function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
| 5,276 |
211 | // Whether `a` is less than or equal to `b`. a an int256. b a FixedPoint.Signed.return True if `a <= b`, or False. / | function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
| function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
| 64,984 |
42 | // buy mining | function buyMiner()
public
payable
whenNotPaused
isNotBlackList(msg.sender)
| function buyMiner()
public
payable
whenNotPaused
isNotBlackList(msg.sender)
| 5,777 |
13 | // Present. | event Present(address indexed fromAddress, address indexed toAddress, uint256 amount, uint256 presentTime);
| event Present(address indexed fromAddress, address indexed toAddress, uint256 amount, uint256 presentTime);
| 32,742 |
36 | // Withdraw staked ApeCoin from the ApeCoin pool.If withdraw is total staked amount, performs an automatic claim. _amount Amount of ApeCoin / | function withdrawSelfApeCoin(uint256 _amount) external {
withdrawApeCoin(_amount, msg.sender);
}
| function withdrawSelfApeCoin(uint256 _amount) external {
withdrawApeCoin(_amount, msg.sender);
}
| 22,488 |
43 | // Ballot receipt record for a voter | struct Receipt {
// Whether or not a vote has been cast
bool hasVoted;
// Whether or not the voter supports the proposal
bool support;
// The number of votes the voter had, which were cast
uint256 votes;
}
| struct Receipt {
// Whether or not a vote has been cast
bool hasVoted;
// Whether or not the voter supports the proposal
bool support;
// The number of votes the voter had, which were cast
uint256 votes;
}
| 11,414 |
5 | // ========== USER METHODS ========== / | function mint() external payable nonReentrant whenNotPaused onlyOwner {
require(tx.origin == msg.sender, "Allowed for EOA only");
_mint(msg.sender, idTracker.current());
idTracker.increment();
}
| function mint() external payable nonReentrant whenNotPaused onlyOwner {
require(tx.origin == msg.sender, "Allowed for EOA only");
_mint(msg.sender, idTracker.current());
idTracker.increment();
}
| 53,846 |
43 | // Transfers vested tokens to the given account. account address of the vested user / | function releaseToken(address account) public {
require(account != address(0));
VestedToken storage vested = vestedUser[account];
uint256 unreleasedToken = _releasableAmount(account); // total releasable token currently
require(unreleasedToken>0);
vested.releasedToken = vested.releasedToken + (unreleasedToken);
DEVIToken.transfer(account,unreleasedToken);
emit TokenReleased(account, unreleasedToken);
}
| function releaseToken(address account) public {
require(account != address(0));
VestedToken storage vested = vestedUser[account];
uint256 unreleasedToken = _releasableAmount(account); // total releasable token currently
require(unreleasedToken>0);
vested.releasedToken = vested.releasedToken + (unreleasedToken);
DEVIToken.transfer(account,unreleasedToken);
emit TokenReleased(account, unreleasedToken);
}
| 30,714 |
149 | // Reserve claim ??? sushi.mint(devaddr, sushiReward.div(10)); sushi.mint(address(this), sushiReward); | pool.accEthyPerShare = pool.accEthyPerShare.add(ethyReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
| pool.accEthyPerShare = pool.accEthyPerShare.add(ethyReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
| 16,040 |
23 | // deposit - allow deposits to a lock/_lock hash of seed | function deposit(
bytes32 _lock
| function deposit(
bytes32 _lock
| 23,706 |
66 | // we check here all the fees to ensure that we don't have a scenario where one set of fees exceeds 33% | require(fbl_calculateStateFee(TransactionState.Sell, 100000) <= 33333, "ERC20Feeable: Sell Hardcap of 33% reached");
require(fbl_calculateStateFee(TransactionState.Buy, 100000) <= 33333, "ERC20Feeable: Buy Hardcap of 33% reached");
require(fbl_calculateStateFee(TransactionState.Normal, 100000) <= 33333, "ERC20Feeable: Norm Hardcap of 33% reached");
return true;
| require(fbl_calculateStateFee(TransactionState.Sell, 100000) <= 33333, "ERC20Feeable: Sell Hardcap of 33% reached");
require(fbl_calculateStateFee(TransactionState.Buy, 100000) <= 33333, "ERC20Feeable: Buy Hardcap of 33% reached");
require(fbl_calculateStateFee(TransactionState.Normal, 100000) <= 33333, "ERC20Feeable: Norm Hardcap of 33% reached");
return true;
| 37,169 |
32 | // solium-disable-next-line security/no-block-members | block.timestamp < crowdsales[_token].closingTime,
"Failed to buy token due to crowdsale is closed."
);
deposits[msg.sender][_token] = (
deposits[msg.sender][_token].add(msg.value)
);
crowdsales[_token].raised = crowdsales[_token].raised.add(msg.value);
emit TokenBought(msg.sender, _token, msg.value);
| block.timestamp < crowdsales[_token].closingTime,
"Failed to buy token due to crowdsale is closed."
);
deposits[msg.sender][_token] = (
deposits[msg.sender][_token].add(msg.value)
);
crowdsales[_token].raised = crowdsales[_token].raised.add(msg.value);
emit TokenBought(msg.sender, _token, msg.value);
| 82,000 |
9 | // Returns the downcasted int32 from int256, reverting onoverflow (when the input is less than smallest int32 orgreater 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);
}
| 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);
}
| 14,953 |
577 | // Reads the uint216 at `mPtr` in memory. | function readUint216(
MemoryPointer mPtr
| function readUint216(
MemoryPointer mPtr
| 33,706 |
0 | // Payments Event Emitter | contract PaymentModelEventEmitter {
event LogPaymentSent(address from, address to, uint amount);
event LogPaymentRecv(address from, address to, uint amount);
}
| contract PaymentModelEventEmitter {
event LogPaymentSent(address from, address to, uint amount);
event LogPaymentRecv(address from, address to, uint amount);
}
| 49,990 |
1 | // Name of collection // Symbol of collection // Price per token // Max per Tx // Maximum amount of tokens in collection // URI for the contract metadata // Public sale state // Total supply // Notify on sale state change // Notify on total supply change // For URI conversions / | ) ERC1155(_uri) PaymentSplitter(shareholders, shares) {}
/// @notice Sets public sale state
/// @param val The new value
function setSaleState(bool val) external onlyOwner {
saleActive = val;
emit SaleStateChanged(val);
}
| ) ERC1155(_uri) PaymentSplitter(shareholders, shares) {}
/// @notice Sets public sale state
/// @param val The new value
function setSaleState(bool val) external onlyOwner {
saleActive = val;
emit SaleStateChanged(val);
}
| 30,077 |
101 | // `updateValueAtNow` used to update the `balances` map and the/`totalSupplyHistory`/checkpoints The history of data being updated/_value The new number of tokens | function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1];
oldCheckPoint.value = uint128(_value);
}
}
| function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1];
oldCheckPoint.value = uint128(_value);
}
}
| 16,152 |
30 | // Has surplus | totalSurplus = totalSurplus.add(surplus);
| totalSurplus = totalSurplus.add(surplus);
| 27,964 |
36 | // Buy tokens from contract by sending ether | function buy() payable public {
require(!frozenAccount[msg.sender]);
require(msg.value > 0);
commission = msg.value/commissionRate; // % of wei tx
require(address(this).send(commission));
buyToken();
}
| function buy() payable public {
require(!frozenAccount[msg.sender]);
require(msg.value > 0);
commission = msg.value/commissionRate; // % of wei tx
require(address(this).send(commission));
buyToken();
}
| 28,629 |
24 | // Withdraw an amount of asset from the platform. _recipient Address to which the asset should be sent _asset Address of the asset _amountUnits of asset to withdraw / | function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external virtual;
| function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external virtual;
| 16,321 |
6 | // The Owned contract A contract with helpers for basic contract ownership. / | contract Owned {
address payable public owner;
address private pendingOwner;
event OwnershipTransferRequested(
address indexed from,
address indexed to
);
event OwnershipTransferred(
address indexed from,
address indexed to
);
constructor() public {
owner = msg.sender;
}
/**
* @dev Allows an owner to begin transferring ownership to a new address,
* pending.
*/
function transferOwnership(address _to)
external
onlyOwner()
{
pendingOwner = _to;
emit OwnershipTransferRequested(owner, _to);
}
/**
* @dev Allows an ownership transfer to be completed by the recipient.
*/
function acceptOwnership()
external
{
require(msg.sender == pendingOwner, "Must be proposed owner");
address oldOwner = owner;
owner = msg.sender;
pendingOwner = address(0);
emit OwnershipTransferred(oldOwner, msg.sender);
}
/**
* @dev Reverts if called by anyone other than the contract owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "Only callable by owner");
_;
}
}
| contract Owned {
address payable public owner;
address private pendingOwner;
event OwnershipTransferRequested(
address indexed from,
address indexed to
);
event OwnershipTransferred(
address indexed from,
address indexed to
);
constructor() public {
owner = msg.sender;
}
/**
* @dev Allows an owner to begin transferring ownership to a new address,
* pending.
*/
function transferOwnership(address _to)
external
onlyOwner()
{
pendingOwner = _to;
emit OwnershipTransferRequested(owner, _to);
}
/**
* @dev Allows an ownership transfer to be completed by the recipient.
*/
function acceptOwnership()
external
{
require(msg.sender == pendingOwner, "Must be proposed owner");
address oldOwner = owner;
owner = msg.sender;
pendingOwner = address(0);
emit OwnershipTransferred(oldOwner, msg.sender);
}
/**
* @dev Reverts if called by anyone other than the contract owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "Only callable by owner");
_;
}
}
| 29,065 |
7 | // Borrower is attempting to create or modify a loan such that their loan's quote token would be less than the pool's minimum debt amount. / | error AmountLTMinDebt();
| error AmountLTMinDebt();
| 39,855 |
26 | // Ensure token belongs to the caller/ | modifier isTokenOwner(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender , "caller is not token owner");
_;
}
| modifier isTokenOwner(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender , "caller is not token owner");
_;
}
| 556 |
109 | // DIP4GenesisBlock | function setStorageDIP4GenesisBlock(uint256 _block) internal {
eternalStorage().setUint(getStorageDIP4GenesisBlockKey(), _block);
}
| function setStorageDIP4GenesisBlock(uint256 _block) internal {
eternalStorage().setUint(getStorageDIP4GenesisBlockKey(), _block);
}
| 2,672 |
17 | // Determine whether all hosts have revealed their secret random numbers. | bool all_hosts_revealed = num_hosts == num_hosts_revealed;
| bool all_hosts_revealed = num_hosts == num_hosts_revealed;
| 11,917 |
96 | // buying can only begins as soon as the ownership has been transfer to the pendingOwner | require(owner==pendingOwner);
uint256 weiAmount = msg.value;
| require(owner==pendingOwner);
uint256 weiAmount = msg.value;
| 47,693 |
55 | // Returns the downcasted int136 from int256, reverting onoverflow (when the input is less than smallest int136 orgreater than largest int136). Counterpart to Solidity's `int136` operator. Requirements: - input must fit into 136 bits _Available since v4.7._ / | function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
}
| function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
}
| 32,167 |
80 | // A sample implementation of core ERC1155 function. | contract ERC1155 is IERC1155, ERC165, CommonConstants {
using SafeMath for uint256;
using Address for address;
// id => (owner => balance)
mapping (uint256 => mapping(address => uint256)) internal balances;
// owner => (operator => approved)
mapping (address => mapping(address => bool)) internal operatorApproval;
/////////////////////////////////////////// ERC165 //////////////////////////////////////////////
/*
bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
bytes4(keccak256("balanceOf(address,uint256)")) ^
bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
bytes4(keccak256("setApprovalForAll(address,bool)")) ^
bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
/////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////
constructor() public {
_registerInterface(INTERFACE_SIGNATURE_ERC1155);
}
/////////////////////////////////////////// ERC1155 //////////////////////////////////////////////
/**
@notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if balance of holder for token `_id` is lower than the `_value` sent.
MUST revert on any other error.
MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard).
After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _id ID of the token type
@param _value Transfer amount
@param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external {
require(_to != address(0x0), "_to must be non-zero.");
require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers.");
// SafeMath will throw with insuficient funds _from
// or if _id is not valid (balance will be 0)
balances[_id][_from] = balances[_id][_from].sub(_value);
balances[_id][_to] = _value.add(balances[_id][_to]);
// MUST emit event
emit TransferSingle(msg.sender, _from, _to, _id, _value);
// Now that the balance is updated and the event was emitted,
// call onERC1155Received if the destination is a contract.
if (_to.isContract()) {
_doSafeTransferAcceptanceCheck(msg.sender, _from, _to, _id, _value, _data);
}
}
/**
@notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if length of `_ids` is not the same as length of `_values`.
MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient.
MUST revert on any other error.
MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard).
Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc).
After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _ids IDs of each token type (order and length must match _values array)
@param _values Transfer amounts per token type (order and length must match _ids array)
@param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external {
// MUST Throw on errors
require(_to != address(0x0), "destination address must be non-zero.");
require(_ids.length == _values.length, "_ids and _values array lenght must match.");
require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers.");
for (uint256 i = 0; i < _ids.length; ++i) {
uint256 id = _ids[i];
uint256 value = _values[i];
// SafeMath will throw with insuficient funds _from
// or if _id is not valid (balance will be 0)
balances[id][_from] = balances[id][_from].sub(value);
balances[id][_to] = value.add(balances[id][_to]);
}
// Note: instead of the below batch versions of event and acceptance check you MAY have emitted a TransferSingle
// event and a subsequent call to _doSafeTransferAcceptanceCheck in above loop for each balance change instead.
// Or emitted a TransferSingle event for each in the loop and then the single _doSafeBatchTransferAcceptanceCheck below.
// However it is implemented the balance changes and events MUST match when a check (i.e. calling an external contract) is done.
// MUST emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _values);
// Now that the balances are updated and the events are emitted,
// call onERC1155BatchReceived if the destination is a contract.
if (_to.isContract()) {
_doSafeBatchTransferAcceptanceCheck(msg.sender, _from, _to, _ids, _values, _data);
}
}
/**
@notice Get the balance of an account's Tokens.
@param _owner The address of the token holder
@param _id ID of the Token
@return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id) external view returns (uint256) {
// The balance of any account can be calculated from the Transfer events history.
// However, since we need to keep the balances to validate transfer request,
// there is no extra cost to also privide a querry function.
return balances[_id][_owner];
}
/**
@notice Get the balance of multiple account/token pairs
@param _owners The addresses of the token holders
@param _ids ID of the Tokens
@return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory) {
require(_owners.length == _ids.length);
uint256[] memory balances_ = new uint256[](_owners.length);
for (uint256 i = 0; i < _owners.length; ++i) {
balances_[i] = balances[_ids[i]][_owners[i]];
}
return balances_;
}
/**
@notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
@dev MUST emit the ApprovalForAll event on success.
@param _operator Address to add to the set of authorized operators
@param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external {
operatorApproval[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
@notice Queries the approval status of an operator for a given owner.
@param _owner The owner of the Tokens
@param _operator Address of authorized operator
@return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator) external view returns (bool) {
return operatorApproval[_owner][_operator];
}
/////////////////////////////////////////// Internal //////////////////////////////////////////////
function _doSafeTransferAcceptanceCheck(address _operator, address _from, address _to, uint256 _id, uint256 _value, bytes memory _data) internal {
// If this was a hybrid standards solution you would have to check ERC165(_to).supportsInterface(0x4e2312e0) here but as this is a pure implementation of an ERC-1155 token set as recommended by
// the standard, it is not necessary. The below should revert in all failure cases i.e. _to isn't a receiver, or it is and either returns an unknown value or it reverts in the call to indicate non-acceptance.
// Note: if the below reverts in the onERC1155Received function of the _to address you will have an undefined revert reason returned rather than the one in the require test.
// If you want predictable revert reasons consider using low level _to.call() style instead so the revert does not bubble up and you can revert yourself on the ERC1155_ACCEPTED test.
require(ERC1155TokenReceiver(_to).onERC1155Received(_operator, _from, _id, _value, _data) == ERC1155_ACCEPTED, "contract returned an unknown value from onERC1155Received");
}
function _doSafeBatchTransferAcceptanceCheck(address _operator, address _from, address _to, uint256[] memory _ids, uint256[] memory _values, bytes memory _data) internal {
// If this was a hybrid standards solution you would have to check ERC165(_to).supportsInterface(0x4e2312e0) here but as this is a pure implementation of an ERC-1155 token set as recommended by
// the standard, it is not necessary. The below should revert in all failure cases i.e. _to isn't a receiver, or it is and either returns an unknown value or it reverts in the call to indicate non-acceptance.
// Note: if the below reverts in the onERC1155BatchReceived function of the _to address you will have an undefined revert reason returned rather than the one in the require test.
// If you want predictable revert reasons consider using low level _to.call() style instead so the revert does not bubble up and you can revert yourself on the ERC1155_BATCH_ACCEPTED test.
require(ERC1155TokenReceiver(_to).onERC1155BatchReceived(_operator, _from, _ids, _values, _data) == ERC1155_BATCH_ACCEPTED, "contract returned an unknown value from onERC1155BatchReceived");
}
}
| contract ERC1155 is IERC1155, ERC165, CommonConstants {
using SafeMath for uint256;
using Address for address;
// id => (owner => balance)
mapping (uint256 => mapping(address => uint256)) internal balances;
// owner => (operator => approved)
mapping (address => mapping(address => bool)) internal operatorApproval;
/////////////////////////////////////////// ERC165 //////////////////////////////////////////////
/*
bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
bytes4(keccak256("balanceOf(address,uint256)")) ^
bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
bytes4(keccak256("setApprovalForAll(address,bool)")) ^
bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
/////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////
constructor() public {
_registerInterface(INTERFACE_SIGNATURE_ERC1155);
}
/////////////////////////////////////////// ERC1155 //////////////////////////////////////////////
/**
@notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if balance of holder for token `_id` is lower than the `_value` sent.
MUST revert on any other error.
MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard).
After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _id ID of the token type
@param _value Transfer amount
@param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external {
require(_to != address(0x0), "_to must be non-zero.");
require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers.");
// SafeMath will throw with insuficient funds _from
// or if _id is not valid (balance will be 0)
balances[_id][_from] = balances[_id][_from].sub(_value);
balances[_id][_to] = _value.add(balances[_id][_to]);
// MUST emit event
emit TransferSingle(msg.sender, _from, _to, _id, _value);
// Now that the balance is updated and the event was emitted,
// call onERC1155Received if the destination is a contract.
if (_to.isContract()) {
_doSafeTransferAcceptanceCheck(msg.sender, _from, _to, _id, _value, _data);
}
}
/**
@notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if length of `_ids` is not the same as length of `_values`.
MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient.
MUST revert on any other error.
MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard).
Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc).
After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _ids IDs of each token type (order and length must match _values array)
@param _values Transfer amounts per token type (order and length must match _ids array)
@param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external {
// MUST Throw on errors
require(_to != address(0x0), "destination address must be non-zero.");
require(_ids.length == _values.length, "_ids and _values array lenght must match.");
require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers.");
for (uint256 i = 0; i < _ids.length; ++i) {
uint256 id = _ids[i];
uint256 value = _values[i];
// SafeMath will throw with insuficient funds _from
// or if _id is not valid (balance will be 0)
balances[id][_from] = balances[id][_from].sub(value);
balances[id][_to] = value.add(balances[id][_to]);
}
// Note: instead of the below batch versions of event and acceptance check you MAY have emitted a TransferSingle
// event and a subsequent call to _doSafeTransferAcceptanceCheck in above loop for each balance change instead.
// Or emitted a TransferSingle event for each in the loop and then the single _doSafeBatchTransferAcceptanceCheck below.
// However it is implemented the balance changes and events MUST match when a check (i.e. calling an external contract) is done.
// MUST emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _values);
// Now that the balances are updated and the events are emitted,
// call onERC1155BatchReceived if the destination is a contract.
if (_to.isContract()) {
_doSafeBatchTransferAcceptanceCheck(msg.sender, _from, _to, _ids, _values, _data);
}
}
/**
@notice Get the balance of an account's Tokens.
@param _owner The address of the token holder
@param _id ID of the Token
@return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id) external view returns (uint256) {
// The balance of any account can be calculated from the Transfer events history.
// However, since we need to keep the balances to validate transfer request,
// there is no extra cost to also privide a querry function.
return balances[_id][_owner];
}
/**
@notice Get the balance of multiple account/token pairs
@param _owners The addresses of the token holders
@param _ids ID of the Tokens
@return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory) {
require(_owners.length == _ids.length);
uint256[] memory balances_ = new uint256[](_owners.length);
for (uint256 i = 0; i < _owners.length; ++i) {
balances_[i] = balances[_ids[i]][_owners[i]];
}
return balances_;
}
/**
@notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
@dev MUST emit the ApprovalForAll event on success.
@param _operator Address to add to the set of authorized operators
@param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external {
operatorApproval[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
@notice Queries the approval status of an operator for a given owner.
@param _owner The owner of the Tokens
@param _operator Address of authorized operator
@return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator) external view returns (bool) {
return operatorApproval[_owner][_operator];
}
/////////////////////////////////////////// Internal //////////////////////////////////////////////
function _doSafeTransferAcceptanceCheck(address _operator, address _from, address _to, uint256 _id, uint256 _value, bytes memory _data) internal {
// If this was a hybrid standards solution you would have to check ERC165(_to).supportsInterface(0x4e2312e0) here but as this is a pure implementation of an ERC-1155 token set as recommended by
// the standard, it is not necessary. The below should revert in all failure cases i.e. _to isn't a receiver, or it is and either returns an unknown value or it reverts in the call to indicate non-acceptance.
// Note: if the below reverts in the onERC1155Received function of the _to address you will have an undefined revert reason returned rather than the one in the require test.
// If you want predictable revert reasons consider using low level _to.call() style instead so the revert does not bubble up and you can revert yourself on the ERC1155_ACCEPTED test.
require(ERC1155TokenReceiver(_to).onERC1155Received(_operator, _from, _id, _value, _data) == ERC1155_ACCEPTED, "contract returned an unknown value from onERC1155Received");
}
function _doSafeBatchTransferAcceptanceCheck(address _operator, address _from, address _to, uint256[] memory _ids, uint256[] memory _values, bytes memory _data) internal {
// If this was a hybrid standards solution you would have to check ERC165(_to).supportsInterface(0x4e2312e0) here but as this is a pure implementation of an ERC-1155 token set as recommended by
// the standard, it is not necessary. The below should revert in all failure cases i.e. _to isn't a receiver, or it is and either returns an unknown value or it reverts in the call to indicate non-acceptance.
// Note: if the below reverts in the onERC1155BatchReceived function of the _to address you will have an undefined revert reason returned rather than the one in the require test.
// If you want predictable revert reasons consider using low level _to.call() style instead so the revert does not bubble up and you can revert yourself on the ERC1155_BATCH_ACCEPTED test.
require(ERC1155TokenReceiver(_to).onERC1155BatchReceived(_operator, _from, _ids, _values, _data) == ERC1155_BATCH_ACCEPTED, "contract returned an unknown value from onERC1155BatchReceived");
}
}
| 5,637 |
13 | // Pools | IRewardDistributionRecipient uniPool = IRewardDistributionRecipient(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IRewardDistributionRecipient bptPool = IRewardDistributionRecipient(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
| IRewardDistributionRecipient uniPool = IRewardDistributionRecipient(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IRewardDistributionRecipient bptPool = IRewardDistributionRecipient(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
| 23,525 |
157 | // Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. / | function doTransferOut(address payable to, uint amount) internal virtual ;
| function doTransferOut(address payable to, uint amount) internal virtual ;
| 12,324 |
61 | // Change the RC end block number. _endBlock The end block / | function setEndBlock(uint256 _endBlock) external onlyOwner beforeEnd whenReserving {
require(_endBlock >= block.number, "_endBlock < current block");
require(_endBlock >= startBlock, "_endBlock < startBlock");
require(_endBlock != endBlock, "_endBlock == endBlock");
endBlock = _endBlock;
emit LogEndBlockChanged(_endBlock);
}
| function setEndBlock(uint256 _endBlock) external onlyOwner beforeEnd whenReserving {
require(_endBlock >= block.number, "_endBlock < current block");
require(_endBlock >= startBlock, "_endBlock < startBlock");
require(_endBlock != endBlock, "_endBlock == endBlock");
endBlock = _endBlock;
emit LogEndBlockChanged(_endBlock);
}
| 47,852 |
59 | // get fee for funder _funder address of funder to check fee / | function feeForFunder(address _funder) public view returns (uint256) {
FunderPortfolio memory tokenFunder = funders[_funder];
uint8 currentId = tokenFunder.class;
uint256 currentFee = classes[currentId].classFee;
return (seedAmountForFunder(_funder) * currentFee) / PRECISION;
}
| function feeForFunder(address _funder) public view returns (uint256) {
FunderPortfolio memory tokenFunder = funders[_funder];
uint8 currentId = tokenFunder.class;
uint256 currentFee = classes[currentId].classFee;
return (seedAmountForFunder(_funder) * currentFee) / PRECISION;
}
| 502 |
16 | // Changes the proportion of appeal fees that must be paid by winner and loser and changes the appeal period portion for losers._winnerStakeMultiplier The new winner stake multiplier value respect to DENOMINATOR._loserStakeMultiplier The new loser stake multiplier value respect to DENOMINATOR._loserAppealPeriodMultiplier The new loser appeal period multiplier respect to DENOMINATOR. Having a value greater than DENOMINATOR has no effect since arbitrator limits appeal period. / | function changeMultipliers(
uint256 _winnerStakeMultiplier,
uint256 _loserStakeMultiplier,
uint256 _loserAppealPeriodMultiplier
| function changeMultipliers(
uint256 _winnerStakeMultiplier,
uint256 _loserStakeMultiplier,
uint256 _loserAppealPeriodMultiplier
| 15,794 |
30 | // Set the beneficiary address of this contract. Only the contract owner may call this. The provided beneficiary must be non-null. _beneficiary The address to pay any eth contained in this contract to upon self-destruction. / | function setSelfDestructBeneficiary(address _beneficiary) external onlyOwner {
require(_beneficiary != address(0), "Beneficiary must not be zero");
selfDestructBeneficiary = _beneficiary;
emit SelfDestructBeneficiaryUpdated(_beneficiary);
}
| function setSelfDestructBeneficiary(address _beneficiary) external onlyOwner {
require(_beneficiary != address(0), "Beneficiary must not be zero");
selfDestructBeneficiary = _beneficiary;
emit SelfDestructBeneficiaryUpdated(_beneficiary);
}
| 530 |
17 | // Set the sell amount to the user's full balance, don't sell if empty | uint256 amount = tokenBalanceOf(_customerAddress);
require(amount > 0);
| uint256 amount = tokenBalanceOf(_customerAddress);
require(amount > 0);
| 21,109 |
8 | // shares.approve(address(controller), shares.balanceOf(address(this))); the fuck | controller.redeemShares();
| controller.redeemShares();
| 33,568 |
51 | // tokens remaining for ILO | uint private _availTokensILO;
| uint private _availTokensILO;
| 21,879 |
80 | // Current max wallet amount (If limits in effect) | uint256 public maxWallet;
| uint256 public maxWallet;
| 8,568 |
215 | // start off by borrowing or returning: | (bool borrowMore, uint256 amount) = internalCreditOfficer();
| (bool borrowMore, uint256 amount) = internalCreditOfficer();
| 30,669 |
0 | // Maximum uint256 | uint256 constant MAX_INT = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
using SafeMath for uint256;
string private _name;
string private _symbol;
uint256 private _totalSupply;
mapping(address => uint256) private balances;
mapping(address => mapping(address => uint256)) private allowed;
| uint256 constant MAX_INT = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
using SafeMath for uint256;
string private _name;
string private _symbol;
uint256 private _totalSupply;
mapping(address => uint256) private balances;
mapping(address => mapping(address => uint256)) private allowed;
| 4,502 |
2 | // Internal function to set the contract URI _contractURI string URI prefix to assign / | function _setContractURI(string memory _contractURI) internal {
contractURI = _contractURI;
}
| function _setContractURI(string memory _contractURI) internal {
contractURI = _contractURI;
}
| 36,585 |
102 | // See {IERC1155Inventory-isFungible(uint256)}. | function isFungible(uint256 id) external pure virtual override returns (bool) {
return id.isFungibleToken();
}
| function isFungible(uint256 id) external pure virtual override returns (bool) {
return id.isFungibleToken();
}
| 33,960 |
9 | // Adds a int256 value to the request with a given key name self The initialized request key The name of the key value The int256 value to add / | function addInt(
Request memory self,
string memory key,
int256 value
| function addInt(
Request memory self,
string memory key,
int256 value
| 15,410 |
0 | // Libraries | using SafeToken for address;
using SafeMath for uint256;
| using SafeToken for address;
using SafeMath for uint256;
| 29,058 |
10 | // Make sure the user was added at least `recoveryUserWaitTime` ago | (user.addedAt + recoveryUserWaitTime < block.timestamp) &&
| (user.addedAt + recoveryUserWaitTime < block.timestamp) &&
| 11,111 |
3 | // allowed draw ETH | bool public allowDraw = true;
| bool public allowDraw = true;
| 24,094 |
21 | // EIP20 Approval event / | event Approval(address indexed owner, address indexed spender, uint amount);
| event Approval(address indexed owner, address indexed spender, uint amount);
| 6,700 |
133 | // Paused stops new deposits and checkpoints | bool private paused;
address[] private rewardTokens;
mapping(address => TotalHarvestData) private rewardTokenToTotalHarvestData;
mapping(address => mapping(address => UserHarvestData)) private rewardTokenToUserToHarvestData;
| bool private paused;
address[] private rewardTokens;
mapping(address => TotalHarvestData) private rewardTokenToTotalHarvestData;
mapping(address => mapping(address => UserHarvestData)) private rewardTokenToUserToHarvestData;
| 60,739 |
193 | // Withdraw balance of this contract to the `wallet` address Used only if there are some leftoverfunds (because of topUpBalance)/ | function withdrawBalance() public mustBeAtStage(Stage.Finalized) {
wallet.transfer(this.balance);
}
| function withdrawBalance() public mustBeAtStage(Stage.Finalized) {
wallet.transfer(this.balance);
}
| 17,758 |
516 | // Decode a integer numeric value from a Result as an `int128` value. _result An instance of Result.return The `int128` decoded from the Result. / | function asInt128(Result memory _result) public pure returns(int128) {
require(_result.success, "Tried to read `int128` value from errored Result");
return _result.cborValue.decodeInt128();
}
| function asInt128(Result memory _result) public pure returns(int128) {
require(_result.success, "Tried to read `int128` value from errored Result");
return _result.cborValue.decodeInt128();
}
| 12,821 |
119 | // Minimum gain required to buy WETH is about 0.01 tokens |
if(gain >= minGain){
|
if(gain >= minGain){
| 44,009 |
34 | // Thrown if the account owner tries to transfer an unhealthy account | error CantTransferLiquidatableAccountException();
| error CantTransferLiquidatableAccountException();
| 28,733 |
7 | // 3. Call work to altering Vault position | Vault(_vault).work{ value: _msgValue }(_posId, _worker, _principalAmount, _borrowAmount, _maxReturn, _workData);
| Vault(_vault).work{ value: _msgValue }(_posId, _worker, _principalAmount, _borrowAmount, _maxReturn, _workData);
| 28,644 |
7 | // NonReceivableInitializedProxy Anna Carroll / | contract NonReceivableInitializedProxy {
// address of logic contract
address public immutable logic;
// ======== Constructor =========
constructor(address _logic, bytes memory _initializationCalldata) {
logic = _logic;
// Delegatecall into the logic contract, supplying initialization calldata
(bool _ok, bytes memory returnData) = _logic.delegatecall(
_initializationCalldata
);
// Revert if delegatecall to implementation reverts
require(_ok, string(returnData));
}
// ======== Fallback =========
fallback() external payable {
address _impl = logic;
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 {
revert(ptr, size)
}
default {
return(ptr, size)
}
}
}
} | contract NonReceivableInitializedProxy {
// address of logic contract
address public immutable logic;
// ======== Constructor =========
constructor(address _logic, bytes memory _initializationCalldata) {
logic = _logic;
// Delegatecall into the logic contract, supplying initialization calldata
(bool _ok, bytes memory returnData) = _logic.delegatecall(
_initializationCalldata
);
// Revert if delegatecall to implementation reverts
require(_ok, string(returnData));
}
// ======== Fallback =========
fallback() external payable {
address _impl = logic;
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 {
revert(ptr, size)
}
default {
return(ptr, size)
}
}
}
} | 38,954 |
173 | // Current price | ethAmount.mul(1e18).div(tokenAmount) :
| ethAmount.mul(1e18).div(tokenAmount) :
| 20,805 |
8 | // The percentage taken by the house on every game Can be changed later with the changeHouseCutPercentage() function / | uint public houseCutPercentage = 10;
| uint public houseCutPercentage = 10;
| 45,986 |
350 | // Returns the downcasted int184 from int256, reverting onoverflow (when the input is less than smallest int184 orgreater than largest int184). Counterpart to Solidity's `int184` operator. Requirements: - input must fit into 184 bits _Available since v4.7._ / | function toInt184(int256 value) internal pure returns (int184) {
require(value >= type(int184).min && value <= type(int184).max, "SafeCast: value doesn't fit in 184 bits");
return int184(value);
}
| function toInt184(int256 value) internal pure returns (int184) {
require(value >= type(int184).min && value <= type(int184).max, "SafeCast: value doesn't fit in 184 bits");
return int184(value);
}
| 7,562 |
27 | // Sends the last weis in this contract to the owner. These weis come fromthe imprecision in the ROI integer division, and would be otherwise stuckin this contract. Can be called only after all FUNDs have been redeemed. / | function drain()
public
onlyDuring(State.Finished)
onlyBy(owner)
| function drain()
public
onlyDuring(State.Finished)
onlyBy(owner)
| 4,970 |
33 | // bytes4(keccak256(bytes('transfer(address,uint256)'))); | (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'Helper::safeTransfer: transfer failed'
);
| (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'Helper::safeTransfer: transfer failed'
);
| 15,894 |
9 | // _TOKEN Address of TOKEN/_sTOKENAddress of sTOKEN/_epochLengthEpoch length/_secondsTillFirstEpochSeconds till first epoch starts | constructor(address _TOKEN, address _sTOKEN, uint256 _epochLength, uint256 _secondsTillFirstEpoch) {
require(_TOKEN != address(0), "Zero address: TOKEN");
TOKEN = IERC20(_TOKEN);
require(_sTOKEN != address(0), "Zero address");
sTOKEN = IsStakingProtocol(_sTOKEN);
epoch = Epoch({length: _epochLength, number: 0, end: block.timestamp + _secondsTillFirstEpoch, distribute: 0});
}
| constructor(address _TOKEN, address _sTOKEN, uint256 _epochLength, uint256 _secondsTillFirstEpoch) {
require(_TOKEN != address(0), "Zero address: TOKEN");
TOKEN = IERC20(_TOKEN);
require(_sTOKEN != address(0), "Zero address");
sTOKEN = IsStakingProtocol(_sTOKEN);
epoch = Epoch({length: _epochLength, number: 0, end: block.timestamp + _secondsTillFirstEpoch, distribute: 0});
}
| 1,002 |
19 | // voteForRequest - To vote for a new Functionality Request _requestName - Name of the Functionality Request _isUpvote - Is the vote an Upvote or Downvotereturns - Successful or not (true/false) / | function voteForRequest(string _requestName, bool _isUpvote)
isPOWRHolder
isValidVoter(_requestName)
| function voteForRequest(string _requestName, bool _isUpvote)
isPOWRHolder
isValidVoter(_requestName)
| 25,320 |
41 | // Save off the previous white list | uint8 previousWhitelist = addressWhitelists[addressToAdd[i]];
| uint8 previousWhitelist = addressWhitelists[addressToAdd[i]];
| 9,069 |
67 | // The address where all the funds will be stored/ | address public wallet;
| address public wallet;
| 6,996 |
15 | // Viewsfunction getSynthExchangeSuspensions(bytes32[] calldata synths)externalviewreturns (bool[] memory exchangeSuspensions, uint256[] memory reasons); |
function synthExchangeSuspension(bytes32 currencyKey)
external
view
returns (bool suspended, uint248 reason);
|
function synthExchangeSuspension(bytes32 currencyKey)
external
view
returns (bool suspended, uint248 reason);
| 45,472 |
40 | // Query a contract to see if it supports a certain interface/Returns `true` the interface is supported and `false` otherwise,/returns `true` for INTERFACE_SIGNATURE_ERC165 and/INTERFACE_SIGNATURE_ERC721, see ERC-165 for other interface signatures. | function supportsInterface(bytes4 _interfaceID) external pure returns (bool);
| function supportsInterface(bytes4 _interfaceID) external pure returns (bool);
| 29,384 |
25 | // Model for responses from oracles | struct ResponseInfo {
address requester; // Account that requested status
bool isOpen; // If open, oracle responses are accepted
mapping(uint8 => address[]) responses; // Mapping key is the status code reported
// This lets us group responses and identify
// the response that majority of the oracles
}
| struct ResponseInfo {
address requester; // Account that requested status
bool isOpen; // If open, oracle responses are accepted
mapping(uint8 => address[]) responses; // Mapping key is the status code reported
// This lets us group responses and identify
// the response that majority of the oracles
}
| 306 |
0 | // The premia token | IERC20 public premia;
| IERC20 public premia;
| 52,900 |
52 | // swap and liquify at 0.025% of initialSupply | uint256 public minimumTokensBeforeSwap = initialSupply * 250 / 1000000;
address public liquidityWallet;
address public operationsWallet;
address public buyBackWallet;
address public charityWallet;
| uint256 public minimumTokensBeforeSwap = initialSupply * 250 / 1000000;
address public liquidityWallet;
address public operationsWallet;
address public buyBackWallet;
address public charityWallet;
| 46,156 |
122 | // provide token1 and token2 to SUSHI | IERC20(uniLPComponentToken0).safeApprove(sushiswapRouterV2, 0);
IERC20(uniLPComponentToken0).safeApprove(sushiswapRouterV2, token0Amount);
IERC20(uniLPComponentToken1).safeApprove(sushiswapRouterV2, 0);
IERC20(uniLPComponentToken1).safeApprove(sushiswapRouterV2, token1Amount);
| IERC20(uniLPComponentToken0).safeApprove(sushiswapRouterV2, 0);
IERC20(uniLPComponentToken0).safeApprove(sushiswapRouterV2, token0Amount);
IERC20(uniLPComponentToken1).safeApprove(sushiswapRouterV2, 0);
IERC20(uniLPComponentToken1).safeApprove(sushiswapRouterV2, token1Amount);
| 33,174 |
180 | // It will deposit tokens into the locker for given beneficiary./beneficiary Address of the beneficiary, whose tokens are being locked./amount Amount of tokens being locked | function deposit (address beneficiary, uint amount ) public onlyAuction preLock {
uint totalBalance = token.balanceOf(this);
require(totalBalance.sub(deposited) >= amount);
deposited = deposited.add(amount);
emit Deposited(beneficiary, amount);
}
| function deposit (address beneficiary, uint amount ) public onlyAuction preLock {
uint totalBalance = token.balanceOf(this);
require(totalBalance.sub(deposited) >= amount);
deposited = deposited.add(amount);
emit Deposited(beneficiary, amount);
}
| 4,651 |
94 | // Nodes This contract contains all logic to manage SKALE Network nodes states,space availability, stake requirement checks, and exit functions.Nodes may be in one of several states:- Active:Node is registered and is in network operation.- Leaving: Node has begun exiting from the network.- Left:Node has left the network.- In_Maintenance:Node is temporarily offline or undergoing infrastructuremaintenanceNote: Online nodes contain both Active and Leaving states. / | contract Nodes is Permissions, INodes {
import "./Permissions.sol";
import "./ConstantsHolder.sol";
import "./utils/Random.sol";
import "./utils/SegmentTree.sol";
import "./NodeRotation.sol";
using Random for IRandom.RandomGenerator;
using SafeCastUpgradeable for uint;
using SegmentTree for SegmentTree.Tree;
bytes32 constant public COMPLIANCE_ROLE = keccak256("COMPLIANCE_ROLE");
bytes32 public constant NODE_MANAGER_ROLE = keccak256("NODE_MANAGER_ROLE");
// array which contain all Nodes
Node[] public nodes;
SpaceManaging[] public spaceOfNodes;
// mapping for checking which Nodes and which number of Nodes owned by user
mapping (address => CreatedNodes) public nodeIndexes;
// mapping for checking is IP address busy
mapping (bytes4 => bool) public nodesIPCheck;
// mapping for checking is Name busy
mapping (bytes32 => bool) public nodesNameCheck;
// mapping for indication from Name to Index
mapping (bytes32 => uint) public nodesNameToIndex;
// mapping for indication from space to Nodes
mapping (uint8 => uint[]) public spaceToNodes;
mapping (uint => uint[]) public validatorToNodeIndexes;
uint public override numberOfActiveNodes;
uint public numberOfLeavingNodes;
uint public numberOfLeftNodes;
mapping (uint => string) public domainNames;
mapping (uint => bool) private _invisible;
SegmentTree.Tree private _nodesAmountBySpace;
mapping (uint => bool) public override incompliant;
modifier checkNodeExists(uint nodeIndex) {
_checkNodeIndex(nodeIndex);
_;
}
modifier onlyNodeOrNodeManager(uint nodeIndex) {
_checkNodeOrNodeManager(nodeIndex, msg.sender);
_;
}
modifier onlyCompliance() {
require(hasRole(COMPLIANCE_ROLE, msg.sender), "COMPLIANCE_ROLE is required");
_;
}
modifier nonZeroIP(bytes4 ip) {
require(ip != 0x0 && !nodesIPCheck[ip], "IP address is zero or is not available");
_;
}
/**
* @dev Allows Schains and SchainsInternal contracts to occupy available
* space on a node.
*
* Returns whether operation is successful.
*/
function removeSpaceFromNode(uint nodeIndex, uint8 space)
external
override
checkNodeExists(nodeIndex)
allowTwo("NodeRotation", "SchainsInternal")
returns (bool)
{
if (spaceOfNodes[nodeIndex].freeSpace < space) {
return false;
}
if (space > 0) {
_moveNodeToNewSpaceMap(
nodeIndex,
(uint(spaceOfNodes[nodeIndex].freeSpace) - space).toUint8()
);
}
return true;
}
/**
* @dev Allows Schains contract to occupy free space on a node.
*
* Returns whether operation is successful.
*/
function addSpaceToNode(uint nodeIndex, uint8 space)
external
override
checkNodeExists(nodeIndex)
allow("SchainsInternal")
{
if (space > 0) {
_moveNodeToNewSpaceMap(
nodeIndex,
(uint(spaceOfNodes[nodeIndex].freeSpace) + space).toUint8()
);
}
}
/**
* @dev Allows SkaleManager to change a node's last reward date.
*/
function changeNodeLastRewardDate(uint nodeIndex)
external
override
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
nodes[nodeIndex].lastRewardDate = block.timestamp;
}
/**
* @dev Allows SkaleManager to change a node's finish time.
*/
function changeNodeFinishTime(uint nodeIndex, uint time)
external
override
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
nodes[nodeIndex].finishTime = time;
}
/**
* @dev Allows SkaleManager contract to create new node and add it to the
* Nodes contract.
*
* Emits a {NodeCreated} event.
*
* Requirements:
*
* - Node IP must be non-zero.
* - Node IP must be available.
* - Node name must not already be registered.
* - Node port must be greater than zero.
*/
function createNode(address from, NodeCreationParams calldata params)
external
override
allow("SkaleManager")
nonZeroIP(params.ip)
{
// checks that Node has correct data
require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered");
require(params.port > 0, "Port is zero");
require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect");
uint validatorId = IValidatorService(
contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from);
uint8 totalSpace = ConstantsHolder(contractManager.getContract("ConstantsHolder")).TOTAL_SPACE_ON_NODE();
nodes.push(Node({
name: params.name,
ip: params.ip,
publicIP: params.publicIp,
port: params.port,
publicKey: params.publicKey,
startBlock: block.number,
lastRewardDate: block.timestamp,
finishTime: 0,
status: NodeStatus.Active,
validatorId: validatorId
}));
uint nodeIndex = nodes.length - 1;
validatorToNodeIndexes[validatorId].push(nodeIndex);
bytes32 nodeId = keccak256(abi.encodePacked(params.name));
nodesIPCheck[params.ip] = true;
nodesNameCheck[nodeId] = true;
nodesNameToIndex[nodeId] = nodeIndex;
nodeIndexes[from].isNodeExist[nodeIndex] = true;
nodeIndexes[from].numberOfNodes++;
domainNames[nodeIndex] = params.domainName;
spaceOfNodes.push(SpaceManaging({
freeSpace: totalSpace,
indexInSpaceMap: spaceToNodes[totalSpace].length
}));
_setNodeActive(nodeIndex);
emit NodeCreated(
nodeIndex,
from,
params.name,
params.ip,
params.publicIp,
params.port,
params.nonce,
params.domainName);
}
/**
* @dev Allows NODE_MANAGER_ROLE to initiate a node exit procedure.
*
* Returns whether the operation is successful.
*
* Emits an {ExitInitialized} event.
*/
function initExit(uint nodeIndex)
external
override
checkNodeExists(nodeIndex)
{
require(hasRole(NODE_MANAGER_ROLE, msg.sender), "NODE_MANAGER_ROLE is required");
require(isNodeActive(nodeIndex), "Node should be Active");
_setNodeLeaving(nodeIndex);
NodeRotation(contractManager.getContract("NodeRotation")).freezeSchains(nodeIndex);
emit ExitInitialized(nodeIndex, block.timestamp);
}
/**
* @dev Allows SkaleManager contract to complete a node exit procedure.
*
* Returns whether the operation is successful.
*
* Emits an {ExitCompleted} event.
*
* Requirements:
*
* - Node must have already initialized a node exit procedure.
*/
function completeExit(uint nodeIndex)
external
override
checkNodeExists(nodeIndex)
allow("SkaleManager")
returns (bool)
{
require(isNodeLeaving(nodeIndex), "Node is not Leaving");
_setNodeLeft(nodeIndex);
emit ExitCompleted(nodeIndex);
return true;
}
/**
* @dev Allows SkaleManager contract to delete a validator's node.
*
* Requirements:
*
* - Validator ID must exist.
*/
function deleteNodeForValidator(uint validatorId, uint nodeIndex)
external
override
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
IValidatorService validatorService = IValidatorService(contractManager.getValidatorService());
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
uint[] memory validatorNodes = validatorToNodeIndexes[validatorId];
uint position = _findNode(validatorNodes, nodeIndex);
if (position < validatorNodes.length) {
validatorToNodeIndexes[validatorId][position] =
validatorToNodeIndexes[validatorId][validatorNodes.length - 1];
}
validatorToNodeIndexes[validatorId].pop();
address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey);
if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) {
if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) {
validatorService.removeNodeAddress(validatorId, nodeOwner);
}
nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false;
nodeIndexes[nodeOwner].numberOfNodes--;
}
}
/**
* @dev Allows SkaleManager contract to check whether a validator has
* sufficient stake to create another node.
*
* Requirements:
*
* - Validator must be included on trusted list if trusted list is enabled.
* - Validator must have sufficient stake to operate an additional node.
*/
function checkPossibilityCreatingNode(address nodeAddress) external override allow("SkaleManager") {
IValidatorService validatorService = IValidatorService(contractManager.getValidatorService());
uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress);
require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node");
require(
_checkValidatorPositionToMaintainNode(validatorId, validatorToNodeIndexes[validatorId].length),
"Validator must meet the Minimum Staking Requirement");
}
/**
* @dev Allows SkaleManager contract to check whether a validator has
* sufficient stake to maintain a node.
*
* Returns whether validator can maintain node with current stake.
*
* Requirements:
*
* - Validator ID and nodeIndex must both exist.
*/
function checkPossibilityToMaintainNode(
uint validatorId,
uint nodeIndex
)
external
override
checkNodeExists(nodeIndex)
allow("Bounty")
returns (bool)
{
IValidatorService validatorService = IValidatorService(contractManager.getValidatorService());
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
uint[] memory validatorNodes = validatorToNodeIndexes[validatorId];
uint position = _findNode(validatorNodes, nodeIndex);
require(position < validatorNodes.length, "Node does not exist for this Validator");
return _checkValidatorPositionToMaintainNode(validatorId, position);
}
/**
* @dev Allows Node to set In_Maintenance status.
*
* Requirements:
*
* - Node must already be Active.
* - `msg.sender` must be owner of Node, validator, or SkaleManager.
*/
function setNodeInMaintenance(uint nodeIndex) external override onlyNodeOrNodeManager(nodeIndex) {
require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active");
_setNodeInMaintenance(nodeIndex);
emit MaintenanceNode(nodeIndex, true);
}
/**
* @dev Allows Node to remove In_Maintenance status.
*
* Requirements:
*
* - Node must already be In Maintenance.
* - `msg.sender` must be owner of Node, validator, or SkaleManager.
*/
function removeNodeFromInMaintenance(uint nodeIndex) external override onlyNodeOrNodeManager(nodeIndex) {
require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance");
_setNodeActive(nodeIndex);
emit MaintenanceNode(nodeIndex, false);
}
/**
* @dev Marks the node as incompliant
*
*/
function setNodeIncompliant(uint nodeIndex) external override onlyCompliance checkNodeExists(nodeIndex) {
if (!incompliant[nodeIndex]) {
incompliant[nodeIndex] = true;
_makeNodeInvisible(nodeIndex);
emit IncompliantNode(nodeIndex, true);
}
}
/**
* @dev Marks the node as compliant
*
*/
function setNodeCompliant(uint nodeIndex) external override onlyCompliance checkNodeExists(nodeIndex) {
if (incompliant[nodeIndex]) {
incompliant[nodeIndex] = false;
_tryToMakeNodeVisible(nodeIndex);
emit IncompliantNode(nodeIndex, false);
}
}
function setDomainName(uint nodeIndex, string memory domainName)
external
override
onlyNodeOrNodeManager(nodeIndex)
{
domainNames[nodeIndex] = domainName;
}
function makeNodeVisible(uint nodeIndex) external override allow("SchainsInternal") {
_tryToMakeNodeVisible(nodeIndex);
}
function makeNodeInvisible(uint nodeIndex) external override allow("SchainsInternal") {
_makeNodeInvisible(nodeIndex);
}
function changeIP(
uint nodeIndex,
bytes4 newIP,
bytes4 newPublicIP
)
external
override
onlyAdmin
checkNodeExists(nodeIndex)
nonZeroIP(newIP)
{
if (newPublicIP != 0x0) {
require(newIP == newPublicIP, "IP address is not the same");
nodes[nodeIndex].publicIP = newPublicIP;
}
nodesIPCheck[nodes[nodeIndex].ip] = false;
nodesIPCheck[newIP] = true;
emit IPChanged(nodeIndex, nodes[nodeIndex].ip, newIP);
nodes[nodeIndex].ip = newIP;
}
function getRandomNodeWithFreeSpace(
uint8 freeSpace,
IRandom.RandomGenerator memory randomGenerator
)
external
view
override
returns (uint)
{
uint8 place = _nodesAmountBySpace.getRandomNonZeroElementFromPlaceToLast(
freeSpace == 0 ? 1 : freeSpace,
randomGenerator
).toUint8();
require(place > 0, "Node not found");
return spaceToNodes[place][randomGenerator.random(spaceToNodes[place].length)];
}
/**
* @dev Checks whether it is time for a node's reward.
*/
function isTimeForReward(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (bool)
{
return IBountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= block.timestamp;
}
/**
* @dev Returns IP address of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodeIP(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (bytes4)
{
require(nodeIndex < nodes.length, "Node does not exist");
return nodes[nodeIndex].ip;
}
/**
* @dev Returns domain name of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodeDomainName(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (string memory)
{
return domainNames[nodeIndex];
}
/**
* @dev Returns the port of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodePort(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (uint16)
{
return nodes[nodeIndex].port;
}
/**
* @dev Returns the public key of a given node.
*/
function getNodePublicKey(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (bytes32[2] memory)
{
return nodes[nodeIndex].publicKey;
}
/**
* @dev Returns an address of a given node.
*/
function getNodeAddress(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (address)
{
return _publicKeyToAddress(nodes[nodeIndex].publicKey);
}
/**
* @dev Returns the finish exit time of a given node.
*/
function getNodeFinishTime(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].finishTime;
}
/**
* @dev Checks whether a node has left the network.
*/
function isNodeLeft(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Left;
}
function isNodeInMaintenance(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.In_Maintenance;
}
/**
* @dev Returns a given node's last reward date.
*/
function getNodeLastRewardDate(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].lastRewardDate;
}
/**
* @dev Returns a given node's next reward date.
*/
function getNodeNextRewardDate(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (uint)
{
return IBountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex);
}
/**
* @dev Returns the total number of registered nodes.
*/
function getNumberOfNodes() external view override returns (uint) {
return nodes.length;
}
/**
* @dev Returns the total number of online nodes.
*
* Note: Online nodes are equal to the number of active plus leaving nodes.
*/
function getNumberOnlineNodes() external view override returns (uint) {
return numberOfActiveNodes + numberOfLeavingNodes ;
}
/**
* @dev Return active node IDs.
*/
function getActiveNodeIds() external view override returns (uint[] memory activeNodeIds) {
activeNodeIds = new uint[](numberOfActiveNodes);
uint indexOfActiveNodeIds = 0;
for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) {
if (isNodeActive(indexOfNodes)) {
activeNodeIds[indexOfActiveNodeIds] = indexOfNodes;
indexOfActiveNodeIds++;
}
}
}
/**
* @dev Return a given node's current status.
*/
function getNodeStatus(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (NodeStatus)
{
return nodes[nodeIndex].status;
}
/**
* @dev Return a validator's linked nodes.
*
* Requirements:
*
* - Validator ID must exist.
*/
function getValidatorNodeIndexes(uint validatorId) external view override returns (uint[] memory) {
IValidatorService validatorService = IValidatorService(contractManager.getValidatorService());
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
return validatorToNodeIndexes[validatorId];
}
/**
* @dev Returns number of nodes with available space.
*/
function countNodesWithFreeSpace(uint8 freeSpace) external view override returns (uint count) {
if (freeSpace == 0) {
return _nodesAmountBySpace.sumFromPlaceToLast(1);
}
return _nodesAmountBySpace.sumFromPlaceToLast(freeSpace);
}
/**
* @dev constructor in Permissions approach.
*/
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
numberOfActiveNodes = 0;
numberOfLeavingNodes = 0;
numberOfLeftNodes = 0;
_nodesAmountBySpace.create(128);
}
/**
* @dev Returns the Validator ID for a given node.
*/
function getValidatorId(uint nodeIndex)
public
view
override
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].validatorId;
}
/**
* @dev Checks whether a node exists for a given address.
*/
function isNodeExist(address from, uint nodeIndex)
public
view
override
checkNodeExists(nodeIndex)
returns (bool)
{
return nodeIndexes[from].isNodeExist[nodeIndex];
}
/**
* @dev Checks whether a node's status is Active.
*/
function isNodeActive(uint nodeIndex)
public
view
override
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Active;
}
/**
* @dev Checks whether a node's status is Leaving.
*/
function isNodeLeaving(uint nodeIndex)
public
view
override
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Leaving;
}
function _removeNodeFromSpaceToNodes(uint nodeIndex, uint8 space) internal {
uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap;
uint len = spaceToNodes[space].length - 1;
if (indexInArray < len) {
uint shiftedIndex = spaceToNodes[space][len];
spaceToNodes[space][indexInArray] = shiftedIndex;
spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray;
}
spaceToNodes[space].pop();
delete spaceOfNodes[nodeIndex].indexInSpaceMap;
}
/**
* @dev Moves a node to a new space mapping.
*/
function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private {
if (!_invisible[nodeIndex]) {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_removeNodeFromTree(space);
_addNodeToTree(newSpace);
_removeNodeFromSpaceToNodes(nodeIndex, space);
_addNodeToSpaceToNodes(nodeIndex, newSpace);
}
spaceOfNodes[nodeIndex].freeSpace = newSpace;
}
/**
* @dev Changes a node's status to Active.
*/
function _setNodeActive(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.Active;
numberOfActiveNodes = numberOfActiveNodes + 1;
if (_invisible[nodeIndex]) {
_tryToMakeNodeVisible(nodeIndex);
} else {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_addNodeToSpaceToNodes(nodeIndex, space);
_addNodeToTree(space);
}
}
/**
* @dev Changes a node's status to In_Maintenance.
*/
function _setNodeInMaintenance(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.In_Maintenance;
numberOfActiveNodes = numberOfActiveNodes - 1;
_makeNodeInvisible(nodeIndex);
}
/**
* @dev Changes a node's status to Left.
*/
function _setNodeLeft(uint nodeIndex) private {
nodesIPCheck[nodes[nodeIndex].ip] = false;
nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false;
delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))];
if (nodes[nodeIndex].status == NodeStatus.Active) {
numberOfActiveNodes--;
} else {
numberOfLeavingNodes--;
}
nodes[nodeIndex].status = NodeStatus.Left;
numberOfLeftNodes++;
delete spaceOfNodes[nodeIndex].freeSpace;
}
/**
* @dev Changes a node's status to Leaving.
*/
function _setNodeLeaving(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.Leaving;
numberOfActiveNodes--;
numberOfLeavingNodes++;
_makeNodeInvisible(nodeIndex);
}
function _makeNodeInvisible(uint nodeIndex) private {
if (!_invisible[nodeIndex]) {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_removeNodeFromSpaceToNodes(nodeIndex, space);
_removeNodeFromTree(space);
_invisible[nodeIndex] = true;
}
}
function _tryToMakeNodeVisible(uint nodeIndex) private {
if (_invisible[nodeIndex] && _canBeVisible(nodeIndex)) {
_makeNodeVisible(nodeIndex);
}
}
function _makeNodeVisible(uint nodeIndex) private {
if (_invisible[nodeIndex]) {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_addNodeToSpaceToNodes(nodeIndex, space);
_addNodeToTree(space);
delete _invisible[nodeIndex];
}
}
function _addNodeToSpaceToNodes(uint nodeIndex, uint8 space) private {
spaceToNodes[space].push(nodeIndex);
spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[space].length - 1;
}
function _addNodeToTree(uint8 space) private {
if (space > 0) {
_nodesAmountBySpace.addToPlace(space, 1);
}
}
function _removeNodeFromTree(uint8 space) private {
if (space > 0) {
_nodesAmountBySpace.removeFromPlace(space, 1);
}
}
function _checkValidatorPositionToMaintainNode(uint validatorId, uint position) private returns (bool) {
IDelegationController delegationController = IDelegationController(
contractManager.getContract("DelegationController")
);
uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId);
uint msr = IConstantsHolder(contractManager.getConstantsHolder()).msr();
return (position + 1) * msr <= delegationsTotal;
}
function _checkNodeIndex(uint nodeIndex) private view {
require(nodeIndex < nodes.length, "Node with such index does not exist");
}
function _checkNodeOrNodeManager(uint nodeIndex, address sender) private view {
IValidatorService validatorService = IValidatorService(contractManager.getValidatorService());
require(
isNodeExist(sender, nodeIndex) ||
hasRole(NODE_MANAGER_ROLE, msg.sender) ||
getValidatorId(nodeIndex) == validatorService.getValidatorId(sender),
"Sender is not permitted to call this function"
);
}
function _canBeVisible(uint nodeIndex) private view returns (bool) {
return !incompliant[nodeIndex] && nodes[nodeIndex].status == NodeStatus.Active;
}
/**
* @dev Returns the index of a given node within the validator's node index.
*/
function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) {
uint i;
for (i = 0; i < validatorNodeIndexes.length; i++) {
if (validatorNodeIndexes[i] == nodeIndex) {
return i;
}
}
return validatorNodeIndexes.length;
}
function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) {
bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1]));
bytes20 addr;
for (uint8 i = 12; i < 32; i++) {
addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8);
}
return address(addr);
}
}
| contract Nodes is Permissions, INodes {
import "./Permissions.sol";
import "./ConstantsHolder.sol";
import "./utils/Random.sol";
import "./utils/SegmentTree.sol";
import "./NodeRotation.sol";
using Random for IRandom.RandomGenerator;
using SafeCastUpgradeable for uint;
using SegmentTree for SegmentTree.Tree;
bytes32 constant public COMPLIANCE_ROLE = keccak256("COMPLIANCE_ROLE");
bytes32 public constant NODE_MANAGER_ROLE = keccak256("NODE_MANAGER_ROLE");
// array which contain all Nodes
Node[] public nodes;
SpaceManaging[] public spaceOfNodes;
// mapping for checking which Nodes and which number of Nodes owned by user
mapping (address => CreatedNodes) public nodeIndexes;
// mapping for checking is IP address busy
mapping (bytes4 => bool) public nodesIPCheck;
// mapping for checking is Name busy
mapping (bytes32 => bool) public nodesNameCheck;
// mapping for indication from Name to Index
mapping (bytes32 => uint) public nodesNameToIndex;
// mapping for indication from space to Nodes
mapping (uint8 => uint[]) public spaceToNodes;
mapping (uint => uint[]) public validatorToNodeIndexes;
uint public override numberOfActiveNodes;
uint public numberOfLeavingNodes;
uint public numberOfLeftNodes;
mapping (uint => string) public domainNames;
mapping (uint => bool) private _invisible;
SegmentTree.Tree private _nodesAmountBySpace;
mapping (uint => bool) public override incompliant;
modifier checkNodeExists(uint nodeIndex) {
_checkNodeIndex(nodeIndex);
_;
}
modifier onlyNodeOrNodeManager(uint nodeIndex) {
_checkNodeOrNodeManager(nodeIndex, msg.sender);
_;
}
modifier onlyCompliance() {
require(hasRole(COMPLIANCE_ROLE, msg.sender), "COMPLIANCE_ROLE is required");
_;
}
modifier nonZeroIP(bytes4 ip) {
require(ip != 0x0 && !nodesIPCheck[ip], "IP address is zero or is not available");
_;
}
/**
* @dev Allows Schains and SchainsInternal contracts to occupy available
* space on a node.
*
* Returns whether operation is successful.
*/
function removeSpaceFromNode(uint nodeIndex, uint8 space)
external
override
checkNodeExists(nodeIndex)
allowTwo("NodeRotation", "SchainsInternal")
returns (bool)
{
if (spaceOfNodes[nodeIndex].freeSpace < space) {
return false;
}
if (space > 0) {
_moveNodeToNewSpaceMap(
nodeIndex,
(uint(spaceOfNodes[nodeIndex].freeSpace) - space).toUint8()
);
}
return true;
}
/**
* @dev Allows Schains contract to occupy free space on a node.
*
* Returns whether operation is successful.
*/
function addSpaceToNode(uint nodeIndex, uint8 space)
external
override
checkNodeExists(nodeIndex)
allow("SchainsInternal")
{
if (space > 0) {
_moveNodeToNewSpaceMap(
nodeIndex,
(uint(spaceOfNodes[nodeIndex].freeSpace) + space).toUint8()
);
}
}
/**
* @dev Allows SkaleManager to change a node's last reward date.
*/
function changeNodeLastRewardDate(uint nodeIndex)
external
override
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
nodes[nodeIndex].lastRewardDate = block.timestamp;
}
/**
* @dev Allows SkaleManager to change a node's finish time.
*/
function changeNodeFinishTime(uint nodeIndex, uint time)
external
override
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
nodes[nodeIndex].finishTime = time;
}
/**
* @dev Allows SkaleManager contract to create new node and add it to the
* Nodes contract.
*
* Emits a {NodeCreated} event.
*
* Requirements:
*
* - Node IP must be non-zero.
* - Node IP must be available.
* - Node name must not already be registered.
* - Node port must be greater than zero.
*/
function createNode(address from, NodeCreationParams calldata params)
external
override
allow("SkaleManager")
nonZeroIP(params.ip)
{
// checks that Node has correct data
require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered");
require(params.port > 0, "Port is zero");
require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect");
uint validatorId = IValidatorService(
contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from);
uint8 totalSpace = ConstantsHolder(contractManager.getContract("ConstantsHolder")).TOTAL_SPACE_ON_NODE();
nodes.push(Node({
name: params.name,
ip: params.ip,
publicIP: params.publicIp,
port: params.port,
publicKey: params.publicKey,
startBlock: block.number,
lastRewardDate: block.timestamp,
finishTime: 0,
status: NodeStatus.Active,
validatorId: validatorId
}));
uint nodeIndex = nodes.length - 1;
validatorToNodeIndexes[validatorId].push(nodeIndex);
bytes32 nodeId = keccak256(abi.encodePacked(params.name));
nodesIPCheck[params.ip] = true;
nodesNameCheck[nodeId] = true;
nodesNameToIndex[nodeId] = nodeIndex;
nodeIndexes[from].isNodeExist[nodeIndex] = true;
nodeIndexes[from].numberOfNodes++;
domainNames[nodeIndex] = params.domainName;
spaceOfNodes.push(SpaceManaging({
freeSpace: totalSpace,
indexInSpaceMap: spaceToNodes[totalSpace].length
}));
_setNodeActive(nodeIndex);
emit NodeCreated(
nodeIndex,
from,
params.name,
params.ip,
params.publicIp,
params.port,
params.nonce,
params.domainName);
}
/**
* @dev Allows NODE_MANAGER_ROLE to initiate a node exit procedure.
*
* Returns whether the operation is successful.
*
* Emits an {ExitInitialized} event.
*/
function initExit(uint nodeIndex)
external
override
checkNodeExists(nodeIndex)
{
require(hasRole(NODE_MANAGER_ROLE, msg.sender), "NODE_MANAGER_ROLE is required");
require(isNodeActive(nodeIndex), "Node should be Active");
_setNodeLeaving(nodeIndex);
NodeRotation(contractManager.getContract("NodeRotation")).freezeSchains(nodeIndex);
emit ExitInitialized(nodeIndex, block.timestamp);
}
/**
* @dev Allows SkaleManager contract to complete a node exit procedure.
*
* Returns whether the operation is successful.
*
* Emits an {ExitCompleted} event.
*
* Requirements:
*
* - Node must have already initialized a node exit procedure.
*/
function completeExit(uint nodeIndex)
external
override
checkNodeExists(nodeIndex)
allow("SkaleManager")
returns (bool)
{
require(isNodeLeaving(nodeIndex), "Node is not Leaving");
_setNodeLeft(nodeIndex);
emit ExitCompleted(nodeIndex);
return true;
}
/**
* @dev Allows SkaleManager contract to delete a validator's node.
*
* Requirements:
*
* - Validator ID must exist.
*/
function deleteNodeForValidator(uint validatorId, uint nodeIndex)
external
override
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
IValidatorService validatorService = IValidatorService(contractManager.getValidatorService());
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
uint[] memory validatorNodes = validatorToNodeIndexes[validatorId];
uint position = _findNode(validatorNodes, nodeIndex);
if (position < validatorNodes.length) {
validatorToNodeIndexes[validatorId][position] =
validatorToNodeIndexes[validatorId][validatorNodes.length - 1];
}
validatorToNodeIndexes[validatorId].pop();
address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey);
if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) {
if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) {
validatorService.removeNodeAddress(validatorId, nodeOwner);
}
nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false;
nodeIndexes[nodeOwner].numberOfNodes--;
}
}
/**
* @dev Allows SkaleManager contract to check whether a validator has
* sufficient stake to create another node.
*
* Requirements:
*
* - Validator must be included on trusted list if trusted list is enabled.
* - Validator must have sufficient stake to operate an additional node.
*/
function checkPossibilityCreatingNode(address nodeAddress) external override allow("SkaleManager") {
IValidatorService validatorService = IValidatorService(contractManager.getValidatorService());
uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress);
require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node");
require(
_checkValidatorPositionToMaintainNode(validatorId, validatorToNodeIndexes[validatorId].length),
"Validator must meet the Minimum Staking Requirement");
}
/**
* @dev Allows SkaleManager contract to check whether a validator has
* sufficient stake to maintain a node.
*
* Returns whether validator can maintain node with current stake.
*
* Requirements:
*
* - Validator ID and nodeIndex must both exist.
*/
function checkPossibilityToMaintainNode(
uint validatorId,
uint nodeIndex
)
external
override
checkNodeExists(nodeIndex)
allow("Bounty")
returns (bool)
{
IValidatorService validatorService = IValidatorService(contractManager.getValidatorService());
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
uint[] memory validatorNodes = validatorToNodeIndexes[validatorId];
uint position = _findNode(validatorNodes, nodeIndex);
require(position < validatorNodes.length, "Node does not exist for this Validator");
return _checkValidatorPositionToMaintainNode(validatorId, position);
}
/**
* @dev Allows Node to set In_Maintenance status.
*
* Requirements:
*
* - Node must already be Active.
* - `msg.sender` must be owner of Node, validator, or SkaleManager.
*/
function setNodeInMaintenance(uint nodeIndex) external override onlyNodeOrNodeManager(nodeIndex) {
require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active");
_setNodeInMaintenance(nodeIndex);
emit MaintenanceNode(nodeIndex, true);
}
/**
* @dev Allows Node to remove In_Maintenance status.
*
* Requirements:
*
* - Node must already be In Maintenance.
* - `msg.sender` must be owner of Node, validator, or SkaleManager.
*/
function removeNodeFromInMaintenance(uint nodeIndex) external override onlyNodeOrNodeManager(nodeIndex) {
require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance");
_setNodeActive(nodeIndex);
emit MaintenanceNode(nodeIndex, false);
}
/**
* @dev Marks the node as incompliant
*
*/
function setNodeIncompliant(uint nodeIndex) external override onlyCompliance checkNodeExists(nodeIndex) {
if (!incompliant[nodeIndex]) {
incompliant[nodeIndex] = true;
_makeNodeInvisible(nodeIndex);
emit IncompliantNode(nodeIndex, true);
}
}
/**
* @dev Marks the node as compliant
*
*/
function setNodeCompliant(uint nodeIndex) external override onlyCompliance checkNodeExists(nodeIndex) {
if (incompliant[nodeIndex]) {
incompliant[nodeIndex] = false;
_tryToMakeNodeVisible(nodeIndex);
emit IncompliantNode(nodeIndex, false);
}
}
function setDomainName(uint nodeIndex, string memory domainName)
external
override
onlyNodeOrNodeManager(nodeIndex)
{
domainNames[nodeIndex] = domainName;
}
function makeNodeVisible(uint nodeIndex) external override allow("SchainsInternal") {
_tryToMakeNodeVisible(nodeIndex);
}
function makeNodeInvisible(uint nodeIndex) external override allow("SchainsInternal") {
_makeNodeInvisible(nodeIndex);
}
function changeIP(
uint nodeIndex,
bytes4 newIP,
bytes4 newPublicIP
)
external
override
onlyAdmin
checkNodeExists(nodeIndex)
nonZeroIP(newIP)
{
if (newPublicIP != 0x0) {
require(newIP == newPublicIP, "IP address is not the same");
nodes[nodeIndex].publicIP = newPublicIP;
}
nodesIPCheck[nodes[nodeIndex].ip] = false;
nodesIPCheck[newIP] = true;
emit IPChanged(nodeIndex, nodes[nodeIndex].ip, newIP);
nodes[nodeIndex].ip = newIP;
}
function getRandomNodeWithFreeSpace(
uint8 freeSpace,
IRandom.RandomGenerator memory randomGenerator
)
external
view
override
returns (uint)
{
uint8 place = _nodesAmountBySpace.getRandomNonZeroElementFromPlaceToLast(
freeSpace == 0 ? 1 : freeSpace,
randomGenerator
).toUint8();
require(place > 0, "Node not found");
return spaceToNodes[place][randomGenerator.random(spaceToNodes[place].length)];
}
/**
* @dev Checks whether it is time for a node's reward.
*/
function isTimeForReward(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (bool)
{
return IBountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= block.timestamp;
}
/**
* @dev Returns IP address of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodeIP(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (bytes4)
{
require(nodeIndex < nodes.length, "Node does not exist");
return nodes[nodeIndex].ip;
}
/**
* @dev Returns domain name of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodeDomainName(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (string memory)
{
return domainNames[nodeIndex];
}
/**
* @dev Returns the port of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodePort(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (uint16)
{
return nodes[nodeIndex].port;
}
/**
* @dev Returns the public key of a given node.
*/
function getNodePublicKey(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (bytes32[2] memory)
{
return nodes[nodeIndex].publicKey;
}
/**
* @dev Returns an address of a given node.
*/
function getNodeAddress(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (address)
{
return _publicKeyToAddress(nodes[nodeIndex].publicKey);
}
/**
* @dev Returns the finish exit time of a given node.
*/
function getNodeFinishTime(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].finishTime;
}
/**
* @dev Checks whether a node has left the network.
*/
function isNodeLeft(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Left;
}
function isNodeInMaintenance(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.In_Maintenance;
}
/**
* @dev Returns a given node's last reward date.
*/
function getNodeLastRewardDate(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].lastRewardDate;
}
/**
* @dev Returns a given node's next reward date.
*/
function getNodeNextRewardDate(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (uint)
{
return IBountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex);
}
/**
* @dev Returns the total number of registered nodes.
*/
function getNumberOfNodes() external view override returns (uint) {
return nodes.length;
}
/**
* @dev Returns the total number of online nodes.
*
* Note: Online nodes are equal to the number of active plus leaving nodes.
*/
function getNumberOnlineNodes() external view override returns (uint) {
return numberOfActiveNodes + numberOfLeavingNodes ;
}
/**
* @dev Return active node IDs.
*/
function getActiveNodeIds() external view override returns (uint[] memory activeNodeIds) {
activeNodeIds = new uint[](numberOfActiveNodes);
uint indexOfActiveNodeIds = 0;
for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) {
if (isNodeActive(indexOfNodes)) {
activeNodeIds[indexOfActiveNodeIds] = indexOfNodes;
indexOfActiveNodeIds++;
}
}
}
/**
* @dev Return a given node's current status.
*/
function getNodeStatus(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (NodeStatus)
{
return nodes[nodeIndex].status;
}
/**
* @dev Return a validator's linked nodes.
*
* Requirements:
*
* - Validator ID must exist.
*/
function getValidatorNodeIndexes(uint validatorId) external view override returns (uint[] memory) {
IValidatorService validatorService = IValidatorService(contractManager.getValidatorService());
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
return validatorToNodeIndexes[validatorId];
}
/**
* @dev Returns number of nodes with available space.
*/
function countNodesWithFreeSpace(uint8 freeSpace) external view override returns (uint count) {
if (freeSpace == 0) {
return _nodesAmountBySpace.sumFromPlaceToLast(1);
}
return _nodesAmountBySpace.sumFromPlaceToLast(freeSpace);
}
/**
* @dev constructor in Permissions approach.
*/
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
numberOfActiveNodes = 0;
numberOfLeavingNodes = 0;
numberOfLeftNodes = 0;
_nodesAmountBySpace.create(128);
}
/**
* @dev Returns the Validator ID for a given node.
*/
function getValidatorId(uint nodeIndex)
public
view
override
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].validatorId;
}
/**
* @dev Checks whether a node exists for a given address.
*/
function isNodeExist(address from, uint nodeIndex)
public
view
override
checkNodeExists(nodeIndex)
returns (bool)
{
return nodeIndexes[from].isNodeExist[nodeIndex];
}
/**
* @dev Checks whether a node's status is Active.
*/
function isNodeActive(uint nodeIndex)
public
view
override
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Active;
}
/**
* @dev Checks whether a node's status is Leaving.
*/
function isNodeLeaving(uint nodeIndex)
public
view
override
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Leaving;
}
function _removeNodeFromSpaceToNodes(uint nodeIndex, uint8 space) internal {
uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap;
uint len = spaceToNodes[space].length - 1;
if (indexInArray < len) {
uint shiftedIndex = spaceToNodes[space][len];
spaceToNodes[space][indexInArray] = shiftedIndex;
spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray;
}
spaceToNodes[space].pop();
delete spaceOfNodes[nodeIndex].indexInSpaceMap;
}
/**
* @dev Moves a node to a new space mapping.
*/
function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private {
if (!_invisible[nodeIndex]) {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_removeNodeFromTree(space);
_addNodeToTree(newSpace);
_removeNodeFromSpaceToNodes(nodeIndex, space);
_addNodeToSpaceToNodes(nodeIndex, newSpace);
}
spaceOfNodes[nodeIndex].freeSpace = newSpace;
}
/**
* @dev Changes a node's status to Active.
*/
function _setNodeActive(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.Active;
numberOfActiveNodes = numberOfActiveNodes + 1;
if (_invisible[nodeIndex]) {
_tryToMakeNodeVisible(nodeIndex);
} else {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_addNodeToSpaceToNodes(nodeIndex, space);
_addNodeToTree(space);
}
}
/**
* @dev Changes a node's status to In_Maintenance.
*/
function _setNodeInMaintenance(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.In_Maintenance;
numberOfActiveNodes = numberOfActiveNodes - 1;
_makeNodeInvisible(nodeIndex);
}
/**
* @dev Changes a node's status to Left.
*/
function _setNodeLeft(uint nodeIndex) private {
nodesIPCheck[nodes[nodeIndex].ip] = false;
nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false;
delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))];
if (nodes[nodeIndex].status == NodeStatus.Active) {
numberOfActiveNodes--;
} else {
numberOfLeavingNodes--;
}
nodes[nodeIndex].status = NodeStatus.Left;
numberOfLeftNodes++;
delete spaceOfNodes[nodeIndex].freeSpace;
}
/**
* @dev Changes a node's status to Leaving.
*/
function _setNodeLeaving(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.Leaving;
numberOfActiveNodes--;
numberOfLeavingNodes++;
_makeNodeInvisible(nodeIndex);
}
function _makeNodeInvisible(uint nodeIndex) private {
if (!_invisible[nodeIndex]) {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_removeNodeFromSpaceToNodes(nodeIndex, space);
_removeNodeFromTree(space);
_invisible[nodeIndex] = true;
}
}
function _tryToMakeNodeVisible(uint nodeIndex) private {
if (_invisible[nodeIndex] && _canBeVisible(nodeIndex)) {
_makeNodeVisible(nodeIndex);
}
}
function _makeNodeVisible(uint nodeIndex) private {
if (_invisible[nodeIndex]) {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_addNodeToSpaceToNodes(nodeIndex, space);
_addNodeToTree(space);
delete _invisible[nodeIndex];
}
}
function _addNodeToSpaceToNodes(uint nodeIndex, uint8 space) private {
spaceToNodes[space].push(nodeIndex);
spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[space].length - 1;
}
function _addNodeToTree(uint8 space) private {
if (space > 0) {
_nodesAmountBySpace.addToPlace(space, 1);
}
}
function _removeNodeFromTree(uint8 space) private {
if (space > 0) {
_nodesAmountBySpace.removeFromPlace(space, 1);
}
}
function _checkValidatorPositionToMaintainNode(uint validatorId, uint position) private returns (bool) {
IDelegationController delegationController = IDelegationController(
contractManager.getContract("DelegationController")
);
uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId);
uint msr = IConstantsHolder(contractManager.getConstantsHolder()).msr();
return (position + 1) * msr <= delegationsTotal;
}
function _checkNodeIndex(uint nodeIndex) private view {
require(nodeIndex < nodes.length, "Node with such index does not exist");
}
function _checkNodeOrNodeManager(uint nodeIndex, address sender) private view {
IValidatorService validatorService = IValidatorService(contractManager.getValidatorService());
require(
isNodeExist(sender, nodeIndex) ||
hasRole(NODE_MANAGER_ROLE, msg.sender) ||
getValidatorId(nodeIndex) == validatorService.getValidatorId(sender),
"Sender is not permitted to call this function"
);
}
function _canBeVisible(uint nodeIndex) private view returns (bool) {
return !incompliant[nodeIndex] && nodes[nodeIndex].status == NodeStatus.Active;
}
/**
* @dev Returns the index of a given node within the validator's node index.
*/
function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) {
uint i;
for (i = 0; i < validatorNodeIndexes.length; i++) {
if (validatorNodeIndexes[i] == nodeIndex) {
return i;
}
}
return validatorNodeIndexes.length;
}
function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) {
bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1]));
bytes20 addr;
for (uint8 i = 12; i < 32; i++) {
addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8);
}
return address(addr);
}
}
| 4,921 |
250 | // And push the new swap | self.user_swaps[_to].push(from_swaps[i]);
| self.user_swaps[_to].push(from_swaps[i]);
| 24,006 |
173 | // called from 'enter' proposer is client in the case of 'proposeByBoth' | function proposeByBoth(address payable _client, address _backup, bytes calldata _functionData) external allowSelfCallsOnly {
bytes4 proposedActionId = getMethodId(_functionData);
require(isFastAction(proposedActionId), "invalid proposal");
checkRelation(_client, _backup);
bytes32 functionHash = keccak256(_functionData);
accountStorage.setProposalData(_client, _client, proposedActionId, functionHash, _backup);
}
| function proposeByBoth(address payable _client, address _backup, bytes calldata _functionData) external allowSelfCallsOnly {
bytes4 proposedActionId = getMethodId(_functionData);
require(isFastAction(proposedActionId), "invalid proposal");
checkRelation(_client, _backup);
bytes32 functionHash = keccak256(_functionData);
accountStorage.setProposalData(_client, _client, proposedActionId, functionHash, _backup);
}
| 1,232 |
52 | // constant addresses of all advisers / | address constant ADVISER1 = 0x7915D5A865FE68C63112be5aD3DCA5187EB08f24;
address constant ADVISER2 = 0x31cFF39AA68B91fa7C957272A6aA8fB8F7b69Cb0;
address constant ADVISER3 = 0x358b3aeec9fae5ab15fe28d2fe6c7c9fda596857;
address constant ADVISER4 = 0x1011FC646261eb5d4aB875886f1470d4919d83c8;
address constant ADVISER5 = 0xcc04Cd98da89A9172372aEf4B62BEDecd01A7F5a;
address constant ADVISER6 = 0xECD791f8E548D46A9711D853Ead7edC685Ca4ee8;
address constant ADVISER7 = 0x38B58e5783fd4D077e422B3362E9d6B265484e3f;
address constant ADVISER8 = 0x2934205135A129F995AC891C143cCae83ce175c7;
address constant ADVISER9 = 0x9F5D00F4A383bAd14DEfA9aee53C5AF2ad9ad32F;
address constant ADVISER10 = 0xBE993c982Fc5a0C0360CEbcEf9e4d2727339d96B;
| address constant ADVISER1 = 0x7915D5A865FE68C63112be5aD3DCA5187EB08f24;
address constant ADVISER2 = 0x31cFF39AA68B91fa7C957272A6aA8fB8F7b69Cb0;
address constant ADVISER3 = 0x358b3aeec9fae5ab15fe28d2fe6c7c9fda596857;
address constant ADVISER4 = 0x1011FC646261eb5d4aB875886f1470d4919d83c8;
address constant ADVISER5 = 0xcc04Cd98da89A9172372aEf4B62BEDecd01A7F5a;
address constant ADVISER6 = 0xECD791f8E548D46A9711D853Ead7edC685Ca4ee8;
address constant ADVISER7 = 0x38B58e5783fd4D077e422B3362E9d6B265484e3f;
address constant ADVISER8 = 0x2934205135A129F995AC891C143cCae83ce175c7;
address constant ADVISER9 = 0x9F5D00F4A383bAd14DEfA9aee53C5AF2ad9ad32F;
address constant ADVISER10 = 0xBE993c982Fc5a0C0360CEbcEf9e4d2727339d96B;
| 30,066 |
59 | // Profit share owing/_investor An Ethereum address/ return A positive number | function profitShareOwing(address _investor) public view returns (uint) {
if (!totalSupplyIsFixed || totalSupply_ == 0) {
return 0;
}
InvestorAccount memory account = accounts[_investor];
return totalProfits.sub(account.lastTotalProfits)
.mul(account.balance)
.div(totalSupply_)
.add(account.profitShare);
}
| function profitShareOwing(address _investor) public view returns (uint) {
if (!totalSupplyIsFixed || totalSupply_ == 0) {
return 0;
}
InvestorAccount memory account = accounts[_investor];
return totalProfits.sub(account.lastTotalProfits)
.mul(account.balance)
.div(totalSupply_)
.add(account.profitShare);
}
| 20,094 |
19 | // Comment | function addComment(bytes32 _id, string memory _commentHash) public {
require(idToIndex[_id] != 0, "Propose id don't exist!");
uint id = lsComment.push(_commentHash) - 1;
proIdToComment[_id].push(id);
emit NewComment(_id, _commentHash);
}
| function addComment(bytes32 _id, string memory _commentHash) public {
require(idToIndex[_id] != 0, "Propose id don't exist!");
uint id = lsComment.push(_commentHash) - 1;
proIdToComment[_id].push(id);
emit NewComment(_id, _commentHash);
}
| 38,314 |
195 | // Address of transferProxy contract | ITransferProxy public transferProxyInstance;
| ITransferProxy public transferProxyInstance;
| 17,826 |
35 | // For checking how many tokens you own. _owner - the owner's addr / | function balanceOf(address _owner) public view returns(uint256) {
return ownerKTCount[_owner];
}
| function balanceOf(address _owner) public view returns(uint256) {
return ownerKTCount[_owner];
}
| 31,921 |
14 | // Retrieve the consideration item from the execution struct. | ReceivedItem memory considerationItem = considerationExecution.item;
| ReceivedItem memory considerationItem = considerationExecution.item;
| 20,063 |
26 | // Abstract function to transfer rewards to the desired account to Account address to send the rewards amount Amount of rewards to transfer / | function _transferRewards(address to, uint256 amount) internal virtual;
function _getScaledUserBalanceAndSupply(address _asset, address _user)
internal
view
virtual
returns (uint256 userBalance, uint256 totalSupply);
| function _transferRewards(address to, uint256 amount) internal virtual;
function _getScaledUserBalanceAndSupply(address _asset, address _user)
internal
view
virtual
returns (uint256 userBalance, uint256 totalSupply);
| 5,951 |
9 | // ! ],! "expected": [! "4", "3", "1", "2", "5", "1", "5", "3", "2", "8", "10"! ] | //! }, {
//! "name": "complex",
//! "input": [
//! {
//! "entry": "complex",
//! "calldata": [
//! ]
//! }
| //! }, {
//! "name": "complex",
//! "input": [
//! {
//! "entry": "complex",
//! "calldata": [
//! ]
//! }
| 28,520 |
29 | // Bonus token for holders of any PAC DAO NFT / | contract PACLEXAction is ERC721Enumerable {
/* VARIABLES */
uint256 public currentId;
address payable public beneficiary;
address public owner;
address public pacdao = 0xf27AC88ac7e80487f21e5c2C847290b2AE5d7B8e;
address public lexarmy = 0xBe9aAF4113B5a4aFCdb7E20c21eAa53C6EE20b10;
address public artist = 0x82fDAF8ceD639567dEd54447400b037C4D0719d5;
mapping(uint256 => string) private _tokenURIs;
mapping(bytes32 => uint256) private leafMints;
uint256 maxMintsPerLeaf = 1;
string public baseURI = "ipfs://";
string public defaultMetadata = "QmTYvCgKunY8W18kSpCK5eUpHSEzGCmzqQp185AU451ALV";
string private _contractURI = "Qma4VAp8giZ74Ny7jJVW1e5V8kmC5VVaSeF6cbXWFizxsr";
bool isPublicMint = true;
bytes32 private merkleRoot;
/* CONSTRUCTOR */
constructor () ERC721 ("PAC/LEX Action", "PACLEX-A1"){
owner = msg.sender;
beneficiary = payable(0xf27AC88ac7e80487f21e5c2C847290b2AE5d7B8e);
merkleRoot = 0xbec6093988d4c88c0ee9b16c888f45b54e42106c79b3244b0a5551c0d4191f26;
}
/* PUBLIC VIEWS */
/**
* @dev Return token URI if set or Default URI
*
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId)); // dev: "ERC721URIStorage: URI query for nonexistent token";
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI;
// If there is no base URI, return the token URI.
if (bytes(base).length == 0 && bytes(_tokenURI).length > 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// No Token URI, return default
return string(abi.encodePacked(base, defaultMetadata));
}
/**
* @dev Return contract URI
*
*/
function contractURI() public view returns(string memory) {
return string(abi.encodePacked(baseURI, _contractURI));
}
/*f = PUBLIC WRITEABLE */
/**
* @dev Mint NFT if eligible.
*
*/
function mint(bytes32 leaf, bytes32[] memory proof) public
{
require(isPublicMint); // dev: Minting period over
require(verifyMerkle(leaf, proof)); // dev: Invalid Merkle Tree
require(leafMints[leaf] < maxMintsPerLeaf); // dev: Leaf already used
leafMints[leaf] += 1;
_mint(msg.sender);
if(currentId < 3) {
_mint(artist);
}
if(currentId < 36) {
_mint(pacdao);
_mint(lexarmy);
}
}
/**
* @dev Recover funds inadvertently sent to the contract
*
*/
function withdraw() public
{
beneficiary.transfer(address(this).balance);
}
/* ADMIN FUNCTIONS */
/**
* @dev Admin function to mint an NFT for an address
*
*/
function mintFor(address _mintAddress) public payable
{
require(msg.sender == beneficiary); // dev: Only Admin
require(_mintAddress != address(0));
_mint(_mintAddress);
}
function updateRoot(bytes32 newRoot) public {
require(msg.sender == beneficiary); // dev: Only Admin
merkleRoot = newRoot;
}
/**
* @dev Transfer ownership to new admin
*
*/
function updateBeneficiary(address payable newBeneficiary) public
{
require(msg.sender == beneficiary); // dev: Only Admin
beneficiary = newBeneficiary;
}
function transferOwner(address newOwner) public {
require(msg.sender == beneficiary || msg.sender == owner); // dev: Only Owner
owner = newOwner;
}
function updatePublicMint(bool isMint) public {
require(msg.sender == beneficiary); // dev: Only Admin
isPublicMint = isMint;
}
function updateMaxMintsPerLeaf(uint256 newMax) public {
require(msg.sender == beneficiary); // dev: Only Admin
maxMintsPerLeaf = newMax;
}
/**
* @dev Stoke token URL for specific token
*
*/
function setTokenUri(uint256 _tokenId, string memory _newUri) public
{
require(msg.sender == beneficiary); // dev: Only Admin
_setTokenURI(_tokenId, _newUri);
}
/**
* @dev Update default token URL when not set
*
*/
function setDefaultMetadata(string memory _newUri) public
{
require(msg.sender == beneficiary); //dev: Only Admin
defaultMetadata = _newUri;
}
/**
* @dev Update contract URI
*
*/
function setContractURI(string memory _newData) public {
require(msg.sender == beneficiary); //dev: Only Admin
_contractURI = _newData;
}
/* INTERNAL FUNCTIONS */
/**
* @dev Update ID and mint
*
*/
function _mint(address _mintAddress) private {
currentId += 1;
_safeMint(_mintAddress, currentId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId)); // dev: ERC721URIStorage: URI set of nonexistent token
_tokenURIs[tokenId] = _tokenURI;
}
function verifyMerkle(bytes32 leaf, bytes32[] memory proof) public view returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided rootA
return computedHash == merkleRoot;
}
/* FALLBACK */
receive() external payable { }
fallback() external payable { }
}
| contract PACLEXAction is ERC721Enumerable {
/* VARIABLES */
uint256 public currentId;
address payable public beneficiary;
address public owner;
address public pacdao = 0xf27AC88ac7e80487f21e5c2C847290b2AE5d7B8e;
address public lexarmy = 0xBe9aAF4113B5a4aFCdb7E20c21eAa53C6EE20b10;
address public artist = 0x82fDAF8ceD639567dEd54447400b037C4D0719d5;
mapping(uint256 => string) private _tokenURIs;
mapping(bytes32 => uint256) private leafMints;
uint256 maxMintsPerLeaf = 1;
string public baseURI = "ipfs://";
string public defaultMetadata = "QmTYvCgKunY8W18kSpCK5eUpHSEzGCmzqQp185AU451ALV";
string private _contractURI = "Qma4VAp8giZ74Ny7jJVW1e5V8kmC5VVaSeF6cbXWFizxsr";
bool isPublicMint = true;
bytes32 private merkleRoot;
/* CONSTRUCTOR */
constructor () ERC721 ("PAC/LEX Action", "PACLEX-A1"){
owner = msg.sender;
beneficiary = payable(0xf27AC88ac7e80487f21e5c2C847290b2AE5d7B8e);
merkleRoot = 0xbec6093988d4c88c0ee9b16c888f45b54e42106c79b3244b0a5551c0d4191f26;
}
/* PUBLIC VIEWS */
/**
* @dev Return token URI if set or Default URI
*
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId)); // dev: "ERC721URIStorage: URI query for nonexistent token";
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI;
// If there is no base URI, return the token URI.
if (bytes(base).length == 0 && bytes(_tokenURI).length > 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// No Token URI, return default
return string(abi.encodePacked(base, defaultMetadata));
}
/**
* @dev Return contract URI
*
*/
function contractURI() public view returns(string memory) {
return string(abi.encodePacked(baseURI, _contractURI));
}
/*f = PUBLIC WRITEABLE */
/**
* @dev Mint NFT if eligible.
*
*/
function mint(bytes32 leaf, bytes32[] memory proof) public
{
require(isPublicMint); // dev: Minting period over
require(verifyMerkle(leaf, proof)); // dev: Invalid Merkle Tree
require(leafMints[leaf] < maxMintsPerLeaf); // dev: Leaf already used
leafMints[leaf] += 1;
_mint(msg.sender);
if(currentId < 3) {
_mint(artist);
}
if(currentId < 36) {
_mint(pacdao);
_mint(lexarmy);
}
}
/**
* @dev Recover funds inadvertently sent to the contract
*
*/
function withdraw() public
{
beneficiary.transfer(address(this).balance);
}
/* ADMIN FUNCTIONS */
/**
* @dev Admin function to mint an NFT for an address
*
*/
function mintFor(address _mintAddress) public payable
{
require(msg.sender == beneficiary); // dev: Only Admin
require(_mintAddress != address(0));
_mint(_mintAddress);
}
function updateRoot(bytes32 newRoot) public {
require(msg.sender == beneficiary); // dev: Only Admin
merkleRoot = newRoot;
}
/**
* @dev Transfer ownership to new admin
*
*/
function updateBeneficiary(address payable newBeneficiary) public
{
require(msg.sender == beneficiary); // dev: Only Admin
beneficiary = newBeneficiary;
}
function transferOwner(address newOwner) public {
require(msg.sender == beneficiary || msg.sender == owner); // dev: Only Owner
owner = newOwner;
}
function updatePublicMint(bool isMint) public {
require(msg.sender == beneficiary); // dev: Only Admin
isPublicMint = isMint;
}
function updateMaxMintsPerLeaf(uint256 newMax) public {
require(msg.sender == beneficiary); // dev: Only Admin
maxMintsPerLeaf = newMax;
}
/**
* @dev Stoke token URL for specific token
*
*/
function setTokenUri(uint256 _tokenId, string memory _newUri) public
{
require(msg.sender == beneficiary); // dev: Only Admin
_setTokenURI(_tokenId, _newUri);
}
/**
* @dev Update default token URL when not set
*
*/
function setDefaultMetadata(string memory _newUri) public
{
require(msg.sender == beneficiary); //dev: Only Admin
defaultMetadata = _newUri;
}
/**
* @dev Update contract URI
*
*/
function setContractURI(string memory _newData) public {
require(msg.sender == beneficiary); //dev: Only Admin
_contractURI = _newData;
}
/* INTERNAL FUNCTIONS */
/**
* @dev Update ID and mint
*
*/
function _mint(address _mintAddress) private {
currentId += 1;
_safeMint(_mintAddress, currentId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId)); // dev: ERC721URIStorage: URI set of nonexistent token
_tokenURIs[tokenId] = _tokenURI;
}
function verifyMerkle(bytes32 leaf, bytes32[] memory proof) public view returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided rootA
return computedHash == merkleRoot;
}
/* FALLBACK */
receive() external payable { }
fallback() external payable { }
}
| 34,596 |
62 | // ERC20 compatible token - Short address attack fix created 29/09/2017author Frank Bonnet / | contract Token is IToken, InputValidator {
// Ethereum token standard
string public standard = "Token 0.3";
string public name;
string public symbol;
uint8 public decimals = 8;
// Token state
uint internal totalTokenSupply;
// Token balances
mapping (address => uint) internal balances;
// Token allowances
mapping (address => mapping (address => uint)) internal allowed;
// Events
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
/**
* Construct
*
* @param _name The full token name
* @param _symbol The token symbol (aberration)
*/
function Token(string _name, string _symbol) {
name = _name;
symbol = _symbol;
balances[msg.sender] = 0;
totalTokenSupply = 0;
}
/**
* Get the total token supply
*
* @return The total supply
*/
function totalSupply() public constant returns (uint) {
return totalTokenSupply;
}
/**
* Get balance of `_owner`
*
* @param _owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address _owner) public constant returns (uint) {
return balances[_owner];
}
/**
* Send `_value` token to `_to` from `msg.sender`
*
* @param _to The address of the recipient
* @param _value The amount of token to be transferred
* @return Whether the transfer was successful or not
*/
function transfer(address _to, uint _value) public safe_arguments(2) returns (bool) {
// Check if the sender has enough tokens
require(balances[msg.sender] >= _value);
// Check for overflows
require(balances[_to] + _value >= balances[_to]);
// Transfer tokens
balances[msg.sender] -= _value;
balances[_to] += _value;
// Notify listeners
Transfer(msg.sender, _to, _value);
return true;
}
/**
* Send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of token to be transferred
* @return Whether the transfer was successful or not
*/
function transferFrom(address _from, address _to, uint _value) public safe_arguments(3) returns (bool) {
// Check if the sender has enough
require(balances[_from] >= _value);
// Check for overflows
require(balances[_to] + _value >= balances[_to]);
// Check allowance
require(_value <= allowed[_from][msg.sender]);
// Transfer tokens
balances[_to] += _value;
balances[_from] -= _value;
// Update allowance
allowed[_from][msg.sender] -= _value;
// Notify listeners
Transfer(_from, _to, _value);
return true;
}
/**
* `msg.sender` approves `_spender` to spend `_value` tokens
*
* @param _spender The address of the account able to transfer the tokens
* @param _value The amount of tokens to be approved for transfer
* @return Whether the approval was successful or not
*/
function approve(address _spender, uint _value) public safe_arguments(2) returns (bool) {
// Update allowance
allowed[msg.sender][_spender] = _value;
// Notify listeners
Approval(msg.sender, _spender, _value);
return true;
}
/**
* Get the amount of remaining tokens that `_spender` is allowed to spend from `_owner`
*
* @param _owner The address of the account owning tokens
* @param _spender The address of the account able to transfer the tokens
* @return Amount of remaining tokens allowed to spent
*/
function allowance(address _owner, address _spender) public constant returns (uint) {
return allowed[_owner][_spender];
}
}
| contract Token is IToken, InputValidator {
// Ethereum token standard
string public standard = "Token 0.3";
string public name;
string public symbol;
uint8 public decimals = 8;
// Token state
uint internal totalTokenSupply;
// Token balances
mapping (address => uint) internal balances;
// Token allowances
mapping (address => mapping (address => uint)) internal allowed;
// Events
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
/**
* Construct
*
* @param _name The full token name
* @param _symbol The token symbol (aberration)
*/
function Token(string _name, string _symbol) {
name = _name;
symbol = _symbol;
balances[msg.sender] = 0;
totalTokenSupply = 0;
}
/**
* Get the total token supply
*
* @return The total supply
*/
function totalSupply() public constant returns (uint) {
return totalTokenSupply;
}
/**
* Get balance of `_owner`
*
* @param _owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address _owner) public constant returns (uint) {
return balances[_owner];
}
/**
* Send `_value` token to `_to` from `msg.sender`
*
* @param _to The address of the recipient
* @param _value The amount of token to be transferred
* @return Whether the transfer was successful or not
*/
function transfer(address _to, uint _value) public safe_arguments(2) returns (bool) {
// Check if the sender has enough tokens
require(balances[msg.sender] >= _value);
// Check for overflows
require(balances[_to] + _value >= balances[_to]);
// Transfer tokens
balances[msg.sender] -= _value;
balances[_to] += _value;
// Notify listeners
Transfer(msg.sender, _to, _value);
return true;
}
/**
* Send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of token to be transferred
* @return Whether the transfer was successful or not
*/
function transferFrom(address _from, address _to, uint _value) public safe_arguments(3) returns (bool) {
// Check if the sender has enough
require(balances[_from] >= _value);
// Check for overflows
require(balances[_to] + _value >= balances[_to]);
// Check allowance
require(_value <= allowed[_from][msg.sender]);
// Transfer tokens
balances[_to] += _value;
balances[_from] -= _value;
// Update allowance
allowed[_from][msg.sender] -= _value;
// Notify listeners
Transfer(_from, _to, _value);
return true;
}
/**
* `msg.sender` approves `_spender` to spend `_value` tokens
*
* @param _spender The address of the account able to transfer the tokens
* @param _value The amount of tokens to be approved for transfer
* @return Whether the approval was successful or not
*/
function approve(address _spender, uint _value) public safe_arguments(2) returns (bool) {
// Update allowance
allowed[msg.sender][_spender] = _value;
// Notify listeners
Approval(msg.sender, _spender, _value);
return true;
}
/**
* Get the amount of remaining tokens that `_spender` is allowed to spend from `_owner`
*
* @param _owner The address of the account owning tokens
* @param _spender The address of the account able to transfer the tokens
* @return Amount of remaining tokens allowed to spent
*/
function allowance(address _owner, address _spender) public constant returns (uint) {
return allowed[_owner][_spender];
}
}
| 27,759 |
98 | // do the transfers and collect payment | if (zeroForOne) {
if (amount1 < 0) TransferHelper.safeTransfer(token1, recipient, uint256(-amount1));
uint256 balance0Before = balance0();
ISwapHatV3SwapCallback(msg.sender).swaphatV3SwapCallback(amount0, amount1, data);
require(balance0Before.add(uint256(amount0)) <= balance0(), 'IIA');
} else {
| if (zeroForOne) {
if (amount1 < 0) TransferHelper.safeTransfer(token1, recipient, uint256(-amount1));
uint256 balance0Before = balance0();
ISwapHatV3SwapCallback(msg.sender).swaphatV3SwapCallback(amount0, amount1, data);
require(balance0Before.add(uint256(amount0)) <= balance0(), 'IIA');
} else {
| 25,044 |
5 | // Withdraws from Save Withdraws token supported by mStable from Save _credits Credits to withdraw _unstake unstake from Vault?return amountWithdrawn Amount withdrawn in mUSD / |
function _withdraw(uint256 _credits, bool _unstake)
internal
returns (uint256 amountWithdrawn)
|
function _withdraw(uint256 _credits, bool _unstake)
internal
returns (uint256 amountWithdrawn)
| 22,447 |
755 | // Sets the referral code for Aave deposits. referralCode The referral code. / | function setAaveReferralCode(uint16 referralCode) external onlyOwner {
| function setAaveReferralCode(uint16 referralCode) external onlyOwner {
| 36,086 |
5 | // Interface for contracts conforming to ERC-721: Non-Fungible Tokens/Dieter Shirley <dete@axiomzen.co> (https:github.com/dete) | contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
| contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
| 6,715 |
164 | // Returns the rate at which we withdraw maker tokens./info State from `_getBalanceCheckInfo()`./ return makerTokenWithdrawRate Maker token withdraw rate. | function _getMakerTokenWithdrawRate(BalanceCheckInfo memory info)
internal
pure
returns (int256 makerTokenWithdrawRate)
| function _getMakerTokenWithdrawRate(BalanceCheckInfo memory info)
internal
pure
returns (int256 makerTokenWithdrawRate)
| 54,771 |
6 | // @inheritdoc ITasks | function taskCount() external view returns (uint256) {
return taskCounter;
}
| function taskCount() external view returns (uint256) {
return taskCounter;
}
| 24,655 |
161 | // Mint the destination tokens with the withdrawn collateral | destinationPool.exchangeMint(
executeExchangeParams.collateralAmount.rawValue,
executeExchangeParams.destNumTokens.rawValue,
executeExchangeParams.recipient
);
emit Exchange(
executeExchangeParams.sender,
address(destinationPool),
executeExchangeParams.numTokens.rawValue,
| destinationPool.exchangeMint(
executeExchangeParams.collateralAmount.rawValue,
executeExchangeParams.destNumTokens.rawValue,
executeExchangeParams.recipient
);
emit Exchange(
executeExchangeParams.sender,
address(destinationPool),
executeExchangeParams.numTokens.rawValue,
| 7,917 |
183 | // If there's no limit or if the limit is greater than the start distance, apply the discount rate of the base. | if (_limitLength == 0 || _limitLength > _startDistance) {
| if (_limitLength == 0 || _limitLength > _startDistance) {
| 27,430 |
20 | // scope for checks, avoids stack too deep errors | uint256 token0TransferCost = data.transferGasCosts[depositParams.token0];
uint256 token1TransferCost = data.transferGasCosts[depositParams.token1];
require(token0TransferCost != 0 && token1TransferCost != 0, 'OS0F');
checkOrderParams(
data,
depositParams.to,
depositParams.gasLimit,
depositParams.submitDeadline,
ORDER_BASE_COST.add(token0TransferCost).add(token1TransferCost)
);
| uint256 token0TransferCost = data.transferGasCosts[depositParams.token0];
uint256 token1TransferCost = data.transferGasCosts[depositParams.token1];
require(token0TransferCost != 0 && token1TransferCost != 0, 'OS0F');
checkOrderParams(
data,
depositParams.to,
depositParams.gasLimit,
depositParams.submitDeadline,
ORDER_BASE_COST.add(token0TransferCost).add(token1TransferCost)
);
| 28,508 |
13 | // uint256 allClaimableAmount = (lastRoiTimeinvestors[msg.sender].totalLockedapr).div(percentRaterewardPeriod); investors[msg.sender].claimableAmount = investors[msg.sender] .claimableAmount .add(allClaimableAmount); |
investors[msg.sender].maxClaimableAmount = investors[msg.sender]
.maxClaimableAmount
.add(maxAmount);
investors[msg.sender].totalLocked = investors[msg.sender]
.totalLocked
.add(_amount - depositFee);
|
investors[msg.sender].maxClaimableAmount = investors[msg.sender]
.maxClaimableAmount
.add(maxAmount);
investors[msg.sender].totalLocked = investors[msg.sender]
.totalLocked
.add(_amount - depositFee);
| 354 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.