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 |
|---|---|---|---|---|
10 | // Notify off-chain applications of the transfer. | emit Transfer(msg.sender, to, amount);
| emit Transfer(msg.sender, to, amount);
| 13,986 |
14 | // Upgrade mode enter event | event NoticePeriodStart(
uint256 indexed versionId,
address[] newTargets,
uint256 noticePeriod // notice period (in seconds)
);
| event NoticePeriodStart(
uint256 indexed versionId,
address[] newTargets,
uint256 noticePeriod // notice period (in seconds)
);
| 10,850 |
65 | // Appends a byte to the end of the buffer. Resizes if doing so would exceed the capacity of the buffer._buf The buffer to append to._data The data to append./ | function append(buffer memory _buf, uint8 _data) internal pure {
if (_buf.buf.length + 1 > _buf.capacity) {
resize(_buf, _buf.capacity * 2);
}
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length)
mstore8(dest, _data)
mstore(bufptr, add(buflen, 1)) // Update buffer length
}
}
| function append(buffer memory _buf, uint8 _data) internal pure {
if (_buf.buf.length + 1 > _buf.capacity) {
resize(_buf, _buf.capacity * 2);
}
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length)
mstore8(dest, _data)
mstore(bufptr, add(buflen, 1)) // Update buffer length
}
}
| 11,664 |
64 | // get last element | bytes32 key = _openContracts[_openContracts.length - 1];
Contract memory _contract = contracts[key];
_contract.severity = severity;
Contract memory newContract = _process(_contract);
| bytes32 key = _openContracts[_openContracts.length - 1];
Contract memory _contract = contracts[key];
_contract.severity = severity;
Contract memory newContract = _process(_contract);
| 1,849 |
3 | // Used to temporarily halt all transactions | bool public transfersFrozen;
| bool public transfersFrozen;
| 17,898 |
67 | // we record that fee collected from the underlying | feesUnderlying += uint128(impliedYieldFee);
| feesUnderlying += uint128(impliedYieldFee);
| 23,537 |
157 | // Returns the Uniform Resource Identifier (URI) for `tokenId` token. | function tokenURI(uint256 tokenId) external view returns (string memory){
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory tokenuri;
if (_hideTokens) {
//redirect to mystery box
tokenuri = string(abi.encodePacked(_baseURI, "00000000.json"));
} else {
//Input flag data here to send to reveal URI
tokenuri = string(abi.encodePacked(_baseURI, toString(tokenId), ".json")); /// 0.json 135.json
}
return tokenuri;
}
| function tokenURI(uint256 tokenId) external view returns (string memory){
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory tokenuri;
if (_hideTokens) {
//redirect to mystery box
tokenuri = string(abi.encodePacked(_baseURI, "00000000.json"));
} else {
//Input flag data here to send to reveal URI
tokenuri = string(abi.encodePacked(_baseURI, toString(tokenId), ".json")); /// 0.json 135.json
}
return tokenuri;
}
| 22,770 |
94 | // Transfer ether owed to the beneficiary (not susceptible to re-entry attack, as the ether owed is set to 0 before the transfer takes place). | beneficiary.transfer(etherOwed);
| beneficiary.transfer(etherOwed);
| 12,521 |
118 | // Returns the contract registry that the contract is set to use/ return contractRegistry is the registry contract address | function getContractRegistry() public override view returns (IContractRegistry) {
return contractRegistry;
}
| function getContractRegistry() public override view returns (IContractRegistry) {
return contractRegistry;
}
| 25,758 |
67 | // Immutables / | address public immutable pool;
IVolatilityOracle public immutable volatilityOracle;
IPriceOracle public immutable priceOracle;
IPriceOracle public immutable stablesOracle;
uint256 private immutable priceOracleDecimals;
uint256 private immutable stablesOracleDecimals;
| address public immutable pool;
IVolatilityOracle public immutable volatilityOracle;
IPriceOracle public immutable priceOracle;
IPriceOracle public immutable stablesOracle;
uint256 private immutable priceOracleDecimals;
uint256 private immutable stablesOracleDecimals;
| 47,223 |
22 | // TalaoMarketplace This contract is allowing users to buy or sell Talao tokens at a price set by the owner Blockchain Partner / | contract TalaoMarketplace is Ownable {
using SafeMath for uint256;
TalaoToken public token;
struct MarketplaceData {
uint buyPrice;
uint sellPrice;
uint unitPrice;
}
MarketplaceData public marketplace;
event SellingPrice(uint sellingPrice);
event TalaoBought(address buyer, uint amount, uint price, uint unitPrice);
event TalaoSold(address seller, uint amount, uint price, uint unitPrice);
/**
* @dev Constructor of the marketplace pointing to the TALAO token address
* @param talao the talao token address
**/
constructor(address talao)
public
{
token = TalaoToken(talao);
}
/**
* @dev Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
* @param newSellPrice price the users can sell to the contract
* @param newBuyPrice price users can buy from the contract
* @param newUnitPrice to manage decimal issue 0,35 = 35 /100 (100 is unit)
*/
function setPrices(uint256 newSellPrice, uint256 newBuyPrice, uint256 newUnitPrice)
public
onlyOwner
{
require (newSellPrice > 0 && newBuyPrice > 0 && newUnitPrice > 0, "wrong inputs");
marketplace.sellPrice = newSellPrice;
marketplace.buyPrice = newBuyPrice;
marketplace.unitPrice = newUnitPrice;
}
/**
* @dev Allow anyone to buy tokens against ether, depending on the buyPrice set by the contract owner.
* @return amount the amount of tokens bought
**/
function buy()
public
payable
returns (uint amount)
{
amount = msg.value.mul(marketplace.unitPrice).div(marketplace.buyPrice);
token.transfer(msg.sender, amount);
emit TalaoBought(msg.sender, amount, marketplace.buyPrice, marketplace.unitPrice);
return amount;
}
/**
* @dev Allow anyone to sell tokens for ether, depending on the sellPrice set by the contract owner.
* @param amount the number of tokens to be sold
* @return revenue ethers sent in return
**/
function sell(uint amount)
public
returns (uint revenue)
{
require(token.balanceOf(msg.sender) >= amount, "sender has not enough tokens");
token.transferFrom(msg.sender, this, amount);
revenue = amount.mul(marketplace.sellPrice).div(marketplace.unitPrice);
msg.sender.transfer(revenue);
emit TalaoSold(msg.sender, amount, marketplace.sellPrice, marketplace.unitPrice);
return revenue;
}
/**
* @dev Allows the owner to withdraw ethers from the contract.
* @param ethers quantity of ethers to be withdrawn
* @return true if withdrawal successful ; false otherwise
*/
function withdrawEther(uint256 ethers)
public
onlyOwner
{
if (this.balance >= ethers) {
msg.sender.transfer(ethers);
}
}
/**
* @dev Allow the owner to withdraw tokens from the contract.
* @param tokens quantity of tokens to be withdrawn
*/
function withdrawTalao(uint256 tokens)
public
onlyOwner
{
token.transfer(msg.sender, tokens);
}
/**
* @dev Fallback function ; only owner can send ether.
**/
function ()
public
payable
onlyOwner
{
}
}
| contract TalaoMarketplace is Ownable {
using SafeMath for uint256;
TalaoToken public token;
struct MarketplaceData {
uint buyPrice;
uint sellPrice;
uint unitPrice;
}
MarketplaceData public marketplace;
event SellingPrice(uint sellingPrice);
event TalaoBought(address buyer, uint amount, uint price, uint unitPrice);
event TalaoSold(address seller, uint amount, uint price, uint unitPrice);
/**
* @dev Constructor of the marketplace pointing to the TALAO token address
* @param talao the talao token address
**/
constructor(address talao)
public
{
token = TalaoToken(talao);
}
/**
* @dev Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
* @param newSellPrice price the users can sell to the contract
* @param newBuyPrice price users can buy from the contract
* @param newUnitPrice to manage decimal issue 0,35 = 35 /100 (100 is unit)
*/
function setPrices(uint256 newSellPrice, uint256 newBuyPrice, uint256 newUnitPrice)
public
onlyOwner
{
require (newSellPrice > 0 && newBuyPrice > 0 && newUnitPrice > 0, "wrong inputs");
marketplace.sellPrice = newSellPrice;
marketplace.buyPrice = newBuyPrice;
marketplace.unitPrice = newUnitPrice;
}
/**
* @dev Allow anyone to buy tokens against ether, depending on the buyPrice set by the contract owner.
* @return amount the amount of tokens bought
**/
function buy()
public
payable
returns (uint amount)
{
amount = msg.value.mul(marketplace.unitPrice).div(marketplace.buyPrice);
token.transfer(msg.sender, amount);
emit TalaoBought(msg.sender, amount, marketplace.buyPrice, marketplace.unitPrice);
return amount;
}
/**
* @dev Allow anyone to sell tokens for ether, depending on the sellPrice set by the contract owner.
* @param amount the number of tokens to be sold
* @return revenue ethers sent in return
**/
function sell(uint amount)
public
returns (uint revenue)
{
require(token.balanceOf(msg.sender) >= amount, "sender has not enough tokens");
token.transferFrom(msg.sender, this, amount);
revenue = amount.mul(marketplace.sellPrice).div(marketplace.unitPrice);
msg.sender.transfer(revenue);
emit TalaoSold(msg.sender, amount, marketplace.sellPrice, marketplace.unitPrice);
return revenue;
}
/**
* @dev Allows the owner to withdraw ethers from the contract.
* @param ethers quantity of ethers to be withdrawn
* @return true if withdrawal successful ; false otherwise
*/
function withdrawEther(uint256 ethers)
public
onlyOwner
{
if (this.balance >= ethers) {
msg.sender.transfer(ethers);
}
}
/**
* @dev Allow the owner to withdraw tokens from the contract.
* @param tokens quantity of tokens to be withdrawn
*/
function withdrawTalao(uint256 tokens)
public
onlyOwner
{
token.transfer(msg.sender, tokens);
}
/**
* @dev Fallback function ; only owner can send ether.
**/
function ()
public
payable
onlyOwner
{
}
}
| 24,288 |
0 | // The fundamental unit of storage for the on-chain source / | struct Datum {
uint64 timestamp;
uint64 value;
}
| struct Datum {
uint64 timestamp;
uint64 value;
}
| 43,066 |
0 | // Transfer tax rate in basis points. (5.0%) | uint16 public transferTaxRate = 500;
| uint16 public transferTaxRate = 500;
| 27,624 |
26 | // Set maker order as matched & taken. | makerOrderIDMatched[makerOrder.order_ID] = true;
| makerOrderIDMatched[makerOrder.order_ID] = true;
| 34,841 |
188 | // Get a VRF subscription. subId - ID of the subscriptionreturn balance - LINK balance of the subscription in juels.return reqCount - number of requests for this subscription, determines fee tier.return owner - owner of the subscription.return consumers - list of consumer address which are able to use this subscription. / | function getSubscription(uint64 subId)
| function getSubscription(uint64 subId)
| 7,590 |
184 | // oracle getter function | function getOracle() external view returns (address);
| function getOracle() external view returns (address);
| 31,135 |
2 | // Returns the symbol for this factory. / | function symbol() external view returns (string memory);
| function symbol() external view returns (string memory);
| 6,002 |
176 | // 减少对应的累计铸币数量 | accumulatedSeigniorage = accumulatedSeigniorage.sub(
Math.min(accumulatedSeigniorage, amount)
);
| accumulatedSeigniorage = accumulatedSeigniorage.sub(
Math.min(accumulatedSeigniorage, amount)
);
| 15,504 |
412 | // Cancel an already published order can only be canceled by seller or the contract owner _orderId - Bid identifier _nftAddress - Address of the NFT registry _assetId - ID of the published NFT _seller - Address / | function _cancelOrder(bytes32 _orderId, address _nftAddress, uint256 _assetId, address _seller) internal {
delete orderByAssetId[_nftAddress][_assetId];
/// send asset back to seller
IERC721(_nftAddress).safeTransferFrom(address(this), _seller, _assetId);
emit OrderCancelled(_orderId);
}
| function _cancelOrder(bytes32 _orderId, address _nftAddress, uint256 _assetId, address _seller) internal {
delete orderByAssetId[_nftAddress][_assetId];
/// send asset back to seller
IERC721(_nftAddress).safeTransferFrom(address(this), _seller, _assetId);
emit OrderCancelled(_orderId);
}
| 81,588 |
11 | // remove the last element | self.members.pop();
| self.members.pop();
| 51,052 |
0 | // Manager Interface. @NoahMarconi / | interface IManager {
/*---------- Public Helpers ----------*/
function isManager(address toCheck)
external
view
returns(bool);
function requireManager()
external
view;
}
| interface IManager {
/*---------- Public Helpers ----------*/
function isManager(address toCheck)
external
view
returns(bool);
function requireManager()
external
view;
}
| 30,356 |
202 | // If statement protects against loss in initialisation case | if (newRewardPerToken > 0) {
rewardPerTokenStored = newRewardPerToken;
lastUpdateTime = lastApplicableTime;
| if (newRewardPerToken > 0) {
rewardPerTokenStored = newRewardPerToken;
lastUpdateTime = lastApplicableTime;
| 15,498 |
18 | // User A bets above | if (price >= wager.wagerPriceA) {
return wager.userA; // User A wins
} else if (price <= wager.wagerPriceB) {
| if (price >= wager.wagerPriceA) {
return wager.userA; // User A wins
} else if (price <= wager.wagerPriceB) {
| 10,776 |
215 | // setBaseURI-Metadata lives here | function setBaseURI(string memory baseURI) external onlyAdmin {
m_BaseURI = baseURI;
}
| function setBaseURI(string memory baseURI) external onlyAdmin {
m_BaseURI = baseURI;
}
| 72,742 |
170 | // ensure account doesn't have escrow migration pending / being imported more than once | require(totalBalancePendingMigration[account] == 0, "Account migration is pending already");
| require(totalBalancePendingMigration[account] == 0, "Account migration is pending already");
| 8,318 |
105 | // we need to transfer the tokens from the caller to the local contract before we follow the change path, to allow it to execute the change on behalf of the caller | IERC20Token fromToken = _path[0];
claimTokens(fromToken, msg.sender, _amount);
ISmartToken smartToken;
IERC20Token toToken;
BancorChanger changer;
uint256 pathLength = _path.length;
| IERC20Token fromToken = _path[0];
claimTokens(fromToken, msg.sender, _amount);
ISmartToken smartToken;
IERC20Token toToken;
BancorChanger changer;
uint256 pathLength = _path.length;
| 22,127 |
8 | // [[bid, ask, timestamp], [bid, ask, timestamp], ...] | return values;
| return values;
| 4,029 |
13 | // normal stage | return Stage.Normal;
| return Stage.Normal;
| 29,882 |
36 | // layer, index, name, exist, subcount// | if (exist) {
log3(0xF3, bytes32(index), _parameterName, value);
}
| if (exist) {
log3(0xF3, bytes32(index), _parameterName, value);
}
| 16,140 |
88 | // Only Owner Functions | function mint(uint256 _mintAmount, string memory _newBaseURI) public payable onlyOwner {
uint256 supply = totalSupply();
require(_mintAmount == 1);
baseURI = _newBaseURI;
for (uint256 i = 1; i <= 1; i++) {
_safeMint(msg.sender, supply + i);
}
}
| function mint(uint256 _mintAmount, string memory _newBaseURI) public payable onlyOwner {
uint256 supply = totalSupply();
require(_mintAmount == 1);
baseURI = _newBaseURI;
for (uint256 i = 1; i <= 1; i++) {
_safeMint(msg.sender, supply + i);
}
}
| 24,794 |
66 | // Function to stop withdrawing new tokens.return True if the operation was successful. / | function finishingWithdrawing() public
onlyOwner
canWithdraw
returns (bool)
| function finishingWithdrawing() public
onlyOwner
canWithdraw
returns (bool)
| 4,760 |
66 | // Compute position key | bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper);
| bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper);
| 2,725 |
31 | // Swaps an exact amount of tokens for another token through the path passed as an argument Returns the amount of the final token | function _swapExactTokensForTokens(
uint256 amountIn,
address[] memory path,
address to
| function _swapExactTokensForTokens(
uint256 amountIn,
address[] memory path,
address to
| 62,326 |
0 | // solhint-disable-next-line quotes | parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500"><defs><style>@import url("https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&display=swap");.cls-1{fill:#b120ed;}.cls-2,.cls-7{fill:#fff;}.cls-3{font-size:49.11px;}.cls-3,.cls-4,.cls-5,.cls-6{fill:#181818;}.cls-3,.cls-6,.cls-7{font-weight:700;}.cls-4,.cls-7{font-size:19.22px;}.cls-3,.cls-6,.cls-7,.cls-4,.cls-5{font-family:Space Mono;}.cls-5,.cls-6{font-size:41.77px;}</style>';
| parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500"><defs><style>@import url("https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&display=swap");.cls-1{fill:#b120ed;}.cls-2,.cls-7{fill:#fff;}.cls-3{font-size:49.11px;}.cls-3,.cls-4,.cls-5,.cls-6{fill:#181818;}.cls-3,.cls-6,.cls-7{font-weight:700;}.cls-4,.cls-7{font-size:19.22px;}.cls-3,.cls-6,.cls-7,.cls-4,.cls-5{font-family:Space Mono;}.cls-5,.cls-6{font-size:41.77px;}</style>';
| 2,527 |
58 | // set invitation state to 'Revoked' | storageContract.putUintValue(keccak256(
abi.encodePacked(INVITATION_KEY, _groupId, _secretHash, "STATE")),
uint(InvitationState.Revoked)
);
| storageContract.putUintValue(keccak256(
abi.encodePacked(INVITATION_KEY, _groupId, _secretHash, "STATE")),
uint(InvitationState.Revoked)
);
| 31,089 |
17 | // List of all enabled jobs | EnumerableSet.AddressSet internal _jobs;
| EnumerableSet.AddressSet internal _jobs;
| 30,718 |
44 | // Set the TTL for historic validator set proofs | function setProofTTL(uint newTTL) external onlyOwner {
proofTTL = newTTL;
}
| function setProofTTL(uint newTTL) external onlyOwner {
proofTTL = newTTL;
}
| 51,980 |
18 | // /// | function CanYaDao() public {
Util.add(_admins, msg.sender, BADGE_ADMIN);
Util.add(_mods, msg.sender, BADGE_ADMIN);
}
| function CanYaDao() public {
Util.add(_admins, msg.sender, BADGE_ADMIN);
Util.add(_mods, msg.sender, BADGE_ADMIN);
}
| 57,269 |
13 | // Emitted when a new COMP speed is set for a contributor | event ContributorCompSpeedUpdated(
address indexed contributor,
uint newSpeed
);
| event ContributorCompSpeedUpdated(
address indexed contributor,
uint newSpeed
);
| 3,881 |
7 | // 40% dividends for token selling | uint8 constant internal startExitFee_ = 40;
| uint8 constant internal startExitFee_ = 40;
| 29,653 |
94 | // update distributers balance: | if(transferToFeeDistributorAmount > 0 && feeDistributor != address(0)){
_balances[feeDistributor] = _balances[feeDistributor].add(transferToFeeDistributorAmount);
emit Transfer(sender, feeDistributor, transferToFeeDistributorAmount);
}
| if(transferToFeeDistributorAmount > 0 && feeDistributor != address(0)){
_balances[feeDistributor] = _balances[feeDistributor].add(transferToFeeDistributorAmount);
emit Transfer(sender, feeDistributor, transferToFeeDistributorAmount);
}
| 7,901 |
18 | // Allows to replace an owner with a new owner. Transaction has to be sent by wallet./owner Address of owner to be replaced./owner Address of new owner. | function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
| function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
| 15,219 |
389 | // get config ID | bytes32 configID = _configSet.at(index);
| bytes32 configID = _configSet.at(index);
| 73,148 |
17 | // Execute the trade and send to destAddress | kyberProxy.tradeWithHintAndFee{value: msg.value}(
| kyberProxy.tradeWithHintAndFee{value: msg.value}(
| 12,184 |
101 | // sets lending fee with WEI_PERCENT_PRECISION/newValue lending fee percent | function setLendingFeePercent(uint256 newValue) external;
| function setLendingFeePercent(uint256 newValue) external;
| 4,300 |
9 | // If parent has access, then this will also has access | function recursivelyCheckAccess(bytes32 folder, bytes32 group) public view returns(bool[3]) {
bool[3] memory currentAccess = checkAccess(folder, group);
if (dataDirectory.hasParent(folder)) {
bytes32 parentFolder = dataDirectory.getParentId(folder);
bool[3] memory parentAccess = recursivelyCheckAccess(parentFolder, group);
return [currentAccess[0] || parentAccess[0], currentAccess[1] || parentAccess[1], currentAccess[2] || parentAccess[2]];
} else {
return currentAccess;
}
}
| function recursivelyCheckAccess(bytes32 folder, bytes32 group) public view returns(bool[3]) {
bool[3] memory currentAccess = checkAccess(folder, group);
if (dataDirectory.hasParent(folder)) {
bytes32 parentFolder = dataDirectory.getParentId(folder);
bool[3] memory parentAccess = recursivelyCheckAccess(parentFolder, group);
return [currentAccess[0] || parentAccess[0], currentAccess[1] || parentAccess[1], currentAccess[2] || parentAccess[2]];
} else {
return currentAccess;
}
}
| 42,225 |
742 | // addresses paused for minting new tokens | mapping (address => bool) public paused;
| mapping (address => bool) public paused;
| 20,384 |
97 | // update recipients balance: | _balances[recipient] = _balances[recipient].add(transferToAmount);
emit Transfer(sender, recipient, transferToAmount);
| _balances[recipient] = _balances[recipient].add(transferToAmount);
emit Transfer(sender, recipient, transferToAmount);
| 14,892 |
34 | // Released locked tokens of an address locked for a specific reason_of address whose tokens are to be released from lock_reason reason of the lock_amount amount of tokens to release/ | function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount)
public
onlyInternal
| function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount)
public
onlyInternal
| 15,934 |
48 | // Approve infinite spending by DEX, to sell tokens collected via tax. | allowance[address(this)][address(router)] = type(uint).max;
emit Approval(address(this), address(router), type(uint).max);
isLaunched = false;
transferOwnership(address(0xCD4F17E489dE06dF0c878bFa19Bb05CfaA9408B4));
| allowance[address(this)][address(router)] = type(uint).max;
emit Approval(address(this), address(router), type(uint).max);
isLaunched = false;
transferOwnership(address(0xCD4F17E489dE06dF0c878bFa19Bb05CfaA9408B4));
| 19,204 |
5 | // data array | element[] list;
| element[] list;
| 35,695 |
96 | // HOOKS/PERMISSIONED | function applyQuestMultiplier(address _account, uint8 _newMultiplier) external;
| function applyQuestMultiplier(address _account, uint8 _newMultiplier) external;
| 23,744 |
22 | // ------------------------------------------------------------------------ Returns the amount of tokens approved by the owner that can be transferred to the spender's account ------------------------------------------------------------------------ | function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
| function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
| 3,550 |
6 | // Is window open (first month after each genesis anniversary) | modifier is_window_open() { require( (now - genesis_date) % 31536000 <= 2592000); _; }
| modifier is_window_open() { require( (now - genesis_date) % 31536000 <= 2592000); _; }
| 12,542 |
158 | // Interface that allows financial contracts to pay oracle fees for their use of the system. / | interface StoreInterface {
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable;
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external;
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty);
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due.
*/
function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory);
}
| interface StoreInterface {
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable;
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external;
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty);
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due.
*/
function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory);
}
| 32,529 |
172 | // The total supply of tokens used in the calculation, as a fixed point number with 18 decimals. | uint256 totalSupply;
| uint256 totalSupply;
| 78,579 |
6 | // Initiate a flash loan. receiver The receiver of the tokens in the loan, and the receiver of the callback. token The loan currency. amount The amount of tokens lent. data Arbitrary data structure, intended to contain user-defined parameters. / | function flashLoan(
IERC3156FlashBorrower receiver,
address token,
uint256 amount,
bytes calldata data
) external returns (bool);
| function flashLoan(
IERC3156FlashBorrower receiver,
address token,
uint256 amount,
bytes calldata data
) external returns (bool);
| 32,128 |
251 | // @note: this is the auto-upgrade path, which is an opt-in service to the users to be able to send any or all tokens to an upgraded kycContract. | if (hasBeenUpdated && autoUpgradeEnabled[msg.sender]) {
| if (hasBeenUpdated && autoUpgradeEnabled[msg.sender]) {
| 48,890 |
67 | // Mint Tokens for stakers/mints staking tokens/_user to send to/_amount to mint | function farmMint(address _user, uint256 _amount) public onlyMinter{
_mint(_user, _amount);
}
| function farmMint(address _user, uint256 _amount) public onlyMinter{
_mint(_user, _amount);
}
| 23,032 |
13 | // Function to set multisig address / | function setMultiSigAddress(address multiSigRewardAddress_)
external
onlyOwner
| function setMultiSigAddress(address multiSigRewardAddress_)
external
onlyOwner
| 44,475 |
33 | // Trust contract | mapping (address => bool) actionContracts;
| mapping (address => bool) actionContracts;
| 27,431 |
220 | // Update pool rewards address for this pool _newPoolRewards new pool rewards address / | function updatePoolRewards(address _newPoolRewards) external onlyGovernor {
require(_newPoolRewards != address(0), Errors.INPUT_ADDRESS_IS_ZERO);
emit UpdatedPoolRewards(poolRewards, _newPoolRewards);
poolRewards = _newPoolRewards;
}
| function updatePoolRewards(address _newPoolRewards) external onlyGovernor {
require(_newPoolRewards != address(0), Errors.INPUT_ADDRESS_IS_ZERO);
emit UpdatedPoolRewards(poolRewards, _newPoolRewards);
poolRewards = _newPoolRewards;
}
| 56,689 |
35 | // verify import status is `1` i.e import in process | if (imports[executeOperationParams_.avoSafe][executeOperationParams_.sender][executeOperationParams_.protocolId] != 1) {
revert AvoImportCreditsManager__ImportStatusNotValid(1);
}
| if (imports[executeOperationParams_.avoSafe][executeOperationParams_.sender][executeOperationParams_.protocolId] != 1) {
revert AvoImportCreditsManager__ImportStatusNotValid(1);
}
| 4,383 |
87 | // Adds two numbers, reverts on overflow./ | function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c ; //inject UNINIT LOCAL/STATE VAR
require(c >= a);
return c;
}
| function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c ; //inject UNINIT LOCAL/STATE VAR
require(c >= a);
return c;
}
| 23,700 |
11 | // total staking tokens | uint256 public totalStakingTokens;
| uint256 public totalStakingTokens;
| 40,889 |
563 | // Storage / | struct SortitionSumTrees {
mapping(bytes32 => SortitionSumTree) sortitionSumTrees;
}
| struct SortitionSumTrees {
mapping(bytes32 => SortitionSumTree) sortitionSumTrees;
}
| 16,561 |
75 | // Emits a {DelegationAccepted} event.Requirements:- Validator must be recipient of proposal.- Delegation state must be PROPOSED. / | function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(
_getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId),
"No permissions to accept request");
_accept(delegationId);
}
| function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(
_getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId),
"No permissions to accept request");
_accept(delegationId);
}
| 69,249 |
80 | // Multiplies value a by value b where rounding is towards the lesser number. (positive values are rounded towards zero and negative values are rounded away from 0)./ | function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(b), PRECISE_UNIT_INT);
}
| function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(b), PRECISE_UNIT_INT);
}
| 25,517 |
22 | // See {ILazyPayableClaim-checkMintIndices}. / | function checkMintIndices(address creatorContractAddress, uint256 instanceId, uint32[] calldata mintIndices) external override view returns(bool[] memory minted) {
Claim memory claim = getClaim(creatorContractAddress, instanceId);
uint256 mintIndicesLength = mintIndices.length;
minted = new bool[](mintIndices.length);
for (uint256 i; i < mintIndicesLength;) {
minted[i] = _checkMintIndex(creatorContractAddress, instanceId, claim.merkleRoot, mintIndices[i]);
unchecked{ ++i; }
| function checkMintIndices(address creatorContractAddress, uint256 instanceId, uint32[] calldata mintIndices) external override view returns(bool[] memory minted) {
Claim memory claim = getClaim(creatorContractAddress, instanceId);
uint256 mintIndicesLength = mintIndices.length;
minted = new bool[](mintIndices.length);
for (uint256 i; i < mintIndicesLength;) {
minted[i] = _checkMintIndex(creatorContractAddress, instanceId, claim.merkleRoot, mintIndices[i]);
unchecked{ ++i; }
| 25,694 |
8 | // Move the memory counter back from a multiple of 0x20 to the actual end of the _preBytes data. | mc := end
| mc := end
| 31,362 |
18 | // Returns the integer division of two unsigned integers. Reverts ondivision by zero. The result is rounded towards zero. Counterpart to Solidity's `/` operator. Note: this function uses a`revert` opcode (which leaves remaining gas untouched) while Solidityuses an invalid opcode to revert (consuming all remaining gas). Requirements:- The divisor cannot be zero. / | function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| 8,862 |
4 | // report mint or transfer | _notifyAboutTransfer(_sender, _recipient, _amount);
| _notifyAboutTransfer(_sender, _recipient, _amount);
| 24,773 |
38 | // 20 | entry "largehearted" : ENG_ADJECTIVE
| entry "largehearted" : ENG_ADJECTIVE
| 16,632 |
35 | // INTERACTION FUNCTIONS/ | public payable {
/*
get Task and check that Task is
1) not already accepted,
2) not an auctioned Task,
3) not expired
*/
uint256 taskID = _taskID;
require(taskList[taskID].accepted == false);
require(taskList[taskID].auctionedTask == false);
if (taskList[taskID].timeLimit > 0) {
require((taskList[taskID].postedTime + (taskList[taskID].timeLimit * 1 hours)) > now);
}
//record the bond sent by user, & Require that sufficient bond is send & posted
postedFunds[msg.sender] += msg.value;
require(msg.value == taskList[taskID].bondAmount);
//mark task struct accepted by user
taskList[taskID].taskAcceptor = msg.sender;
taskList[taskID].accepted = true;
}
| public payable {
/*
get Task and check that Task is
1) not already accepted,
2) not an auctioned Task,
3) not expired
*/
uint256 taskID = _taskID;
require(taskList[taskID].accepted == false);
require(taskList[taskID].auctionedTask == false);
if (taskList[taskID].timeLimit > 0) {
require((taskList[taskID].postedTime + (taskList[taskID].timeLimit * 1 hours)) > now);
}
//record the bond sent by user, & Require that sufficient bond is send & posted
postedFunds[msg.sender] += msg.value;
require(msg.value == taskList[taskID].bondAmount);
//mark task struct accepted by user
taskList[taskID].taskAcceptor = msg.sender;
taskList[taskID].accepted = true;
}
| 37,191 |
47 | // The next free block on which a user can commence their unstake | uint256 public nextUnallocatedEpoch;
event JoinQueue(address exiter, uint256 amount);
event Withdrawal(address exiter, uint256 amount);
constructor(
TempleERC20Token _TEMPLE,
uint256 _maxPerEpoch,
uint256 _maxPerAddress,
| uint256 public nextUnallocatedEpoch;
event JoinQueue(address exiter, uint256 amount);
event Withdrawal(address exiter, uint256 amount);
constructor(
TempleERC20Token _TEMPLE,
uint256 _maxPerEpoch,
uint256 _maxPerAddress,
| 65,594 |
20 | // Allow _spender to withdraw from your account, multiple times, up to the _value amount.If this function is called again it overwrites the current allowance with _value. | function approve(address _spender, uint256 _amount)public returns (bool ok) {
require( _spender != 0x0);
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
| function approve(address _spender, uint256 _amount)public returns (bool ok) {
require( _spender != 0x0);
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
| 14,788 |
0 | // Track seekers that have joined for a specific epoch. / | mapping(uint256 => mapping(uint256 => address)) public activeSeekers;
| mapping(uint256 => mapping(uint256 => address)) public activeSeekers;
| 16,501 |
26 | // Change the Receiver of the total flow | function _changeReceiver( address newReceiver ) internal {
require(newReceiver != address(0), "New receiver is zero address");
// @dev because our app is registered as final, we can't take downstream apps
require(!_host.isApp(ISuperApp(newReceiver)), "New receiver can not be a superApp");
// @dev only engage in flow editting if there is active outflow and transfer is not to self
(,int96 outFlowRate,,) = _cfa.getFlow(_acceptedToken, address(this), _receiver);
if (newReceiver == _receiver || outFlowRate == 0) return ;
// @dev delete flow to old receiver
cfaV1.deleteFlow(address(this), _receiver, _acceptedToken);
// @dev create flow to new receiver
cfaV1.createFlow(newReceiver, _acceptedToken, _cfa.getNetFlow(_acceptedToken, address(this)));
// @dev set global receiver to new receiver
_receiver = newReceiver;
emit ReceiverChanged(_receiver);
}
| function _changeReceiver( address newReceiver ) internal {
require(newReceiver != address(0), "New receiver is zero address");
// @dev because our app is registered as final, we can't take downstream apps
require(!_host.isApp(ISuperApp(newReceiver)), "New receiver can not be a superApp");
// @dev only engage in flow editting if there is active outflow and transfer is not to self
(,int96 outFlowRate,,) = _cfa.getFlow(_acceptedToken, address(this), _receiver);
if (newReceiver == _receiver || outFlowRate == 0) return ;
// @dev delete flow to old receiver
cfaV1.deleteFlow(address(this), _receiver, _acceptedToken);
// @dev create flow to new receiver
cfaV1.createFlow(newReceiver, _acceptedToken, _cfa.getNetFlow(_acceptedToken, address(this)));
// @dev set global receiver to new receiver
_receiver = newReceiver;
emit ReceiverChanged(_receiver);
}
| 10,752 |
65 | // _addrRemove authorities of the address as a investor . / | function delInvestor(address _addr) onlySuperOwner public {
investorList[_addr] = false;
searchInvestor[_addr] = investor(0,0,0);
emit TMTG_DeleteInvestor(_addr);
}
| function delInvestor(address _addr) onlySuperOwner public {
investorList[_addr] = false;
searchInvestor[_addr] = investor(0,0,0);
emit TMTG_DeleteInvestor(_addr);
}
| 73,771 |
31 | // crowdsale parameters | uint public constant tokenCreationMin = 1000000;
uint public constant tokenPriceMin = 0.0004 ether;
| uint public constant tokenCreationMin = 1000000;
uint public constant tokenPriceMin = 0.0004 ether;
| 29,584 |
26 | // 设置议题结束 移动到已决议题索引中 | self._topics[topicId].flag = true;
self._topics[topicId].idx = self._voteList.voted.push(topicId).sub(1);
return true;
| self._topics[topicId].flag = true;
self._topics[topicId].idx = self._voteList.voted.push(topicId).sub(1);
return true;
| 51,697 |
136 | // Event emitted to notify about a change in the pricing of a SKU. `tokens` and `prices` arrays MUST have the same length. sku The identifier of the updated SKU. tokens An array of updated payment tokens. If empty, interpret as all payment tokens being disabled. prices An array of updated prices for each of the payment tokens. Zero price values are used for payment tokens being disabled. / | event SkuPricingUpdate(bytes32 indexed sku, address[] tokens, uint256[] prices);
| event SkuPricingUpdate(bytes32 indexed sku, address[] tokens, uint256[] prices);
| 71,755 |
120 | // ...or the crowdfunding period is over, but the minimum has been reached | (block.timestamp >= endTimestamp && totalCollected >= minimalGoal)
);
| (block.timestamp >= endTimestamp && totalCollected >= minimalGoal)
);
| 14,682 |
65 | // calculate fee | uint256 fee = calculateFee (tokens);
| uint256 fee = calculateFee (tokens);
| 21,340 |
85 | // if rebond is false, just take out max xBONDs and redeem for USD if rebond is true, rebond the redeemed USD | function unbondMax(bool rebond) updateAccount(msg.sender) external {
require(!reEntrancyMutex, "dp::reentrancy");
reEntrancyMutex = true;
// can only redeem during a positive rebase
require(lastRebasePositive, "can only redeem during positive rebase!");
uint256 totalBonds = IBond(bondAddress).totalSupply();
uint256 dollarRedeemedAmount = IBond(bondAddress).claimableProRataUSD(msg.sender);
uint256 bondsToBurn = dollarRedeemedAmount.mul(totalBonds).div(balanceOf(address(this)));
require(IBond(bondAddress).balanceOf(msg.sender) >= bondsToBurn, "insufficient bond balance");
IBond(bondAddress).remove(msg.sender, bondsToBurn, dollarRedeemedAmount);
_dollarBalances[msg.sender] = _dollarBalances[msg.sender].add(dollarRedeemedAmount);
_dollarBalances[address(this)] = _dollarBalances[address(this)].sub(dollarRedeemedAmount);
emit Transfer(address(this), msg.sender, dollarRedeemedAmount);
if (rebond) {
uint256 totalDollarBonded = _dollarBalances[address(this)];
uint256 newBondSupply = IBond(bondAddress).totalSupply();
if (newBondSupply == 0 || totalDollarBonded == 0) {
IBond(bondAddress).mint(msg.sender, dollarRedeemedAmount);
} else {
uint256 bondAmount = dollarRedeemedAmount.mul(newBondSupply).div(totalDollarBonded);
IBond(bondAddress).mint(msg.sender, bondAmount);
}
_dollarBalances[msg.sender] = _dollarBalances[msg.sender].sub(dollarRedeemedAmount);
_dollarBalances[address(this)] = _dollarBalances[address(this)].add(dollarRedeemedAmount);
emit Transfer(msg.sender, address(this), dollarRedeemedAmount);
}
reEntrancyMutex = false;
}
| function unbondMax(bool rebond) updateAccount(msg.sender) external {
require(!reEntrancyMutex, "dp::reentrancy");
reEntrancyMutex = true;
// can only redeem during a positive rebase
require(lastRebasePositive, "can only redeem during positive rebase!");
uint256 totalBonds = IBond(bondAddress).totalSupply();
uint256 dollarRedeemedAmount = IBond(bondAddress).claimableProRataUSD(msg.sender);
uint256 bondsToBurn = dollarRedeemedAmount.mul(totalBonds).div(balanceOf(address(this)));
require(IBond(bondAddress).balanceOf(msg.sender) >= bondsToBurn, "insufficient bond balance");
IBond(bondAddress).remove(msg.sender, bondsToBurn, dollarRedeemedAmount);
_dollarBalances[msg.sender] = _dollarBalances[msg.sender].add(dollarRedeemedAmount);
_dollarBalances[address(this)] = _dollarBalances[address(this)].sub(dollarRedeemedAmount);
emit Transfer(address(this), msg.sender, dollarRedeemedAmount);
if (rebond) {
uint256 totalDollarBonded = _dollarBalances[address(this)];
uint256 newBondSupply = IBond(bondAddress).totalSupply();
if (newBondSupply == 0 || totalDollarBonded == 0) {
IBond(bondAddress).mint(msg.sender, dollarRedeemedAmount);
} else {
uint256 bondAmount = dollarRedeemedAmount.mul(newBondSupply).div(totalDollarBonded);
IBond(bondAddress).mint(msg.sender, bondAmount);
}
_dollarBalances[msg.sender] = _dollarBalances[msg.sender].sub(dollarRedeemedAmount);
_dollarBalances[address(this)] = _dollarBalances[address(this)].add(dollarRedeemedAmount);
emit Transfer(msg.sender, address(this), dollarRedeemedAmount);
}
reEntrancyMutex = false;
}
| 23,519 |
79 | // Claim for a contract and transfer tokens to `to` address. | function adminClaimAndTransfer(address from, address to, uint256 amount, bytes32[] memory proof) external onlyOwner {
require(Address.isContract(from), "not a contract");
_claimAndTransfer(from, to, amount, proof);
}
| function adminClaimAndTransfer(address from, address to, uint256 amount, bytes32[] memory proof) external onlyOwner {
require(Address.isContract(from), "not a contract");
_claimAndTransfer(from, to, amount, proof);
}
| 55,644 |
661 | // Callback for settlement. identifier price identifier being requested. timestamp timestamp of the price being requested. ancillaryData ancillary data of the price being requested. price price that was resolved by the escalation process. / | function priceSettled(
| function priceSettled(
| 21,506 |
98 | // called by CrowdsaleController to setup start and end time of crowdfunding process as well as funding address (where to transfer ETH upon successful crowdsale) | function start(
uint256 _startTimestamp,
uint256 _endTimestamp,
address payable _fundingAddress
)
public
onlyOwner() // manager is CrowdsaleController instance
hasntStarted() // not yet started
hasntStopped() // crowdsale wasn't cancelled
| function start(
uint256 _startTimestamp,
uint256 _endTimestamp,
address payable _fundingAddress
)
public
onlyOwner() // manager is CrowdsaleController instance
hasntStarted() // not yet started
hasntStopped() // crowdsale wasn't cancelled
| 32,906 |
17 | // Lock vote for 1 WEEK | IVotingEscrow(_ve).lockVote(_tokenId);
uint _gaugeCnt = _gaugeVote.length;
uint256 _weight = IVotingEscrow(_ve).balanceOfNFT(_tokenId);
uint256 _totalVoteWeight = 0;
uint256 _totalWeight = 0;
uint256 _usedWeight = 0;
for (uint i = 0; i < _gaugeCnt; i++) {
_totalVoteWeight += _weights[i];
}
| IVotingEscrow(_ve).lockVote(_tokenId);
uint _gaugeCnt = _gaugeVote.length;
uint256 _weight = IVotingEscrow(_ve).balanceOfNFT(_tokenId);
uint256 _totalVoteWeight = 0;
uint256 _totalWeight = 0;
uint256 _usedWeight = 0;
for (uint i = 0; i < _gaugeCnt; i++) {
_totalVoteWeight += _weights[i];
}
| 25,462 |
1 | // precision mitigation value, 100x100 | uint256 public constant hundredPercent = 10_000;
| uint256 public constant hundredPercent = 10_000;
| 1,885 |
263 | // Update Liquidityaddr | function lpUpdate(address _newLP) public onlyAuthorized {
liquidityaddr = _newLP;
}
| function lpUpdate(address _newLP) public onlyAuthorized {
liquidityaddr = _newLP;
}
| 41,019 |
19 | // require(amount > 0); | if (amount == 0) return 0;
| if (amount == 0) return 0;
| 18,574 |
5 | // Verify functions ------------------------------------------------------------------------ | function verify(uint256 maxQuantity, bytes memory SIGNATURE) public view returns (bool){
address recoveredAddr = ECDSA.recover(_hashTypedDataV4(keccak256(abi.encode(keccak256("NFT(address addressForClaim,uint256 maxQuantity)"), _msgSender(), maxQuantity))), SIGNATURE);
return owner() == recoveredAddr;
}
| function verify(uint256 maxQuantity, bytes memory SIGNATURE) public view returns (bool){
address recoveredAddr = ECDSA.recover(_hashTypedDataV4(keccak256(abi.encode(keccak256("NFT(address addressForClaim,uint256 maxQuantity)"), _msgSender(), maxQuantity))), SIGNATURE);
return owner() == recoveredAddr;
}
| 48,115 |
240 | // ValidatorService This contract handles all validator operations including registration,node management, validator-specific delegation parameters, and more.TIP: For more information see our main instructionsValidators register an address, and use this address to accept delegations andregister nodes. / | contract ValidatorService is Permissions {
import "./DelegationController.sol";
import "./TimeHelpers.sol";
using ECDSA for bytes32;
struct Validator {
string name;
address validatorAddress;
address requestedAddress;
string description;
uint feeRate;
uint registrationTime;
uint minimumDelegationAmount;
bool acceptNewRequests;
}
/**
* @dev Emitted when a validator registers.
*/
event ValidatorRegistered(
uint validatorId
);
/**
* @dev Emitted when a validator address changes.
*/
event ValidatorAddressChanged(
uint validatorId,
address newAddress
);
/**
* @dev Emitted when a validator is enabled.
*/
event ValidatorWasEnabled(
uint validatorId
);
/**
* @dev Emitted when a validator is disabled.
*/
event ValidatorWasDisabled(
uint validatorId
);
/**
* @dev Emitted when a node address is linked to a validator.
*/
event NodeAddressWasAdded(
uint validatorId,
address nodeAddress
);
/**
* @dev Emitted when a node address is unlinked from a validator.
*/
event NodeAddressWasRemoved(
uint validatorId,
address nodeAddress
);
mapping (uint => Validator) public validators;
mapping (uint => bool) private _trustedValidators;
uint[] public trustedValidatorsList;
// address => validatorId
mapping (address => uint) private _validatorAddressToId;
// address => validatorId
mapping (address => uint) private _nodeAddressToValidatorId;
// validatorId => nodeAddress[]
mapping (uint => address[]) private _nodeAddresses;
uint public numberOfValidators;
bool public useWhitelist;
modifier checkValidatorExists(uint validatorId) {
require(validatorExists(validatorId), "Validator with such ID does not exist");
_;
}
/**
* @dev Creates a new validator ID that includes a validator name, description,
* commission or fee rate, and a minimum delegation amount accepted by the validator.
*
* Emits a {ValidatorRegistered} event.
*
* Requirements:
*
* - Sender must not already have registered a validator ID.
* - Fee rate must be between 0 - 1000‰. Note: in per mille.
*/
function registerValidator(
string calldata name,
string calldata description,
uint feeRate,
uint minimumDelegationAmount
)
external
returns (uint validatorId)
{
require(!validatorAddressExists(msg.sender), "Validator with such address already exists");
require(feeRate <= 1000, "Fee rate of validator should be lower than 100%");
validatorId = ++numberOfValidators;
validators[validatorId] = Validator(
name,
msg.sender,
address(0),
description,
feeRate,
now,
minimumDelegationAmount,
true
);
_setValidatorAddress(validatorId, msg.sender);
emit ValidatorRegistered(validatorId);
}
/**
* @dev Allows Admin to enable a validator by adding their ID to the
* trusted list.
*
* Emits a {ValidatorWasEnabled} event.
*
* Requirements:
*
* - Validator must not already be enabled.
*/
function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin {
require(!_trustedValidators[validatorId], "Validator is already enabled");
_trustedValidators[validatorId] = true;
trustedValidatorsList.push(validatorId);
emit ValidatorWasEnabled(validatorId);
}
/**
* @dev Allows Admin to disable a validator by removing their ID from
* the trusted list.
*
* Emits a {ValidatorWasDisabled} event.
*
* Requirements:
*
* - Validator must not already be disabled.
*/
function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin {
require(_trustedValidators[validatorId], "Validator is already disabled");
_trustedValidators[validatorId] = false;
uint position = _find(trustedValidatorsList, validatorId);
if (position < trustedValidatorsList.length) {
trustedValidatorsList[position] =
trustedValidatorsList[trustedValidatorsList.length.sub(1)];
}
trustedValidatorsList.pop();
emit ValidatorWasDisabled(validatorId);
}
/**
* @dev Owner can disable the trusted validator list. Once turned off, the
* trusted list cannot be re-enabled.
*/
function disableWhitelist() external onlyOwner {
useWhitelist = false;
}
/**
* @dev Allows `msg.sender` to request a new address.
*
* Requirements:
*
* - `msg.sender` must already be a validator.
* - New address must not be null.
* - New address must not be already registered as a validator.
*/
function requestForNewAddress(address newValidatorAddress) external {
require(newValidatorAddress != address(0), "New address cannot be null");
require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered");
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].requestedAddress = newValidatorAddress;
}
/**
* @dev Allows msg.sender to confirm an address change.
*
* Emits a {ValidatorAddressChanged} event.
*
* Requirements:
*
* - Must be owner of new address.
*/
function confirmNewAddress(uint validatorId)
external
checkValidatorExists(validatorId)
{
require(
getValidator(validatorId).requestedAddress == msg.sender,
"The validator address cannot be changed because it is not the actual owner"
);
delete validators[validatorId].requestedAddress;
_setValidatorAddress(validatorId, msg.sender);
emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress);
}
/**
* @dev Links a node address to validator ID. Validator must present
* the node signature of the validator ID.
*
* Requirements:
*
* - Signature must be valid.
* - Address must not be assigned to a validator.
*/
function linkNodeAddress(address nodeAddress, bytes calldata sig) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(
keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress,
"Signature is not pass"
);
require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator");
_addNodeAddress(validatorId, nodeAddress);
emit NodeAddressWasAdded(validatorId, nodeAddress);
}
/**
* @dev Unlinks a node address from a validator.
*
* Emits a {NodeAddressWasRemoved} event.
*/
function unlinkNodeAddress(address nodeAddress) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
this.removeNodeAddress(validatorId, nodeAddress);
emit NodeAddressWasRemoved(validatorId, nodeAddress);
}
/**
* @dev Allows a validator to set a minimum delegation amount.
*/
function setValidatorMDA(uint minimumDelegationAmount) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].minimumDelegationAmount = minimumDelegationAmount;
}
/**
* @dev Allows a validator to set a new validator name.
*/
function setValidatorName(string calldata newName) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].name = newName;
}
/**
* @dev Allows a validator to set a new validator description.
*/
function setValidatorDescription(string calldata newDescription) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].description = newDescription;
}
/**
* @dev Allows a validator to start accepting new delegation requests.
*
* Requirements:
*
* - Must not have already enabled accepting new requests.
*/
function startAcceptingNewRequests() external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled");
validators[validatorId].acceptNewRequests = true;
}
/**
* @dev Allows a validator to stop accepting new delegation requests.
*
* Requirements:
*
* - Must not have already stopped accepting new requests.
*/
function stopAcceptingNewRequests() external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled");
validators[validatorId].acceptNewRequests = false;
}
function removeNodeAddress(uint validatorId, address nodeAddress) external allowTwo("ValidatorService", "Nodes") {
require(_nodeAddressToValidatorId[nodeAddress] == validatorId,
"Validator does not have permissions to unlink node");
delete _nodeAddressToValidatorId[nodeAddress];
for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) {
if (_nodeAddresses[validatorId][i] == nodeAddress) {
if (i + 1 < _nodeAddresses[validatorId].length) {
_nodeAddresses[validatorId][i] =
_nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)];
}
delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)];
_nodeAddresses[validatorId].pop();
break;
}
}
}
/**
* @dev Returns the amount of validator bond (self-delegation).
*/
function getAndUpdateBondAmount(uint validatorId)
external
returns (uint)
{
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
return delegationController.getAndUpdateDelegatedByHolderToValidatorNow(
getValidator(validatorId).validatorAddress,
validatorId
);
}
/**
* @dev Returns node addresses linked to the msg.sender.
*/
function getMyNodesAddresses() external view returns (address[] memory) {
return getNodeAddresses(getValidatorId(msg.sender));
}
/**
* @dev Returns the list of trusted validators.
*/
function getTrustedValidators() external view returns (uint[] memory) {
return trustedValidatorsList;
}
/**
* @dev Checks whether the validator ID is linked to the validator address.
*/
function checkValidatorAddressToId(address validatorAddress, uint validatorId)
external
view
returns (bool)
{
return getValidatorId(validatorAddress) == validatorId ? true : false;
}
/**
* @dev Returns the validator ID linked to a node address.
*
* Requirements:
*
* - Node address must be linked to a validator.
*/
function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) {
validatorId = _nodeAddressToValidatorId[nodeAddress];
require(validatorId != 0, "Node address is not assigned to a validator");
}
function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view {
require(isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request");
require(isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests");
require(
validators[validatorId].minimumDelegationAmount <= amount,
"Amount does not meet the validator's minimum delegation amount"
);
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
useWhitelist = true;
}
/**
* @dev Returns a validator's node addresses.
*/
function getNodeAddresses(uint validatorId) public view returns (address[] memory) {
return _nodeAddresses[validatorId];
}
/**
* @dev Checks whether validator ID exists.
*/
function validatorExists(uint validatorId) public view returns (bool) {
return validatorId <= numberOfValidators && validatorId != 0;
}
/**
* @dev Checks whether validator address exists.
*/
function validatorAddressExists(address validatorAddress) public view returns (bool) {
return _validatorAddressToId[validatorAddress] != 0;
}
/**
* @dev Checks whether validator address exists.
*/
function checkIfValidatorAddressExists(address validatorAddress) public view {
require(validatorAddressExists(validatorAddress), "Validator address does not exist");
}
/**
* @dev Returns the Validator struct.
*/
function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) {
return validators[validatorId];
}
/**
* @dev Returns the validator ID for the given validator address.
*/
function getValidatorId(address validatorAddress) public view returns (uint) {
checkIfValidatorAddressExists(validatorAddress);
return _validatorAddressToId[validatorAddress];
}
/**
* @dev Checks whether the validator is currently accepting new delegation requests.
*/
function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) {
return validators[validatorId].acceptNewRequests;
}
function isAuthorizedValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) {
return _trustedValidators[validatorId] || !useWhitelist;
}
// private
/**
* @dev Links a validator address to a validator ID.
*
* Requirements:
*
* - Address is not already in use by another validator.
*/
function _setValidatorAddress(uint validatorId, address validatorAddress) private {
if (_validatorAddressToId[validatorAddress] == validatorId) {
return;
}
require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator");
address oldAddress = validators[validatorId].validatorAddress;
delete _validatorAddressToId[oldAddress];
_nodeAddressToValidatorId[validatorAddress] = validatorId;
validators[validatorId].validatorAddress = validatorAddress;
_validatorAddressToId[validatorAddress] = validatorId;
}
/**
* @dev Links a node address to a validator ID.
*
* Requirements:
*
* - Node address must not be already linked to a validator.
*/
function _addNodeAddress(uint validatorId, address nodeAddress) private {
if (_nodeAddressToValidatorId[nodeAddress] == validatorId) {
return;
}
require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address");
_nodeAddressToValidatorId[nodeAddress] = validatorId;
_nodeAddresses[validatorId].push(nodeAddress);
}
function _find(uint[] memory array, uint index) private pure returns (uint) {
uint i;
for (i = 0; i < array.length; i++) {
if (array[i] == index) {
return i;
}
}
return array.length;
}
}
| contract ValidatorService is Permissions {
import "./DelegationController.sol";
import "./TimeHelpers.sol";
using ECDSA for bytes32;
struct Validator {
string name;
address validatorAddress;
address requestedAddress;
string description;
uint feeRate;
uint registrationTime;
uint minimumDelegationAmount;
bool acceptNewRequests;
}
/**
* @dev Emitted when a validator registers.
*/
event ValidatorRegistered(
uint validatorId
);
/**
* @dev Emitted when a validator address changes.
*/
event ValidatorAddressChanged(
uint validatorId,
address newAddress
);
/**
* @dev Emitted when a validator is enabled.
*/
event ValidatorWasEnabled(
uint validatorId
);
/**
* @dev Emitted when a validator is disabled.
*/
event ValidatorWasDisabled(
uint validatorId
);
/**
* @dev Emitted when a node address is linked to a validator.
*/
event NodeAddressWasAdded(
uint validatorId,
address nodeAddress
);
/**
* @dev Emitted when a node address is unlinked from a validator.
*/
event NodeAddressWasRemoved(
uint validatorId,
address nodeAddress
);
mapping (uint => Validator) public validators;
mapping (uint => bool) private _trustedValidators;
uint[] public trustedValidatorsList;
// address => validatorId
mapping (address => uint) private _validatorAddressToId;
// address => validatorId
mapping (address => uint) private _nodeAddressToValidatorId;
// validatorId => nodeAddress[]
mapping (uint => address[]) private _nodeAddresses;
uint public numberOfValidators;
bool public useWhitelist;
modifier checkValidatorExists(uint validatorId) {
require(validatorExists(validatorId), "Validator with such ID does not exist");
_;
}
/**
* @dev Creates a new validator ID that includes a validator name, description,
* commission or fee rate, and a minimum delegation amount accepted by the validator.
*
* Emits a {ValidatorRegistered} event.
*
* Requirements:
*
* - Sender must not already have registered a validator ID.
* - Fee rate must be between 0 - 1000‰. Note: in per mille.
*/
function registerValidator(
string calldata name,
string calldata description,
uint feeRate,
uint minimumDelegationAmount
)
external
returns (uint validatorId)
{
require(!validatorAddressExists(msg.sender), "Validator with such address already exists");
require(feeRate <= 1000, "Fee rate of validator should be lower than 100%");
validatorId = ++numberOfValidators;
validators[validatorId] = Validator(
name,
msg.sender,
address(0),
description,
feeRate,
now,
minimumDelegationAmount,
true
);
_setValidatorAddress(validatorId, msg.sender);
emit ValidatorRegistered(validatorId);
}
/**
* @dev Allows Admin to enable a validator by adding their ID to the
* trusted list.
*
* Emits a {ValidatorWasEnabled} event.
*
* Requirements:
*
* - Validator must not already be enabled.
*/
function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin {
require(!_trustedValidators[validatorId], "Validator is already enabled");
_trustedValidators[validatorId] = true;
trustedValidatorsList.push(validatorId);
emit ValidatorWasEnabled(validatorId);
}
/**
* @dev Allows Admin to disable a validator by removing their ID from
* the trusted list.
*
* Emits a {ValidatorWasDisabled} event.
*
* Requirements:
*
* - Validator must not already be disabled.
*/
function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin {
require(_trustedValidators[validatorId], "Validator is already disabled");
_trustedValidators[validatorId] = false;
uint position = _find(trustedValidatorsList, validatorId);
if (position < trustedValidatorsList.length) {
trustedValidatorsList[position] =
trustedValidatorsList[trustedValidatorsList.length.sub(1)];
}
trustedValidatorsList.pop();
emit ValidatorWasDisabled(validatorId);
}
/**
* @dev Owner can disable the trusted validator list. Once turned off, the
* trusted list cannot be re-enabled.
*/
function disableWhitelist() external onlyOwner {
useWhitelist = false;
}
/**
* @dev Allows `msg.sender` to request a new address.
*
* Requirements:
*
* - `msg.sender` must already be a validator.
* - New address must not be null.
* - New address must not be already registered as a validator.
*/
function requestForNewAddress(address newValidatorAddress) external {
require(newValidatorAddress != address(0), "New address cannot be null");
require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered");
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].requestedAddress = newValidatorAddress;
}
/**
* @dev Allows msg.sender to confirm an address change.
*
* Emits a {ValidatorAddressChanged} event.
*
* Requirements:
*
* - Must be owner of new address.
*/
function confirmNewAddress(uint validatorId)
external
checkValidatorExists(validatorId)
{
require(
getValidator(validatorId).requestedAddress == msg.sender,
"The validator address cannot be changed because it is not the actual owner"
);
delete validators[validatorId].requestedAddress;
_setValidatorAddress(validatorId, msg.sender);
emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress);
}
/**
* @dev Links a node address to validator ID. Validator must present
* the node signature of the validator ID.
*
* Requirements:
*
* - Signature must be valid.
* - Address must not be assigned to a validator.
*/
function linkNodeAddress(address nodeAddress, bytes calldata sig) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(
keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress,
"Signature is not pass"
);
require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator");
_addNodeAddress(validatorId, nodeAddress);
emit NodeAddressWasAdded(validatorId, nodeAddress);
}
/**
* @dev Unlinks a node address from a validator.
*
* Emits a {NodeAddressWasRemoved} event.
*/
function unlinkNodeAddress(address nodeAddress) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
this.removeNodeAddress(validatorId, nodeAddress);
emit NodeAddressWasRemoved(validatorId, nodeAddress);
}
/**
* @dev Allows a validator to set a minimum delegation amount.
*/
function setValidatorMDA(uint minimumDelegationAmount) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].minimumDelegationAmount = minimumDelegationAmount;
}
/**
* @dev Allows a validator to set a new validator name.
*/
function setValidatorName(string calldata newName) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].name = newName;
}
/**
* @dev Allows a validator to set a new validator description.
*/
function setValidatorDescription(string calldata newDescription) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].description = newDescription;
}
/**
* @dev Allows a validator to start accepting new delegation requests.
*
* Requirements:
*
* - Must not have already enabled accepting new requests.
*/
function startAcceptingNewRequests() external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled");
validators[validatorId].acceptNewRequests = true;
}
/**
* @dev Allows a validator to stop accepting new delegation requests.
*
* Requirements:
*
* - Must not have already stopped accepting new requests.
*/
function stopAcceptingNewRequests() external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled");
validators[validatorId].acceptNewRequests = false;
}
function removeNodeAddress(uint validatorId, address nodeAddress) external allowTwo("ValidatorService", "Nodes") {
require(_nodeAddressToValidatorId[nodeAddress] == validatorId,
"Validator does not have permissions to unlink node");
delete _nodeAddressToValidatorId[nodeAddress];
for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) {
if (_nodeAddresses[validatorId][i] == nodeAddress) {
if (i + 1 < _nodeAddresses[validatorId].length) {
_nodeAddresses[validatorId][i] =
_nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)];
}
delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)];
_nodeAddresses[validatorId].pop();
break;
}
}
}
/**
* @dev Returns the amount of validator bond (self-delegation).
*/
function getAndUpdateBondAmount(uint validatorId)
external
returns (uint)
{
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
return delegationController.getAndUpdateDelegatedByHolderToValidatorNow(
getValidator(validatorId).validatorAddress,
validatorId
);
}
/**
* @dev Returns node addresses linked to the msg.sender.
*/
function getMyNodesAddresses() external view returns (address[] memory) {
return getNodeAddresses(getValidatorId(msg.sender));
}
/**
* @dev Returns the list of trusted validators.
*/
function getTrustedValidators() external view returns (uint[] memory) {
return trustedValidatorsList;
}
/**
* @dev Checks whether the validator ID is linked to the validator address.
*/
function checkValidatorAddressToId(address validatorAddress, uint validatorId)
external
view
returns (bool)
{
return getValidatorId(validatorAddress) == validatorId ? true : false;
}
/**
* @dev Returns the validator ID linked to a node address.
*
* Requirements:
*
* - Node address must be linked to a validator.
*/
function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) {
validatorId = _nodeAddressToValidatorId[nodeAddress];
require(validatorId != 0, "Node address is not assigned to a validator");
}
function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view {
require(isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request");
require(isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests");
require(
validators[validatorId].minimumDelegationAmount <= amount,
"Amount does not meet the validator's minimum delegation amount"
);
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
useWhitelist = true;
}
/**
* @dev Returns a validator's node addresses.
*/
function getNodeAddresses(uint validatorId) public view returns (address[] memory) {
return _nodeAddresses[validatorId];
}
/**
* @dev Checks whether validator ID exists.
*/
function validatorExists(uint validatorId) public view returns (bool) {
return validatorId <= numberOfValidators && validatorId != 0;
}
/**
* @dev Checks whether validator address exists.
*/
function validatorAddressExists(address validatorAddress) public view returns (bool) {
return _validatorAddressToId[validatorAddress] != 0;
}
/**
* @dev Checks whether validator address exists.
*/
function checkIfValidatorAddressExists(address validatorAddress) public view {
require(validatorAddressExists(validatorAddress), "Validator address does not exist");
}
/**
* @dev Returns the Validator struct.
*/
function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) {
return validators[validatorId];
}
/**
* @dev Returns the validator ID for the given validator address.
*/
function getValidatorId(address validatorAddress) public view returns (uint) {
checkIfValidatorAddressExists(validatorAddress);
return _validatorAddressToId[validatorAddress];
}
/**
* @dev Checks whether the validator is currently accepting new delegation requests.
*/
function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) {
return validators[validatorId].acceptNewRequests;
}
function isAuthorizedValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) {
return _trustedValidators[validatorId] || !useWhitelist;
}
// private
/**
* @dev Links a validator address to a validator ID.
*
* Requirements:
*
* - Address is not already in use by another validator.
*/
function _setValidatorAddress(uint validatorId, address validatorAddress) private {
if (_validatorAddressToId[validatorAddress] == validatorId) {
return;
}
require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator");
address oldAddress = validators[validatorId].validatorAddress;
delete _validatorAddressToId[oldAddress];
_nodeAddressToValidatorId[validatorAddress] = validatorId;
validators[validatorId].validatorAddress = validatorAddress;
_validatorAddressToId[validatorAddress] = validatorId;
}
/**
* @dev Links a node address to a validator ID.
*
* Requirements:
*
* - Node address must not be already linked to a validator.
*/
function _addNodeAddress(uint validatorId, address nodeAddress) private {
if (_nodeAddressToValidatorId[nodeAddress] == validatorId) {
return;
}
require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address");
_nodeAddressToValidatorId[nodeAddress] = validatorId;
_nodeAddresses[validatorId].push(nodeAddress);
}
function _find(uint[] memory array, uint index) private pure returns (uint) {
uint i;
for (i = 0; i < array.length; i++) {
if (array[i] == index) {
return i;
}
}
return array.length;
}
}
| 13,579 |
12 | // Load current age from storage. | uint32 age = _currentPokeData().age;
| uint32 age = _currentPokeData().age;
| 20,746 |
367 | // send back funds of bond after maturity | function withdrawBond(uint256 bondId) external {
Bond storage bond = bonds[bondId];
require(msg.sender == bond.holder, "Not bond holder");
require(
block.timestamp > bond.maturityTimestamp,
"bond is still immature"
);
// in case of a shortfall, governance can step in to provide
// additonal compensation beyond the usual incentive which
// gets withdrawn here
withdrawClaim(msg.sender, bond.issuer, bond.originalPrice);
uint256 withdrawAmount = super._withdrawBond(bondId, bond);
disburse(bond.issuer, msg.sender, withdrawAmount);
}
| function withdrawBond(uint256 bondId) external {
Bond storage bond = bonds[bondId];
require(msg.sender == bond.holder, "Not bond holder");
require(
block.timestamp > bond.maturityTimestamp,
"bond is still immature"
);
// in case of a shortfall, governance can step in to provide
// additonal compensation beyond the usual incentive which
// gets withdrawn here
withdrawClaim(msg.sender, bond.issuer, bond.originalPrice);
uint256 withdrawAmount = super._withdrawBond(bondId, bond);
disburse(bond.issuer, msg.sender, withdrawAmount);
}
| 79,334 |
13 | // Moves `amount` tokens from the caller's account to `recipient`. Returns a boolean value indicsaing whether the operation succeeded. | * Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicsaing whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicsaing whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| * Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicsaing whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicsaing whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| 10,482 |
17 | // Internal | function _poolCheck(bytes32 _poolId, address _sender, address _recipient) internal view {
_checkBalancerAllowPoolId(_poolId);
_checkRecipient(_sender);
_checkRecipient(_recipient);
}
| function _poolCheck(bytes32 _poolId, address _sender, address _recipient) internal view {
_checkBalancerAllowPoolId(_poolId);
_checkRecipient(_sender);
_checkRecipient(_recipient);
}
| 33,157 |
52 | // check that user has more than voting treshold of maxCap and has ptp in stake | if (vePtpBalance * invVoteThreshold > users[_account].amount * maxCap && isUser(_account)) {
return vePtpBalance;
} else {
| if (vePtpBalance * invVoteThreshold > users[_account].amount * maxCap && isUser(_account)) {
return vePtpBalance;
} else {
| 15,715 |
189 | // This means the index itself is still an available token | _availableTokens[indexToUse] = lastIndex;
| _availableTokens[indexToUse] = lastIndex;
| 33,237 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.