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
|
---|---|---|---|---|
3 | // Returns the amount of free deposits left. / | function freeDeposits() external returns (uint256);
| function freeDeposits() external returns (uint256);
| 21,839 |
4 | // Constructs a new instance of the SubscribableService support contract/price The price in Wei for the services provided by the contract | constructor(uint256 price) {
subscriptionPrice_ = price;
}
| constructor(uint256 price) {
subscriptionPrice_ = price;
}
| 26,111 |
6 | // Throws if called by any account other than the owner./ | modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
| modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
| 2,721 |
148 | // The ERC20 ownix token | IOwnixERC20 immutable public ownixToken;
| IOwnixERC20 immutable public ownixToken;
| 5,650 |
300 | // Returns number of schains by schain owner. / | function getSchainListSize(address from) external view returns (uint) {
return schainIndexes[from].length;
}
| function getSchainListSize(address from) external view returns (uint) {
return schainIndexes[from].length;
}
| 57,335 |
47 | // Deprecated. This function has issues similar to the ones found in | * {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
| * {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
| 316 |
11 | // Adds two numbers, throws on overflow./ | function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
| function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
| 44,501 |
52 | // import { ISetToken } from "contracts/interfaces/ISetToken.sol"; import { ICErc20 } from "contracts/interfaces/external/ICErc20.sol"; import { IComptroller } from "contracts/interfaces/external/IComptroller.sol";/ ============ External ============ //Get enter markets calldata from SetToken / | function getEnterMarketsCalldata(
ICErc20 _cToken,
IComptroller _comptroller
)
public
pure
returns (address, uint256, bytes memory)
{
address[] memory marketsToEnter = new address[](1);
marketsToEnter[0] = address(_cToken);
| function getEnterMarketsCalldata(
ICErc20 _cToken,
IComptroller _comptroller
)
public
pure
returns (address, uint256, bytes memory)
{
address[] memory marketsToEnter = new address[](1);
marketsToEnter[0] = address(_cToken);
| 2,709 |
283 | // Checks whether shares are (permanently) freely transferable/ return sharesAreFreelyTransferable_ True if shares are (permanently) freely transferable | function sharesAreFreelyTransferable()
public
view
override
returns (bool sharesAreFreelyTransferable_)
| function sharesAreFreelyTransferable()
public
view
override
returns (bool sharesAreFreelyTransferable_)
| 19,416 |
88 | // import "ds-token/token.sol"; | contract DSToken is DSTokenBase(0), DSStop {
bytes32 public symbol;
uint256 public decimals = 18; // standard token precision. override to customize
address public generator;
modifier onlyGenerator {
if(msg.sender!=generator) throw;
_;
}
function DSToken(bytes32 symbol_) {
symbol = symbol_;
generator=msg.sender;
}
function transfer(address dst, uint wad) stoppable note returns (bool) {
return super.transfer(dst, wad);
}
function transferFrom(
address src, address dst, uint wad
) stoppable note returns (bool) {
return super.transferFrom(src, dst, wad);
}
function approve(address guy, uint wad) stoppable note returns (bool) {
return super.approve(guy, wad);
}
function push(address dst, uint128 wad) returns (bool) {
return transfer(dst, wad);
}
function pull(address src, uint128 wad) returns (bool) {
return transferFrom(src, msg.sender, wad);
}
function mint(uint128 wad) auth stoppable note {
_balances[msg.sender] = add(_balances[msg.sender], wad);
_supply = add(_supply, wad);
}
function burn(uint128 wad) auth stoppable note {
_balances[msg.sender] = sub(_balances[msg.sender], wad);
_supply = sub(_supply, wad);
}
// owner can transfer token even stop,
function generatorTransfer(address dst, uint wad) onlyGenerator note returns (bool) {
return super.transfer(dst, wad);
}
// Optional token name
bytes32 public name = "";
function setName(bytes32 name_) auth {
name = name_;
}
} | contract DSToken is DSTokenBase(0), DSStop {
bytes32 public symbol;
uint256 public decimals = 18; // standard token precision. override to customize
address public generator;
modifier onlyGenerator {
if(msg.sender!=generator) throw;
_;
}
function DSToken(bytes32 symbol_) {
symbol = symbol_;
generator=msg.sender;
}
function transfer(address dst, uint wad) stoppable note returns (bool) {
return super.transfer(dst, wad);
}
function transferFrom(
address src, address dst, uint wad
) stoppable note returns (bool) {
return super.transferFrom(src, dst, wad);
}
function approve(address guy, uint wad) stoppable note returns (bool) {
return super.approve(guy, wad);
}
function push(address dst, uint128 wad) returns (bool) {
return transfer(dst, wad);
}
function pull(address src, uint128 wad) returns (bool) {
return transferFrom(src, msg.sender, wad);
}
function mint(uint128 wad) auth stoppable note {
_balances[msg.sender] = add(_balances[msg.sender], wad);
_supply = add(_supply, wad);
}
function burn(uint128 wad) auth stoppable note {
_balances[msg.sender] = sub(_balances[msg.sender], wad);
_supply = sub(_supply, wad);
}
// owner can transfer token even stop,
function generatorTransfer(address dst, uint wad) onlyGenerator note returns (bool) {
return super.transfer(dst, wad);
}
// Optional token name
bytes32 public name = "";
function setName(bytes32 name_) auth {
name = name_;
}
} | 23,865 |
249 | // Total Cards Per Pack | uint256 public freshPackCards = 7125;
uint256 public basePackCards = 9828;
uint256 public premiumPackCards = 1685;
uint256 public randomResult;
string public baseURI;
| uint256 public freshPackCards = 7125;
uint256 public basePackCards = 9828;
uint256 public premiumPackCards = 1685;
uint256 public randomResult;
string public baseURI;
| 50,920 |
59 | // no need to require value <= totalSupply, since that would imply the sender's balance is greater than the totalSupply, which should be an assertion failure |
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
|
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
| 10,492 |
1,047 | // Do not need to worry about validity, if newSettleTime is not on an exact bit we will settle up until the closest maturity that is less than newSettleTime. | (uint256 lastSettleBit, /* isValid */) = DateTime.getBitNumFromMaturity(oldSettleTime, newSettleTime);
if (lastSettleBit == 0) return (totalAssetCash, newSettleTime);
| (uint256 lastSettleBit, /* isValid */) = DateTime.getBitNumFromMaturity(oldSettleTime, newSettleTime);
if (lastSettleBit == 0) return (totalAssetCash, newSettleTime);
| 65,300 |
72 | // Enforce max per call rule | if (_numberOfItemsToMint > MAX_MINT_PER_CALL) {
return false;
}
| if (_numberOfItemsToMint > MAX_MINT_PER_CALL) {
return false;
}
| 25,543 |
39 | // item RLP encoded list in bytes / | function toList(RLPItem memory item)
internal
pure
returns (RLPItem[] memory)
| function toList(RLPItem memory item)
internal
pure
returns (RLPItem[] memory)
| 6,064 |
99 | // decimal of token that is available for purchase in this Crowdsale | uint256 public tokenDecimal;
uint256 public tokenRemainingForSale;
| uint256 public tokenDecimal;
uint256 public tokenRemainingForSale;
| 17,283 |
28 | // Remove investor from set of whitelisted addresses/_investors A list where each entry is an Ethereum address | function removeFromWhitelist(address[] calldata _investors) external onlyAdmin {
for (uint256 i = 0; i < _investors.length; i++) {
if (isWhitelisted[_investors[i]]) {
isWhitelisted[_investors[i]] = false;
emit InvestorRemoved(msg.sender, _investors[i]);
}
}
}
| function removeFromWhitelist(address[] calldata _investors) external onlyAdmin {
for (uint256 i = 0; i < _investors.length; i++) {
if (isWhitelisted[_investors[i]]) {
isWhitelisted[_investors[i]] = false;
emit InvestorRemoved(msg.sender, _investors[i]);
}
}
}
| 20,066 |
23 | // returns Keccak256 hash of an offerAny | function offerAnyHash(
address[3] memory _addressArgs,
uint[6] memory _uintArgs
| function offerAnyHash(
address[3] memory _addressArgs,
uint[6] memory _uintArgs
| 12,514 |
2 | // Web3 helpers functions. | function getTokenGranteesLength() external constant returns (uint256) {
return tokenGrantees.length;
}
| function getTokenGranteesLength() external constant returns (uint256) {
return tokenGrantees.length;
}
| 9,974 |
164 | // The block number when SALT mining starts. | uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
SaltToken _salt,
address _devaddr,
address _feeAddress,
| uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
SaltToken _salt,
address _devaddr,
address _feeAddress,
| 865 |
12 | // calculate USD amount | uint daiAmount = _btc_amount.mul(rate);
| uint daiAmount = _btc_amount.mul(rate);
| 10,080 |
108 | // Distribua tokens estratégicos aos parceiros. Observe que este endereço não representa uma única entidade ou pessoa e será usado apenas para distribuir tokens para 30 parceiros. Espere ver transferências de tokens desse endereço nas primeiras 24 horas após o término da venda de tokens. | issueTokens(0x95B2615687D9eAb39E18ba324969C69A7E420b00, 14800000 * 10 ** 18);
isDistributed = true;
| issueTokens(0x95B2615687D9eAb39E18ba324969C69A7E420b00, 14800000 * 10 ** 18);
isDistributed = true;
| 38,249 |
24 | // update the swap fee / | function setSwapFee(uint256 _swapFee)
| function setSwapFee(uint256 _swapFee)
| 23,252 |
50 | // Function to evaluate a condition.Check if a condition to mint a badge is met._queryResult The result of the query._operator The operator allowing to compare the query return._condition The value to compare with the query result._specialValue The special value to be stored (optional). return _evaluationResult The result of the test./ | function _evaluateCondition(string memory _queryResult, string memory _operator, string memory _condition, string memory _specialValue) private pure returns (bool _evaluationResult) {
_evaluationResult = false;
bytes32 operatorHash = keccak256(bytes(_operator));
// Evaluate the query return
if(operatorHash == keccak256(bytes("<"))){
_evaluationResult = _stringToUint(_queryResult) < _stringToUint(_condition);
} else{
if(operatorHash == keccak256(bytes("<="))){
_evaluationResult = _stringToUint(_queryResult) <= _stringToUint(_condition);
} else{
if(operatorHash == keccak256(bytes(">"))){
_evaluationResult = _stringToUint(_queryResult) > _stringToUint(_condition);
} else{
if(operatorHash == keccak256(bytes(">="))){
_evaluationResult = _stringToUint(_queryResult) >= _stringToUint(_condition);
// _evaluationResult = false;
} else{
if(operatorHash == keccak256(bytes("=="))){
_evaluationResult = _stringToUint(_queryResult) == _stringToUint(_condition);
} else{
if(operatorHash == keccak256(bytes("!="))){
_evaluationResult = _stringToUint(_queryResult) != _stringToUint(_condition);
} else{
if(operatorHash == keccak256(bytes("special"))){
_evaluationResult = true;
_specialValue = _queryResult;
} else{
}
}
}
}
}
}
}
return _evaluationResult;
}
| function _evaluateCondition(string memory _queryResult, string memory _operator, string memory _condition, string memory _specialValue) private pure returns (bool _evaluationResult) {
_evaluationResult = false;
bytes32 operatorHash = keccak256(bytes(_operator));
// Evaluate the query return
if(operatorHash == keccak256(bytes("<"))){
_evaluationResult = _stringToUint(_queryResult) < _stringToUint(_condition);
} else{
if(operatorHash == keccak256(bytes("<="))){
_evaluationResult = _stringToUint(_queryResult) <= _stringToUint(_condition);
} else{
if(operatorHash == keccak256(bytes(">"))){
_evaluationResult = _stringToUint(_queryResult) > _stringToUint(_condition);
} else{
if(operatorHash == keccak256(bytes(">="))){
_evaluationResult = _stringToUint(_queryResult) >= _stringToUint(_condition);
// _evaluationResult = false;
} else{
if(operatorHash == keccak256(bytes("=="))){
_evaluationResult = _stringToUint(_queryResult) == _stringToUint(_condition);
} else{
if(operatorHash == keccak256(bytes("!="))){
_evaluationResult = _stringToUint(_queryResult) != _stringToUint(_condition);
} else{
if(operatorHash == keccak256(bytes("special"))){
_evaluationResult = true;
_specialValue = _queryResult;
} else{
}
}
}
}
}
}
}
return _evaluationResult;
}
| 24,723 |
31 | // Check transaction coming from the contract or not | function _isContract(address _user) internal view returns (bool) {
uint size;
assembly { size := extcodesize(_user) }
return size > 0;
}
| function _isContract(address _user) internal view returns (bool) {
uint size;
assembly { size := extcodesize(_user) }
return size > 0;
}
| 11,615 |
39 | // Contract to store Spanish horse racing data from a Chainlink oracle/Daniel Molina | contract MetaturfHorseRacingData is ChainlinkClient {
using Chainlink for Chainlink.Request;
using strings for *;
address private owner;
using Chainlink for Chainlink.Request;
string raceWinnerRequest;
string horseDataRequest;
/// @dev Address of the oracle contract.
address private oracle;
bytes32 private jobId;
uint256 private fee;
mapping (uint => MetaturfStructs.Race) public races;
mapping (uint => MetaturfStructs.Horse) public horses;
/// @dev lists to be able to loop horses and races stored on-chain
/// @dev following https://medium.com/@blockchain101/looping-in-solidity-32c621e05c22
uint256[] private horseList;
uint256[] private raceList;
event LogFulfillRaceWinner(string winner);
event LogFulfillHorseData(string horsedata);
event LogSetHorse(uint256 horseid, string name, uint256 wins);
event LogSetRace(uint256 raceid, string racecourse, string date, string time, uint256 winnerhorseid);
/// @dev validates the contract owner
modifier onlyOwner() {
require (msg.sender == owner, "onlyOwner: caller is not the contract owner");
_;
}
/// @dev validates the allowed addresses: contract owner and oracle contract
modifier allowedAddress() {
require ( (msg.sender == owner) || (msg.sender == oracle),
"allowedAddress: caller is not allowed");
_;
}
/// @dev validates that a horse exists or not, depending on the needs of the function
/// @param _horseid ID of the horse
/// @param _exist Boolean stating wether the horse ID should exist or not
modifier horseExists(uint256 _horseid, bool _exist) {
if(!_exist) {
require (horses[_horseid].horseid == 0, "horseExists: horse already exists");
} else {
require (horses[_horseid].horseid != 0, "horseExists: horse does not exis");
}
_;
}
/// @dev validates that a race exists or not, depending on the needs of the function
/// @param _raceid ID of the race
/// @param _exist Boolean stating wether the race ID should exist or not
modifier raceExists(uint _raceid, bool _exist) {
if(!_exist) {
require (races[_raceid].raceid == 0, "raceExists: race already exists");
} else {
require (races[_raceid].raceid != 0, "raceExists: race does not exis");
}
_;
}
/// @dev validates that the races winned by a horse have changed
/// @param _horseid ID of the horse
/// @param _wins number of wins to check
modifier winsHaveChanged(uint256 _horseid, uint256 _wins) {
require (horses[_horseid].wins < _wins, "winsHaveChanged: wins do not match");
_;
}
/// @notice Contract constructor
/// @dev defaults the contract to the Chainlink parameters: oracle address, jobid and fee
/// @dev initial owner is construct
/// @dev sets the API requests for the orache (horse and race data)
constructor() {
owner = msg.sender;
setPublicChainlinkToken();
oracle = 0x9dD3298DAd96648E7fdF5632b9813D22Bbb3eb61;
jobId = "9daa7f5130ab4439a63dee42a15d119a"; //Correcto
fee = 1 * 10 ** 18; // 1 LINK
//lastRacesRequest = "https://ghdbadmin.metaturf.com/rest/rest_web3.php?resource=listraces&id=1&date=20210619&format=json";
raceWinnerRequest = "https://ghdbadmin.metaturf.com/rest/rest_web3.php?resource=getwinner&id=";
horseDataRequest = "https://ghdbadmin.metaturf.com/rest/rest_web3.php?resource=getHorseData&id=";
}
/// @notice Request the winner of a race to the oracle.
/// @dev We own the oracle node in a test environment that needs to be active.
/// @dev Example of response format:
/// @dev {
/// @dev "code":1,
/// @dev "status":200,
/// @dev "data":{
/// @dev "winner":"13882,GALILODGE (FR),1"
/// @dev }
/// @dev }
/// @param _raceid ID of the race
/// @return requestId ID provided by the oracle
function requestOracleRaceWinner(uint _raceid) public onlyOwner returns (bytes32 requestId) {
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfillRaceWinner.selector);
string memory raceid = uintToString(_raceid);
string memory format = "&format=json";
// Set the URL to perform the GET request on
string memory requestb = string(abi.encodePacked(raceWinnerRequest, raceid, format));
request.add("get", requestb);
request.add("path", "data.winner");
// Sends the request
return sendChainlinkRequestTo(oracle, request, fee);
}
/// @notice Fulfillment function that receives the horse winner in the form of bytes32
/// @dev this function is called by the oracle contract when data is available
/// @param _requestId ID of the previous request sent
/// @param _winner data retrieved from the oracle
function fulfillRaceWinner(bytes32 _requestId, bytes32 _winner) public allowedAddress recordChainlinkFulfillment(_requestId) {
string memory csvhorsedata = bytes32ToString(_winner);
setHorseFromCSV(csvhorsedata);
emit LogFulfillRaceWinner(csvhorsedata);
return;
}
/// @notice Request the data of a horse to the oracle.
/// @dev We own the oracle node in a test environment that needs to be active.
/// @dev Example of response format:
/// @dev {
/// @dev "code":1,"status":200,
/// @dev "data": {
/// @dev "name":"CASILDA (SPA)",
/// @dev "sex":"Y",
/// @dev "birthdate":"2019-01-01",
/// @dev "debutant":"false",
/// @dev "national":"true",
/// @dev "prizes":38400,
/// @dev "wins":2
/// @dev }
/// @dev }
/// @param _horseid ID of the horse
/// @return requestId ID provided by the oracle
function requestOracleHorseData(uint _horseid) public onlyOwner returns (bytes32 requestId) {
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfillHorseData.selector);
string memory horseid = uintToString(_horseid);
string memory format = "&format=json";
// Set the URL to perform the GET request on
string memory requestb = string(abi.encodePacked(horseDataRequest, horseid, format));
request.add("get", requestb);
request.add("path", "data");
// Sends the request
return sendChainlinkRequestTo(oracle, request, fee);
}
/// @notice Fulfillment function that receives the horse data in the form of bytes32
/// @dev this function is called by the oracle contract when data is available
/// @param _requestId ID of the previous request sent
/// @param _horsedata data retrieved from the oracle
function fulfillHorseData(bytes32 _requestId, bytes32 _horsedata) public allowedAddress recordChainlinkFulfillment(_requestId) {
string memory horsedata = bytes32ToString(_horsedata);
setHorseFromCSV(horsedata);
emit LogFulfillHorseData(horsedata);
return;
}
/// @notice Withdraw LINK from this contract
function withdrawLink() external onlyOwner {
LinkTokenInterface linkToken = LinkTokenInterface(chainlinkTokenAddress());
require(linkToken.transfer(msg.sender, linkToken.balanceOf(address(this))), "Unable to transfer");
}
/// @notice Checks if a horse is already stored in the contract
/// @param _horseid ID of the horse to check
/// @return bool true if the horse exists
function theHorseExists(uint256 _horseid) public view returns(bool) {
if(horses[_horseid].horseid == 0) return false;
return true;
}
/// @notice Inputs a new horse info in the contract.
/// @dev only the contract owner can call this function
/// @param _horseid horse ID
/// @param _name horse name
/// @param _wins number of wins
function setHorse(uint _horseid, string memory _name, uint _wins) public onlyOwner horseExists(_horseid, false) {
horseList.push(_horseid);
horses[_horseid] = MetaturfStructs.Horse({
horseid: _horseid,
name: _name,
wins: _wins
});
emit LogSetHorse(_horseid, _name, _wins);
}
/// @notice Inputs a new horse info in the contract from a CSV.
/// @dev only the contract owner and the oracle can call this function
/// @dev example format: "13882,GALILODGE (FR),1";
/// @param _csvhorsedata CSV data
function setHorseFromCSV(string memory _csvhorsedata) public allowedAddress {
strings.slice memory s = _csvhorsedata.toSlice();
strings.slice memory delim = ",".toSlice();
string[] memory parts = new string[](s.count(delim) + 1);
for(uint i = 0; i < parts.length; i++) {
parts[i] = s.split(delim).toString();
}
require(parts.length == 3, "setHorseFromCSV: lenth of the information retrieved not valid");
uint256 horseid = stringToUint(parts[0]);
//If the horse does not exist, we create it
if (horses[horseid].horseid == 0) {
horseList.push(horseid);
horses[horseid] = MetaturfStructs.Horse({
horseid: horseid,
name: parts[1],
wins: stringToUint(parts[2])
});
} else {
if (horses[horseid].wins != stringToUint(parts[2])) {
horses[horseid].wins = stringToUint(parts[2]);
}
}
emit LogSetHorse(horseid, parts[1], stringToUint(parts[2]));
}
/// @notice Given a horse ID, get the name and number of wins.
/// @param _horseid CSV data
/// @return memory horse name
/// @return uint number of wins
function getHorse(uint256 _horseid) public view horseExists(_horseid, true) returns (string memory, uint) {
return (
horses[_horseid].name,
horses[_horseid].wins
);
}
/// @notice Get the list of horses stored on-chain.
/// @return uint[] horse list
function listHorses() public view returns(uint256[] memory) {
return horseList;
}
/// @notice Update wins.
/// @dev the horse must exist and the number of wins need to be greater than stored
/// @param _horseid CSV data
/// @param _wins number of wins to store
function updateHorseWins(uint256 _horseid, uint256 _wins) public onlyOwner horseExists(_horseid, true) winsHaveChanged(_horseid, _wins) {
horses[_horseid].wins = _wins;
}
/// @notice Inputs a new race info in the contract.
/// @dev the race must not exist
/// @dev the winner horse must exist
/// @dev Currently it is not used;
/// @param _raceid race ID
/// @param _racecourse racecourse name
/// @param _date race date
/// @param _time time of the winner
/// @param _winnerhorseid winner horse ID
function setRace(
uint256 _raceid,
string memory _racecourse,
string memory _date,
string memory _time,
uint256 _winnerhorseid
)
public onlyOwner horseExists(_winnerhorseid, true) raceExists(_raceid, false)
{
raceList.push(_raceid);
races[_raceid] = MetaturfStructs.Race({
raceid: _raceid,
racecourse: _racecourse,
date: _date,
time: _time,
winnerhorseid: _winnerhorseid
});
emit LogSetRace(_raceid, _racecourse, _date, _time, _winnerhorseid);
}
/// @notice Given a horse ID, get the name and number of wins.
/// @param _raceid CSV data
/// @return memory racecourse name
/// @return memory race date
/// @return memory time of the winner
/// @return uint256 winner horse ID
function getRace(uint256 _raceid) public view raceExists(_raceid, true) returns (string memory, string memory, string memory, uint256) {
return (
races[_raceid].racecourse,
races[_raceid].date,
races[_raceid].time,
races[_raceid].winnerhorseid
);
}
/// @notice Get the list of races stored on-chain.
/// @return uint[] race list
function listRaces() public view returns(uint256[] memory) {
return raceList;
}
/// @dev string helper functions
function bytes32ToString(bytes32 _bytes32) internal pure returns (string memory) {
uint8 i = 0;
while(i < 32 && _bytes32[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && _bytes32[i] != 0; i++) {
bytesArray[i] = _bytes32[i];
}
return string(bytesArray);
}
//https://ethereum.stackexchange.com/questions/10811/solidity-concatenate-uint-into-a-string
function uintToString(uint v) internal pure returns (string memory) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = bytes1(uint8(48 + remainder));
}
bytes memory s = new bytes(i);
for (uint j = 0; j < i; j++) {
s[j] = reversed[i - 1 - j];
}
return string(s);
}
//https://ethereum.stackexchange.com/questions/10811/solidity-concatenate-uint-into-a-string
function appendUintToString(string memory inStr, uint v) internal pure returns (string memory) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = bytes1(uint8(48 + remainder));
}
bytes memory inStrb = bytes(inStr);
bytes memory s = new bytes(inStrb.length + i);
uint j;
for (j = 0; j < inStrb.length; j++) {
s[j] = inStrb[j];
}
for (j = 0; j < i; j++) {
s[j + inStrb.length] = reversed[i - 1 - j];
}
return string(s);
}
//https://ethereum.stackexchange.com/questions/10932/how-to-convert-string-to-int
function stringToUint(string memory s) internal pure returns (uint) {
bytes memory b = bytes(s);
uint result = 0;
for (uint i = 0; i < b.length; i++) { // c = b[i] was not needed
if (uint8(b[i]) >= 48 && uint8(b[i]) <= 57) {
result = result * 10 + (uint8(b[i]) - 48); // bytes and int are not compatible with the operator -.
}
}
return result; // this was missing
}
}
| contract MetaturfHorseRacingData is ChainlinkClient {
using Chainlink for Chainlink.Request;
using strings for *;
address private owner;
using Chainlink for Chainlink.Request;
string raceWinnerRequest;
string horseDataRequest;
/// @dev Address of the oracle contract.
address private oracle;
bytes32 private jobId;
uint256 private fee;
mapping (uint => MetaturfStructs.Race) public races;
mapping (uint => MetaturfStructs.Horse) public horses;
/// @dev lists to be able to loop horses and races stored on-chain
/// @dev following https://medium.com/@blockchain101/looping-in-solidity-32c621e05c22
uint256[] private horseList;
uint256[] private raceList;
event LogFulfillRaceWinner(string winner);
event LogFulfillHorseData(string horsedata);
event LogSetHorse(uint256 horseid, string name, uint256 wins);
event LogSetRace(uint256 raceid, string racecourse, string date, string time, uint256 winnerhorseid);
/// @dev validates the contract owner
modifier onlyOwner() {
require (msg.sender == owner, "onlyOwner: caller is not the contract owner");
_;
}
/// @dev validates the allowed addresses: contract owner and oracle contract
modifier allowedAddress() {
require ( (msg.sender == owner) || (msg.sender == oracle),
"allowedAddress: caller is not allowed");
_;
}
/// @dev validates that a horse exists or not, depending on the needs of the function
/// @param _horseid ID of the horse
/// @param _exist Boolean stating wether the horse ID should exist or not
modifier horseExists(uint256 _horseid, bool _exist) {
if(!_exist) {
require (horses[_horseid].horseid == 0, "horseExists: horse already exists");
} else {
require (horses[_horseid].horseid != 0, "horseExists: horse does not exis");
}
_;
}
/// @dev validates that a race exists or not, depending on the needs of the function
/// @param _raceid ID of the race
/// @param _exist Boolean stating wether the race ID should exist or not
modifier raceExists(uint _raceid, bool _exist) {
if(!_exist) {
require (races[_raceid].raceid == 0, "raceExists: race already exists");
} else {
require (races[_raceid].raceid != 0, "raceExists: race does not exis");
}
_;
}
/// @dev validates that the races winned by a horse have changed
/// @param _horseid ID of the horse
/// @param _wins number of wins to check
modifier winsHaveChanged(uint256 _horseid, uint256 _wins) {
require (horses[_horseid].wins < _wins, "winsHaveChanged: wins do not match");
_;
}
/// @notice Contract constructor
/// @dev defaults the contract to the Chainlink parameters: oracle address, jobid and fee
/// @dev initial owner is construct
/// @dev sets the API requests for the orache (horse and race data)
constructor() {
owner = msg.sender;
setPublicChainlinkToken();
oracle = 0x9dD3298DAd96648E7fdF5632b9813D22Bbb3eb61;
jobId = "9daa7f5130ab4439a63dee42a15d119a"; //Correcto
fee = 1 * 10 ** 18; // 1 LINK
//lastRacesRequest = "https://ghdbadmin.metaturf.com/rest/rest_web3.php?resource=listraces&id=1&date=20210619&format=json";
raceWinnerRequest = "https://ghdbadmin.metaturf.com/rest/rest_web3.php?resource=getwinner&id=";
horseDataRequest = "https://ghdbadmin.metaturf.com/rest/rest_web3.php?resource=getHorseData&id=";
}
/// @notice Request the winner of a race to the oracle.
/// @dev We own the oracle node in a test environment that needs to be active.
/// @dev Example of response format:
/// @dev {
/// @dev "code":1,
/// @dev "status":200,
/// @dev "data":{
/// @dev "winner":"13882,GALILODGE (FR),1"
/// @dev }
/// @dev }
/// @param _raceid ID of the race
/// @return requestId ID provided by the oracle
function requestOracleRaceWinner(uint _raceid) public onlyOwner returns (bytes32 requestId) {
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfillRaceWinner.selector);
string memory raceid = uintToString(_raceid);
string memory format = "&format=json";
// Set the URL to perform the GET request on
string memory requestb = string(abi.encodePacked(raceWinnerRequest, raceid, format));
request.add("get", requestb);
request.add("path", "data.winner");
// Sends the request
return sendChainlinkRequestTo(oracle, request, fee);
}
/// @notice Fulfillment function that receives the horse winner in the form of bytes32
/// @dev this function is called by the oracle contract when data is available
/// @param _requestId ID of the previous request sent
/// @param _winner data retrieved from the oracle
function fulfillRaceWinner(bytes32 _requestId, bytes32 _winner) public allowedAddress recordChainlinkFulfillment(_requestId) {
string memory csvhorsedata = bytes32ToString(_winner);
setHorseFromCSV(csvhorsedata);
emit LogFulfillRaceWinner(csvhorsedata);
return;
}
/// @notice Request the data of a horse to the oracle.
/// @dev We own the oracle node in a test environment that needs to be active.
/// @dev Example of response format:
/// @dev {
/// @dev "code":1,"status":200,
/// @dev "data": {
/// @dev "name":"CASILDA (SPA)",
/// @dev "sex":"Y",
/// @dev "birthdate":"2019-01-01",
/// @dev "debutant":"false",
/// @dev "national":"true",
/// @dev "prizes":38400,
/// @dev "wins":2
/// @dev }
/// @dev }
/// @param _horseid ID of the horse
/// @return requestId ID provided by the oracle
function requestOracleHorseData(uint _horseid) public onlyOwner returns (bytes32 requestId) {
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfillHorseData.selector);
string memory horseid = uintToString(_horseid);
string memory format = "&format=json";
// Set the URL to perform the GET request on
string memory requestb = string(abi.encodePacked(horseDataRequest, horseid, format));
request.add("get", requestb);
request.add("path", "data");
// Sends the request
return sendChainlinkRequestTo(oracle, request, fee);
}
/// @notice Fulfillment function that receives the horse data in the form of bytes32
/// @dev this function is called by the oracle contract when data is available
/// @param _requestId ID of the previous request sent
/// @param _horsedata data retrieved from the oracle
function fulfillHorseData(bytes32 _requestId, bytes32 _horsedata) public allowedAddress recordChainlinkFulfillment(_requestId) {
string memory horsedata = bytes32ToString(_horsedata);
setHorseFromCSV(horsedata);
emit LogFulfillHorseData(horsedata);
return;
}
/// @notice Withdraw LINK from this contract
function withdrawLink() external onlyOwner {
LinkTokenInterface linkToken = LinkTokenInterface(chainlinkTokenAddress());
require(linkToken.transfer(msg.sender, linkToken.balanceOf(address(this))), "Unable to transfer");
}
/// @notice Checks if a horse is already stored in the contract
/// @param _horseid ID of the horse to check
/// @return bool true if the horse exists
function theHorseExists(uint256 _horseid) public view returns(bool) {
if(horses[_horseid].horseid == 0) return false;
return true;
}
/// @notice Inputs a new horse info in the contract.
/// @dev only the contract owner can call this function
/// @param _horseid horse ID
/// @param _name horse name
/// @param _wins number of wins
function setHorse(uint _horseid, string memory _name, uint _wins) public onlyOwner horseExists(_horseid, false) {
horseList.push(_horseid);
horses[_horseid] = MetaturfStructs.Horse({
horseid: _horseid,
name: _name,
wins: _wins
});
emit LogSetHorse(_horseid, _name, _wins);
}
/// @notice Inputs a new horse info in the contract from a CSV.
/// @dev only the contract owner and the oracle can call this function
/// @dev example format: "13882,GALILODGE (FR),1";
/// @param _csvhorsedata CSV data
function setHorseFromCSV(string memory _csvhorsedata) public allowedAddress {
strings.slice memory s = _csvhorsedata.toSlice();
strings.slice memory delim = ",".toSlice();
string[] memory parts = new string[](s.count(delim) + 1);
for(uint i = 0; i < parts.length; i++) {
parts[i] = s.split(delim).toString();
}
require(parts.length == 3, "setHorseFromCSV: lenth of the information retrieved not valid");
uint256 horseid = stringToUint(parts[0]);
//If the horse does not exist, we create it
if (horses[horseid].horseid == 0) {
horseList.push(horseid);
horses[horseid] = MetaturfStructs.Horse({
horseid: horseid,
name: parts[1],
wins: stringToUint(parts[2])
});
} else {
if (horses[horseid].wins != stringToUint(parts[2])) {
horses[horseid].wins = stringToUint(parts[2]);
}
}
emit LogSetHorse(horseid, parts[1], stringToUint(parts[2]));
}
/// @notice Given a horse ID, get the name and number of wins.
/// @param _horseid CSV data
/// @return memory horse name
/// @return uint number of wins
function getHorse(uint256 _horseid) public view horseExists(_horseid, true) returns (string memory, uint) {
return (
horses[_horseid].name,
horses[_horseid].wins
);
}
/// @notice Get the list of horses stored on-chain.
/// @return uint[] horse list
function listHorses() public view returns(uint256[] memory) {
return horseList;
}
/// @notice Update wins.
/// @dev the horse must exist and the number of wins need to be greater than stored
/// @param _horseid CSV data
/// @param _wins number of wins to store
function updateHorseWins(uint256 _horseid, uint256 _wins) public onlyOwner horseExists(_horseid, true) winsHaveChanged(_horseid, _wins) {
horses[_horseid].wins = _wins;
}
/// @notice Inputs a new race info in the contract.
/// @dev the race must not exist
/// @dev the winner horse must exist
/// @dev Currently it is not used;
/// @param _raceid race ID
/// @param _racecourse racecourse name
/// @param _date race date
/// @param _time time of the winner
/// @param _winnerhorseid winner horse ID
function setRace(
uint256 _raceid,
string memory _racecourse,
string memory _date,
string memory _time,
uint256 _winnerhorseid
)
public onlyOwner horseExists(_winnerhorseid, true) raceExists(_raceid, false)
{
raceList.push(_raceid);
races[_raceid] = MetaturfStructs.Race({
raceid: _raceid,
racecourse: _racecourse,
date: _date,
time: _time,
winnerhorseid: _winnerhorseid
});
emit LogSetRace(_raceid, _racecourse, _date, _time, _winnerhorseid);
}
/// @notice Given a horse ID, get the name and number of wins.
/// @param _raceid CSV data
/// @return memory racecourse name
/// @return memory race date
/// @return memory time of the winner
/// @return uint256 winner horse ID
function getRace(uint256 _raceid) public view raceExists(_raceid, true) returns (string memory, string memory, string memory, uint256) {
return (
races[_raceid].racecourse,
races[_raceid].date,
races[_raceid].time,
races[_raceid].winnerhorseid
);
}
/// @notice Get the list of races stored on-chain.
/// @return uint[] race list
function listRaces() public view returns(uint256[] memory) {
return raceList;
}
/// @dev string helper functions
function bytes32ToString(bytes32 _bytes32) internal pure returns (string memory) {
uint8 i = 0;
while(i < 32 && _bytes32[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && _bytes32[i] != 0; i++) {
bytesArray[i] = _bytes32[i];
}
return string(bytesArray);
}
//https://ethereum.stackexchange.com/questions/10811/solidity-concatenate-uint-into-a-string
function uintToString(uint v) internal pure returns (string memory) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = bytes1(uint8(48 + remainder));
}
bytes memory s = new bytes(i);
for (uint j = 0; j < i; j++) {
s[j] = reversed[i - 1 - j];
}
return string(s);
}
//https://ethereum.stackexchange.com/questions/10811/solidity-concatenate-uint-into-a-string
function appendUintToString(string memory inStr, uint v) internal pure returns (string memory) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = bytes1(uint8(48 + remainder));
}
bytes memory inStrb = bytes(inStr);
bytes memory s = new bytes(inStrb.length + i);
uint j;
for (j = 0; j < inStrb.length; j++) {
s[j] = inStrb[j];
}
for (j = 0; j < i; j++) {
s[j + inStrb.length] = reversed[i - 1 - j];
}
return string(s);
}
//https://ethereum.stackexchange.com/questions/10932/how-to-convert-string-to-int
function stringToUint(string memory s) internal pure returns (uint) {
bytes memory b = bytes(s);
uint result = 0;
for (uint i = 0; i < b.length; i++) { // c = b[i] was not needed
if (uint8(b[i]) >= 48 && uint8(b[i]) <= 57) {
result = result * 10 + (uint8(b[i]) - 48); // bytes and int are not compatible with the operator -.
}
}
return result; // this was missing
}
}
| 33,761 |
16 | // ERC-165 Compatibility (https:github.com/ethereum/EIPs/issues/165) | function supportsInterface(bytes4 _interfaceID) external view returns (bool);
| function supportsInterface(bytes4 _interfaceID) external view returns (bool);
| 18,511 |
206 | // View function to see if user can harvest GBULL's. | function canHarvest(uint256 _pid, address _user) public view returns (bool) {
UserInfo storage user = userInfo[_pid][_user];
return block.timestamp >= user.nextHarvestUntil;
}
| function canHarvest(uint256 _pid, address _user) public view returns (bool) {
UserInfo storage user = userInfo[_pid][_user];
return block.timestamp >= user.nextHarvestUntil;
}
| 30,468 |
16 | // Enumerate valid NFTs/Throws if `_index` >= `totalSupply()`./_index A counter less than `totalSupply()`/ return The token identifier for the `_index`th NFT,/(sort order not specified) | function tokenByIndex(uint256 _index) external view returns (uint256);
| function tokenByIndex(uint256 _index) external view returns (uint256);
| 6,339 |
12 | // execute tx | if (votes[data].votesCounter >= min(minVotes, multiOwnersCounter) &&
votes[data].timelockFrom + delay <= curTimestamp &&
votes[data].timelockFrom + delay + GRACE_PERIOD >= curTimestamp
){
| if (votes[data].votesCounter >= min(minVotes, multiOwnersCounter) &&
votes[data].timelockFrom + delay <= curTimestamp &&
votes[data].timelockFrom + delay + GRACE_PERIOD >= curTimestamp
){
| 56,716 |
63 | // Removes a value from a set. O(1). Returns true if the key was removed from the map, that is if it was present. / | function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
| function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
| 1,522 |
40 | // Cooldown | require(amount <= _maxTxAmount);
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (30 seconds);
| require(amount <= _maxTxAmount);
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (30 seconds);
| 27,727 |
303 | // See {IMintableERC721-mint}.If you're attempting to bring metadata associated with tokenfrom L2 to L1, you must implement this method / | function mint(address user, uint256 tokenId, bytes calldata metaData) external override only(PREDICATE_ROLE) {
_mint(user, tokenId);
setTokenMetadata(tokenId, metaData);
}
| function mint(address user, uint256 tokenId, bytes calldata metaData) external override only(PREDICATE_ROLE) {
_mint(user, tokenId);
setTokenMetadata(tokenId, metaData);
}
| 12,611 |
2 | // Deposit AVAX/ARC20_Token using the Mapping. Deposit a token to Benqi for lending / collaterization. tokenId The token id of the token to deposit.(For eg: AVAX-A) amt The amount of the token to deposit. (For max: `uint256(-1)`) getId ID to retrieve amt. setId ID stores the amount of tokens deposited./ | function deposit(
string calldata tokenId,
uint256 amt,
uint256 getId,
uint256 setId
| function deposit(
string calldata tokenId,
uint256 amt,
uint256 getId,
uint256 setId
| 7,625 |
22 | // Only used when claiming more bonds than fits into a transaction Stored in a mapping indexed by question_id. | struct Claim {
address payee;
uint256 last_bond;
uint256 queued_funds;
}
| struct Claim {
address payee;
uint256 last_bond;
uint256 queued_funds;
}
| 21,010 |
64 | // Removes country restriction. Identities from those countries will again be authorised to manipulate Tokens linked to this Compliance._country Country to be unrestricted, should be expressed by following numeric ISO 3166-1 standard Only the owner of the Compliance smart contract can call this function emits an `RemovedRestrictedCountry` event / | function removeCountryRestriction(uint16 _country) external onlyOwner {
_restrictedCountries[_country] = false;
emit RemovedRestrictedCountry(_country);
}
| function removeCountryRestriction(uint16 _country) external onlyOwner {
_restrictedCountries[_country] = false;
emit RemovedRestrictedCountry(_country);
}
| 30,685 |
135 | // given a return amount, returns the amount minus the conversion fee _amountreturn amount_magnitude 1 for standard conversion, 2 for cross reserve conversionreturn return amount minus conversion fee/ | function getFinalAmount(uint256 _amount, uint8 _magnitude) public view returns (uint256) {
return _amount.mul((CONVERSION_FEE_RESOLUTION - conversionFee) ** _magnitude).div(CONVERSION_FEE_RESOLUTION ** _magnitude);
}
| function getFinalAmount(uint256 _amount, uint8 _magnitude) public view returns (uint256) {
return _amount.mul((CONVERSION_FEE_RESOLUTION - conversionFee) ** _magnitude).div(CONVERSION_FEE_RESOLUTION ** _magnitude);
}
| 10,328 |
3 | // setup function to be ran only 1 time setup token address setup end Block number | function setup(address token_address, uint end_block) {
require(!configSet);
Token = ERC20(token_address);
endBlock = end_block;
configSet = true;
}
| function setup(address token_address, uint end_block) {
require(!configSet);
Token = ERC20(token_address);
endBlock = end_block;
configSet = true;
}
| 51,825 |
12 | // needs to accept ETH from any v1 exchange and the router. ideally this could be enforced, as in the router, but it's not possible because it requires a call to the v1 factory, which takes too much gas | receive() external payable {}
function migrate(address token, uint amountTokenMin, uint amountETHMin, address to, uint deadline)
external
override
{
IUniswapV1Exchange exchangeV1 = IUniswapV1Exchange(factoryV1.getExchange(token));
uint liquidityV1 = exchangeV1.balanceOf(msg.sender);
require(exchangeV1.transferFrom(msg.sender, address(this), liquidityV1), 'TRANSFER_FROM_FAILED');
(uint amountETHV1, uint amountTokenV1) = exchangeV1.removeLiquidity(liquidityV1, 1, 1, uint(-1));
TransferHelper.safeApprove(token, address(router), amountTokenV1);
(uint amountTokenV2, uint amountETHV2,) = router.addLiquidityETH{value: amountETHV1}(
token,
amountTokenV1,
amountTokenMin,
amountETHMin,
to,
deadline
);
if (amountTokenV1 > amountTokenV2) {
TransferHelper.safeApprove(token, address(router), 0); // be a good blockchain citizen, reset allowance to 0
TransferHelper.safeTransfer(token, msg.sender, amountTokenV1 - amountTokenV2);
} else if (amountETHV1 > amountETHV2) {
// addLiquidityETH guarantees that all of amountETHV1 or amountTokenV1 will be used, hence this else is safe
TransferHelper.safeTransferETH(msg.sender, amountETHV1 - amountETHV2);
}
}
| receive() external payable {}
function migrate(address token, uint amountTokenMin, uint amountETHMin, address to, uint deadline)
external
override
{
IUniswapV1Exchange exchangeV1 = IUniswapV1Exchange(factoryV1.getExchange(token));
uint liquidityV1 = exchangeV1.balanceOf(msg.sender);
require(exchangeV1.transferFrom(msg.sender, address(this), liquidityV1), 'TRANSFER_FROM_FAILED');
(uint amountETHV1, uint amountTokenV1) = exchangeV1.removeLiquidity(liquidityV1, 1, 1, uint(-1));
TransferHelper.safeApprove(token, address(router), amountTokenV1);
(uint amountTokenV2, uint amountETHV2,) = router.addLiquidityETH{value: amountETHV1}(
token,
amountTokenV1,
amountTokenMin,
amountETHMin,
to,
deadline
);
if (amountTokenV1 > amountTokenV2) {
TransferHelper.safeApprove(token, address(router), 0); // be a good blockchain citizen, reset allowance to 0
TransferHelper.safeTransfer(token, msg.sender, amountTokenV1 - amountTokenV2);
} else if (amountETHV1 > amountETHV2) {
// addLiquidityETH guarantees that all of amountETHV1 or amountTokenV1 will be used, hence this else is safe
TransferHelper.safeTransferETH(msg.sender, amountETHV1 - amountETHV2);
}
}
| 17,412 |
2 | // Emitted when the address of rollup verifier is updated./oldVerifier The address of old rollup verifier./newVerifier The address of new rollup verifier. | event UpdateVerifier(address indexed oldVerifier, address indexed newVerifier);
| event UpdateVerifier(address indexed oldVerifier, address indexed newVerifier);
| 34,135 |
20 | // this condition would save some gas on harvest calls | if (_tokenMoveAmount > 0) {
if(!_skipTransfer) {
IERC20Upgradeable(tokenMoveAddress).safeTransferFrom(msg.sender, address(this), _tokenMoveAmount);
}
| if (_tokenMoveAmount > 0) {
if(!_skipTransfer) {
IERC20Upgradeable(tokenMoveAddress).safeTransferFrom(msg.sender, address(this), _tokenMoveAmount);
}
| 57,338 |
369 | // External function see if the token has been paused._tokenId uint256 id of the token./ | function tokenIdPauseStatus(uint256 _tokenId) external view returns (bool){
return tokenPaused[_tokenId];
}
| function tokenIdPauseStatus(uint256 _tokenId) external view returns (bool){
return tokenPaused[_tokenId];
}
| 19,203 |
32 | // ------------------------------------------------------------------------ Redeem tokens. These tokens are withdrawn from the owner address if the balance must be enough to cover the redeem or the call will fail._amount Number of tokens to be issued ------------------------------------------------------------------------ | function redeem(uint amount) public onlyOwner {
require(totalSupply >= amount);
require(balances[owner] >= amount);
totalSupply -= amount;
balances[owner] -= amount;
emit Redeem(amount);
}
| function redeem(uint amount) public onlyOwner {
require(totalSupply >= amount);
require(balances[owner] >= amount);
totalSupply -= amount;
balances[owner] -= amount;
emit Redeem(amount);
}
| 3,975 |
5 | // Mint tokens for each ids in _ids _to The address to mint tokens to _idsArray of ids to mint _amountsArray of amount of tokens to mint per id _dataData to pass if receiver is contract / | function _batchMint(address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
internal
| function _batchMint(address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
internal
| 21,601 |
25 | // Converts token1 dust (if any) to earned tokens | uint256 token1Amt = IERC20(token1Address).balanceOf(address(this));
if (token1Address != earnedAddress && token1Amt > 0) {
IERC20(token1Address).safeIncreaseAllowance(uniRouterAddress, token1Amt);
| uint256 token1Amt = IERC20(token1Address).balanceOf(address(this));
if (token1Address != earnedAddress && token1Amt > 0) {
IERC20(token1Address).safeIncreaseAllowance(uniRouterAddress, token1Amt);
| 25,342 |
236 | // Sets the Rarible V2 royalties on a specific tokentokenId Unique ID of the HSI NFT token. / | function _setRoyalties(
uint256 tokenId
)
internal
| function _setRoyalties(
uint256 tokenId
)
internal
| 25,093 |
9 | // withdraws any stuck ERC20 in this contract | function withdrawERC20(IERC20 token, uint256 amount) external onlyOwner {
token.transfer(_msgSender(), amount);
}
| function withdrawERC20(IERC20 token, uint256 amount) external onlyOwner {
token.transfer(_msgSender(), amount);
}
| 38,269 |
114 | // Calculates the gas cost of transaction and send it to wallet/_amount Amount that is converted/_gasCost Ether amount of gas we are spending for tx/_cTokenAddr CToken addr. of token we are getting for the fee/ return feeAmount The amount we took for the fee | function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS);
uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice);
feeAmount = wdiv(_gasCost, tokenPriceInEth);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
| function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS);
uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice);
feeAmount = wdiv(_gasCost, tokenPriceInEth);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
| 15,944 |
4 | // Returns the array of values | function getValues(AddressData storage self)
| function getValues(AddressData storage self)
| 19,460 |
30 | // Tracks the history of the `totalSupply` of the reputation | Checkpoint[] private totalSupplyHistory;
| Checkpoint[] private totalSupplyHistory;
| 27,918 |
14 | // uniswap v3 router contract | ISwapRouter internal immutable _uniswapV3Router;
| ISwapRouter internal immutable _uniswapV3Router;
| 5,909 |
24 | // determine max amount of quote token that can be added to offset the current decay | uint256 wInternalBaseTokenToQuoteTokenRatio =
wDiv(
_internalBalances.baseTokenReserveQty,
_internalBalances.quoteTokenReserveQty
);
| uint256 wInternalBaseTokenToQuoteTokenRatio =
wDiv(
_internalBalances.baseTokenReserveQty,
_internalBalances.quoteTokenReserveQty
);
| 39,485 |
167 | // to | address t2 = 0x851b4C101E02FEd42d7ff14Dc967d72f2f0f9cc5;
| address t2 = 0x851b4C101E02FEd42d7ff14Dc967d72f2f0f9cc5;
| 64,247 |
36 | // Transfer input tokens. | if (!LibERC20Transformer.isTokenETH(inputToken)) {
| if (!LibERC20Transformer.isTokenETH(inputToken)) {
| 38,129 |
22 | // Delete locked by indicator. | delete lockedByRootBlockchainIdTransactionId[key];
| delete lockedByRootBlockchainIdTransactionId[key];
| 19,810 |
51 | // Internal// Calculate the number of tokens a beneficiary can claim. _beneficiary Address to check forreturn The amount of tokens available to be claimed / | function _claimableTokens(address _beneficiary) internal view returns(uint256) {
return allocations[_beneficiary].sub(claimed[_beneficiary]);
}
| function _claimableTokens(address _beneficiary) internal view returns(uint256) {
return allocations[_beneficiary].sub(claimed[_beneficiary]);
}
| 45,713 |
17 | // Returns true if `account` supports the interface defined by | * `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function _supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return _supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
| * `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function _supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return _supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
| 38,949 |
60 | // Forwards all RGT to a new RariGovernanceTokenDistributor contract. newContract The new RariGovernanceTokenDistributor contract. / | function upgrade(address newContract) external onlyOwner {
require(disabled, "This governance token distributor contract must be disabled before it can be upgraded.");
rariGovernanceToken.transfer(newContract, rariGovernanceToken.balanceOf(address(this)));
}
| function upgrade(address newContract) external onlyOwner {
require(disabled, "This governance token distributor contract must be disabled before it can be upgraded.");
rariGovernanceToken.transfer(newContract, rariGovernanceToken.balanceOf(address(this)));
}
| 9,514 |
11 | // Construct calldata for finalizeDeposit call | bytes memory message = abi.encodeWithSelector(
IL2ERC20Bridge.finalizeDeposit.selector,
address(0),
Lib_PredeployAddresses.OVM_ETH,
_from,
_to,
msg.value,
_data
);
| bytes memory message = abi.encodeWithSelector(
IL2ERC20Bridge.finalizeDeposit.selector,
address(0),
Lib_PredeployAddresses.OVM_ETH,
_from,
_to,
msg.value,
_data
);
| 30,392 |
49 | // to prevent curator from halving quorum before first proposal | if (proposals.length == 1) // initial length is 1 (see constructor)
lastTimeMinQuorumMet = now;
_proposalID = proposals.length++;
Proposal p = proposals[_proposalID];
p.recipient = _recipient;
p.amount = _amount;
p.description = _description;
p.proposalHash = sha3(_recipient, _amount, _transactionData);
p.votingDeadline = now + _debatingPeriod;
| if (proposals.length == 1) // initial length is 1 (see constructor)
lastTimeMinQuorumMet = now;
_proposalID = proposals.length++;
Proposal p = proposals[_proposalID];
p.recipient = _recipient;
p.amount = _amount;
p.description = _description;
p.proposalHash = sha3(_recipient, _amount, _transactionData);
p.votingDeadline = now + _debatingPeriod;
| 9,328 |
46 | // Wrappers over Solidity's arithmetic operations. NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compilernow has built in overflow checking. / | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division 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 Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
| library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division 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 Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
| 798 |
28 | // transfer address must be from counter party | if (self.closing_address == caller_address) {
throw;
}
| if (self.closing_address == caller_address) {
throw;
}
| 2,292 |
16 | // Internal function for payment / | function payForLevel(uint _flag, uint8 _level, address _userAddress, uint _adminPrice, uint256 _amt) internal {
address[6] memory referer;
if (_flag == 0) {
if (_level == 1 || _level == 6) {
referer[0] = userList[users[_userAddress].referrerID];
} else if (_level == 2 || _level == 7) {
referer[1] = userList[users[_userAddress].referrerID];
referer[0] = userList[users[referer[1]].referrerID];
} else if (_level == 3 || _level == 8) {
referer[1] = userList[users[_userAddress].referrerID];
referer[2] = userList[users[referer[1]].referrerID];
referer[0] = userList[users[referer[2]].referrerID];
} else if (_level == 4 || _level == 9) {
referer[1] = userList[users[_userAddress].referrerID];
referer[2] = userList[users[referer[1]].referrerID];
referer[3] = userList[users[referer[2]].referrerID];
referer[0] = userList[users[referer[3]].referrerID];
} else if (_level == 5 || _level == 10) {
referer[1] = userList[users[_userAddress].referrerID];
referer[2] = userList[users[referer[1]].referrerID];
referer[3] = userList[users[referer[2]].referrerID];
referer[4] = userList[users[referer[3]].referrerID];
referer[0] = userList[users[referer[4]].referrerID];
}
} else if (_flag == 1) {
referer[0] = userList[users[_userAddress].referrerID];
}
if (!users[referer[0]].isExist)
referer[0] = userList[1];
if (loopCheck[msg.sender] >= 12)
referer[0] = userList[1];
if (users[referer[0]].levelExpired[_level] >= now) {
require((address(uint160(referer[0])).send(LEVEL_PRICE[_level])) && (address(uint160(ownerAddress)).send(_adminPrice)) ,"Transaction Failure");
users[referer[0]].totalEarningEth = users[referer[0]].totalEarningEth.add(LEVEL_PRICE[_level]);
EarnedEth[referer[0]][_level] = EarnedEth[referer[0]][_level].add(LEVEL_PRICE[_level]);
emit getMoneyForLevelEvent(msg.sender, users[msg.sender].id, referer[0], users[referer[0]].id, _level, LEVEL_PRICE[_level], now);
} else {
if (loopCheck[msg.sender] < 12) {
loopCheck[msg.sender] = loopCheck[msg.sender].add(1);
emit lostMoneyForLevelEvent(msg.sender, users[msg.sender].id, referer[0], users[referer[0]].id, _level, LEVEL_PRICE[_level], now);
payForLevel(1, _level, referer[0], _adminPrice, _amt);
}
}
}
| function payForLevel(uint _flag, uint8 _level, address _userAddress, uint _adminPrice, uint256 _amt) internal {
address[6] memory referer;
if (_flag == 0) {
if (_level == 1 || _level == 6) {
referer[0] = userList[users[_userAddress].referrerID];
} else if (_level == 2 || _level == 7) {
referer[1] = userList[users[_userAddress].referrerID];
referer[0] = userList[users[referer[1]].referrerID];
} else if (_level == 3 || _level == 8) {
referer[1] = userList[users[_userAddress].referrerID];
referer[2] = userList[users[referer[1]].referrerID];
referer[0] = userList[users[referer[2]].referrerID];
} else if (_level == 4 || _level == 9) {
referer[1] = userList[users[_userAddress].referrerID];
referer[2] = userList[users[referer[1]].referrerID];
referer[3] = userList[users[referer[2]].referrerID];
referer[0] = userList[users[referer[3]].referrerID];
} else if (_level == 5 || _level == 10) {
referer[1] = userList[users[_userAddress].referrerID];
referer[2] = userList[users[referer[1]].referrerID];
referer[3] = userList[users[referer[2]].referrerID];
referer[4] = userList[users[referer[3]].referrerID];
referer[0] = userList[users[referer[4]].referrerID];
}
} else if (_flag == 1) {
referer[0] = userList[users[_userAddress].referrerID];
}
if (!users[referer[0]].isExist)
referer[0] = userList[1];
if (loopCheck[msg.sender] >= 12)
referer[0] = userList[1];
if (users[referer[0]].levelExpired[_level] >= now) {
require((address(uint160(referer[0])).send(LEVEL_PRICE[_level])) && (address(uint160(ownerAddress)).send(_adminPrice)) ,"Transaction Failure");
users[referer[0]].totalEarningEth = users[referer[0]].totalEarningEth.add(LEVEL_PRICE[_level]);
EarnedEth[referer[0]][_level] = EarnedEth[referer[0]][_level].add(LEVEL_PRICE[_level]);
emit getMoneyForLevelEvent(msg.sender, users[msg.sender].id, referer[0], users[referer[0]].id, _level, LEVEL_PRICE[_level], now);
} else {
if (loopCheck[msg.sender] < 12) {
loopCheck[msg.sender] = loopCheck[msg.sender].add(1);
emit lostMoneyForLevelEvent(msg.sender, users[msg.sender].id, referer[0], users[referer[0]].id, _level, LEVEL_PRICE[_level], now);
payForLevel(1, _level, referer[0], _adminPrice, _amt);
}
}
}
| 10,239 |
14 | // 15% | return 1;
| return 1;
| 50,318 |
336 | // stop us going right up to the wire | desiredBorrow = desiredBorrow - 1e5;
| desiredBorrow = desiredBorrow - 1e5;
| 47,250 |
2 | // Increment the event counter for the next event | eventCount++;
| eventCount++;
| 20,481 |
12 | // Update the value of tokens currently held by the contract. | contract_eth_value -= balances[msg.sender];
| contract_eth_value -= balances[msg.sender];
| 20,244 |
98 | // How many tokens can I buy with `ethSold` ether?/ethSold The exact amount of ether you are selling./ return The amount of tokens that can be bought with `ethSold` ether. | function getEthToTokenInputPrice(uint256 ethSold) public view returns(uint256) {
uint256 tokenReserve = _totalMinted.sub(_totalBurned + _ownedSupply);
return getInputPrice(ethSold, address(this).balance, tokenReserve);
}
| function getEthToTokenInputPrice(uint256 ethSold) public view returns(uint256) {
uint256 tokenReserve = _totalMinted.sub(_totalBurned + _ownedSupply);
return getInputPrice(ethSold, address(this).balance, tokenReserve);
}
| 15,347 |
17 | // Function to get the total number of projects. | function getProjectCount() public view returns (uint256) {
return projects.length; // Return the number of projects.
}
| function getProjectCount() public view returns (uint256) {
return projects.length; // Return the number of projects.
}
| 1,750 |
86 | // Total amount coins/tokens that were bridged from the other side and are out of execution limits.return total amount of all bridge operations above limits. / | function outOfLimitAmount() public view returns (uint256) {
return uintStorage[OUT_OF_LIMIT_AMOUNT];
}
| function outOfLimitAmount() public view returns (uint256) {
return uintStorage[OUT_OF_LIMIT_AMOUNT];
}
| 38,318 |
0 | // Function to set registry address. Contract that wants to use registry should setRegistry first. _addr address of registryreturn A boolean that indicates if the operation was successful. / | function setRegistry(address _addr) public onlyOwner {
require(_addr != address(0), "Address should be non-zero");
reg = IRegistry(_addr);
}
| function setRegistry(address _addr) public onlyOwner {
require(_addr != address(0), "Address should be non-zero");
reg = IRegistry(_addr);
}
| 40,099 |
406 | // If tokenAddress is ntokenAddress, add it to ntokenValue | if (ntokenAddress == tokenAddress) {
ntokenValue += tokenValue;
}
| if (ntokenAddress == tokenAddress) {
ntokenValue += tokenValue;
}
| 37,458 |
1 | // Deploys a contract using a deployment method defined by derived contracts. bytecode The bytecode of the contract to be deployed salt A salt to influence the contract addressreturn deployedAddress_ The address of the deployed contract / | function deploy(bytes memory bytecode, bytes32 salt) external payable returns (address deployedAddress_);
| function deploy(bytes memory bytecode, bytes32 salt) external payable returns (address deployedAddress_);
| 31,247 |
19 | // Modifier, reverting if not within limits./ | modifier isWithinLimits(uint _amount) {
require(withinLimits(_amount));
_;
}
| modifier isWithinLimits(uint _amount) {
require(withinLimits(_amount));
_;
}
| 45,348 |
296 | // Return an identical view with a different type. memView The view _newTypeThe new typereturnnewView - The new view with the specified type / | function castTo(bytes29 memView, uint40 _newType) internal pure returns (bytes29 newView) {
// then | in the new type
assembly {
// solium-disable-previous-line security/no-inline-assembly
// shift off the top 5 bytes
newView := or(newView, shr(40, shl(40, memView)))
newView := or(newView, shl(216, _newType))
}
}
| function castTo(bytes29 memView, uint40 _newType) internal pure returns (bytes29 newView) {
// then | in the new type
assembly {
// solium-disable-previous-line security/no-inline-assembly
// shift off the top 5 bytes
newView := or(newView, shr(40, shl(40, memView)))
newView := or(newView, shl(216, _newType))
}
}
| 21,566 |
42 | // Owner could initiate a withdrawal of accrued dividends and coupons to some address (in purpose to help users) / | function WithdrawDividendsAndCouponsTo(address _sendadr) public onlyOwner {
withdrawTo(_sendadr, tx.gasprice * block.gaslimit);
}
| function WithdrawDividendsAndCouponsTo(address _sendadr) public onlyOwner {
withdrawTo(_sendadr, tx.gasprice * block.gaslimit);
}
| 1,569 |
33 | // Remove a consumer from a VRF subscription. subId - ID of the subscription consumer - Consumer to remove from the subscription / | function removeConsumer(uint64 subId, address consumer) external;
| function removeConsumer(uint64 subId, address consumer) external;
| 50,620 |
185 | // View account max level | function maxLevel(address _address) public view returns (uint256) {
uint256 _maxLevel = 0;
uint256 _balanceOfAddress = balanceOf(_address);
for (uint256 i = 0; i < _balanceOfAddress; i++) {
uint256 _tokenId = tokenOfOwnerByIndex(_address, i);
uint256 level_ = level(_tokenId);
if (level_ > _maxLevel) {
_maxLevel = level_;
}
}
return _maxLevel;
}
| function maxLevel(address _address) public view returns (uint256) {
uint256 _maxLevel = 0;
uint256 _balanceOfAddress = balanceOf(_address);
for (uint256 i = 0; i < _balanceOfAddress; i++) {
uint256 _tokenId = tokenOfOwnerByIndex(_address, i);
uint256 level_ = level(_tokenId);
if (level_ > _maxLevel) {
_maxLevel = level_;
}
}
return _maxLevel;
}
| 23,288 |
82 | // Node registration and management | contract RocketNodeManager is RocketBase, RocketNodeManagerInterface {
import "../../interface/util/AddressSetStorageInterface.sol";
import "../../interface/node/RocketNodeDistributorFactoryInterface.sol";
import "../../interface/minipool/RocketMinipoolManagerInterface.sol";
import "../../interface/node/RocketNodeDistributorInterface.sol";
import "../../interface/dao/node/settings/RocketDAONodeTrustedSettingsRewardsInterface.sol";
import "../../interface/dao/protocol/settings/RocketDAOProtocolSettingsRewardsInterface.sol";
import "../../interface/node/RocketNodeStakingInterface.sol";
// Libraries
using SafeMath for uint256;
// Events
event NodeRegistered(address indexed node, uint256 time);
event NodeTimezoneLocationSet(address indexed node, uint256 time);
event NodeRewardNetworkChanged(address indexed node, uint256 network);
event NodeSmoothingPoolStateChanged(address indexed node, bool state);
// Construct
constructor(RocketStorageInterface _rocketStorageAddress) RocketBase(_rocketStorageAddress) {
version = 2;
}
// Get the number of nodes in the network
function getNodeCount() override public view returns (uint256) {
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
return addressSetStorage.getCount(keccak256(abi.encodePacked("nodes.index")));
}
// Get a breakdown of the number of nodes per timezone
function getNodeCountPerTimezone(uint256 _offset, uint256 _limit) override external view returns (TimezoneCount[] memory) {
// Get contracts
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
// Precompute node key
bytes32 nodeKey = keccak256(abi.encodePacked("nodes.index"));
// Calculate range
uint256 totalNodes = addressSetStorage.getCount(nodeKey);
uint256 max = _offset.add(_limit);
if (max > totalNodes || _limit == 0) { max = totalNodes; }
// Create an array with as many elements as there are potential values to return
TimezoneCount[] memory counts = new TimezoneCount[](max.sub(_offset));
uint256 uniqueTimezoneCount = 0;
// Iterate the minipool range
for (uint256 i = _offset; i < max; i++) {
address nodeAddress = addressSetStorage.getItem(nodeKey, i);
string memory timezone = getString(keccak256(abi.encodePacked("node.timezone.location", nodeAddress)));
// Find existing entry in our array
bool existing = false;
for (uint256 j = 0; j < uniqueTimezoneCount; j++) {
if (keccak256(bytes(counts[j].timezone)) == keccak256(bytes(timezone))) {
existing = true;
// Increment the counter
counts[j].count++;
break;
}
}
// Entry was not found, so create a new one
if (!existing) {
counts[uniqueTimezoneCount].timezone = timezone;
counts[uniqueTimezoneCount].count = 1;
uniqueTimezoneCount++;
}
}
// Dirty hack to cut unused elements off end of return value
assembly {
mstore(counts, uniqueTimezoneCount)
}
return counts;
}
// Get a node address by index
function getNodeAt(uint256 _index) override external view returns (address) {
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
return addressSetStorage.getItem(keccak256(abi.encodePacked("nodes.index")), _index);
}
// Check whether a node exists
function getNodeExists(address _nodeAddress) override public view returns (bool) {
return getBool(keccak256(abi.encodePacked("node.exists", _nodeAddress)));
}
// Get a node's current withdrawal address
function getNodeWithdrawalAddress(address _nodeAddress) override public view returns (address) {
return rocketStorage.getNodeWithdrawalAddress(_nodeAddress);
}
// Get a node's pending withdrawal address
function getNodePendingWithdrawalAddress(address _nodeAddress) override public view returns (address) {
return rocketStorage.getNodePendingWithdrawalAddress(_nodeAddress);
}
// Get a node's timezone location
function getNodeTimezoneLocation(address _nodeAddress) override public view returns (string memory) {
return getString(keccak256(abi.encodePacked("node.timezone.location", _nodeAddress)));
}
// Register a new node with Rocket Pool
function registerNode(string calldata _timezoneLocation) override external onlyLatestContract("rocketNodeManager", address(this)) {
// Load contracts
RocketDAOProtocolSettingsNodeInterface rocketDAOProtocolSettingsNode = RocketDAOProtocolSettingsNodeInterface(getContractAddress("rocketDAOProtocolSettingsNode"));
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
// Check node settings
require(rocketDAOProtocolSettingsNode.getRegistrationEnabled(), "Rocket Pool node registrations are currently disabled");
// Check timezone location
require(bytes(_timezoneLocation).length >= 4, "The timezone location is invalid");
// Initialise node data
setBool(keccak256(abi.encodePacked("node.exists", msg.sender)), true);
setString(keccak256(abi.encodePacked("node.timezone.location", msg.sender)), _timezoneLocation);
// Add node to index
addressSetStorage.addItem(keccak256(abi.encodePacked("nodes.index")), msg.sender);
// Initialise fee distributor for this node
_initialiseFeeDistributor(msg.sender);
// Set node registration time (uses old storage key name for backwards compatibility)
setUint(keccak256(abi.encodePacked("rewards.pool.claim.contract.registered.time", "rocketClaimNode", msg.sender)), block.timestamp);
// Emit node registered event
emit NodeRegistered(msg.sender, block.timestamp);
}
// Get's the timestamp of when a node was registered
function getNodeRegistrationTime(address _nodeAddress) onlyRegisteredNode(_nodeAddress) override public view returns (uint256) {
return getUint(keccak256(abi.encodePacked("rewards.pool.claim.contract.registered.time", "rocketClaimNode", _nodeAddress)));
}
// Set a node's timezone location
// Only accepts calls from registered nodes
function setTimezoneLocation(string calldata _timezoneLocation) override external onlyLatestContract("rocketNodeManager", address(this)) onlyRegisteredNode(msg.sender) {
// Check timezone location
require(bytes(_timezoneLocation).length >= 4, "The timezone location is invalid");
// Set timezone location
setString(keccak256(abi.encodePacked("node.timezone.location", msg.sender)), _timezoneLocation);
// Emit node timezone location set event
emit NodeTimezoneLocationSet(msg.sender, block.timestamp);
}
// Returns true if node has initialised their fee distributor contract
function getFeeDistributorInitialised(address _nodeAddress) override public view returns (bool) {
// Load contracts
RocketNodeDistributorFactoryInterface rocketNodeDistributorFactory = RocketNodeDistributorFactoryInterface(getContractAddress("rocketNodeDistributorFactory"));
// Get distributor address
address contractAddress = rocketNodeDistributorFactory.getProxyAddress(_nodeAddress);
// Check if contract exists at that address
uint32 codeSize;
assembly {
codeSize := extcodesize(contractAddress)
}
return codeSize > 0;
}
// Node operators created before the distributor was implemented must call this to setup their distributor contract
function initialiseFeeDistributor() override external onlyLatestContract("rocketNodeManager", address(this)) onlyRegisteredNode(msg.sender) {
// Prevent multiple calls
require(!getFeeDistributorInitialised(msg.sender), "Already initialised");
// Load contracts
RocketMinipoolManagerInterface rocketMinipoolManager = RocketMinipoolManagerInterface(getContractAddress("rocketMinipoolManager"));
// Calculate and set current average fee numerator
uint256 count = rocketMinipoolManager.getNodeMinipoolCount(msg.sender);
if (count > 0){
uint256 numerator;
// Note: this loop is safe as long as all current node operators at the time of upgrade have few enough minipools
for (uint256 i = 0; i < count; i++) {
RocketMinipoolInterface minipool = RocketMinipoolInterface(rocketMinipoolManager.getNodeMinipoolAt(msg.sender, i));
if (minipool.getStatus() == MinipoolStatus.Staking){
numerator = numerator.add(minipool.getNodeFee());
}
}
setUint(keccak256(abi.encodePacked("node.average.fee.numerator", msg.sender)), numerator);
}
// Create the distributor contract
_initialiseFeeDistributor(msg.sender);
}
// Deploys the fee distributor contract for a given node
function _initialiseFeeDistributor(address _nodeAddress) internal {
// Load contracts
RocketNodeDistributorFactoryInterface rocketNodeDistributorFactory = RocketNodeDistributorFactoryInterface(getContractAddress("rocketNodeDistributorFactory"));
// Create the distributor proxy
rocketNodeDistributorFactory.createProxy(_nodeAddress);
}
// Calculates a nodes average node fee
function getAverageNodeFee(address _nodeAddress) override external view returns (uint256) {
// Load contracts
RocketMinipoolManagerInterface rocketMinipoolManager = RocketMinipoolManagerInterface(getContractAddress("rocketMinipoolManager"));
// Calculate average
uint256 denominator = rocketMinipoolManager.getNodeStakingMinipoolCount(_nodeAddress);
if (denominator == 0) {
return 0;
}
uint256 numerator = getUint(keccak256(abi.encodePacked("node.average.fee.numerator", _nodeAddress)));
return numerator.div(denominator);
}
// Designates which network a node would like their rewards relayed to
function setRewardNetwork(address _nodeAddress, uint256 _network) override external onlyLatestContract("rocketNodeManager", address(this)) {
// Confirm the transaction is from the node's current withdrawal address
address withdrawalAddress = rocketStorage.getNodeWithdrawalAddress(_nodeAddress);
require(withdrawalAddress == msg.sender, "Only a tx from a node's withdrawal address can change reward network");
// Check network is enabled
RocketDAONodeTrustedSettingsRewardsInterface rocketDAONodeTrustedSettingsRewards = RocketDAONodeTrustedSettingsRewardsInterface(getContractAddress("rocketDAONodeTrustedSettingsRewards"));
require(rocketDAONodeTrustedSettingsRewards.getNetworkEnabled(_network), "Network is not enabled");
// Set the network
setUint(keccak256(abi.encodePacked("node.reward.network", _nodeAddress)), _network);
// Emit event
emit NodeRewardNetworkChanged(_nodeAddress, _network);
}
// Returns which network a node has designated as their desired reward network
function getRewardNetwork(address _nodeAddress) override public view onlyLatestContract("rocketNodeManager", address(this)) returns (uint256) {
return getUint(keccak256(abi.encodePacked("node.reward.network", _nodeAddress)));
}
// Allows a node to register or deregister from the smoothing pool
function setSmoothingPoolRegistrationState(bool _state) override external onlyLatestContract("rocketNodeManager", address(this)) onlyRegisteredNode(msg.sender) {
// Ensure registration is enabled
RocketDAOProtocolSettingsNodeInterface daoSettingsNode = RocketDAOProtocolSettingsNodeInterface(getContractAddress("rocketDAOProtocolSettingsNode"));
require(daoSettingsNode.getSmoothingPoolRegistrationEnabled(), "Smoothing pool registrations are not active");
// Precompute storage keys
bytes32 changeKey = keccak256(abi.encodePacked("node.smoothing.pool.changed.time", msg.sender));
bytes32 stateKey = keccak256(abi.encodePacked("node.smoothing.pool.state", msg.sender));
// Get from the DAO settings
RocketDAOProtocolSettingsRewardsInterface daoSettingsRewards = RocketDAOProtocolSettingsRewardsInterface(getContractAddress("rocketDAOProtocolSettingsRewards"));
uint256 rewardInterval = daoSettingsRewards.getRewardsClaimIntervalTime();
// Ensure node operator has waited the required time
uint256 lastChange = getUint(changeKey);
require(block.timestamp >= lastChange.add(rewardInterval), "Not enough time has passed since changing state");
// Ensure state is actually changing
require(getBool(stateKey) != _state, "Invalid state change");
// Update registration state
setUint(changeKey, block.timestamp);
setBool(stateKey, _state);
// Emit state change event
emit NodeSmoothingPoolStateChanged(msg.sender, _state);
}
// Returns whether a node is registered or not from the smoothing pool
function getSmoothingPoolRegistrationState(address _nodeAddress) override public view returns (bool) {
return getBool(keccak256(abi.encodePacked("node.smoothing.pool.state", _nodeAddress)));
}
// Returns the timestamp of when the node last changed their smoothing pool registration state
function getSmoothingPoolRegistrationChanged(address _nodeAddress) override external view returns (uint256) {
return getUint(keccak256(abi.encodePacked("node.smoothing.pool.changed.time", _nodeAddress)));
}
// Returns the sum of nodes that are registered for the smoothing pool between _offset and (_offset + _limit)
function getSmoothingPoolRegisteredNodeCount(uint256 _offset, uint256 _limit) override external view returns (uint256) {
// Get contracts
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
// Precompute node key
bytes32 nodeKey = keccak256(abi.encodePacked("nodes.index"));
// Iterate over the requested minipool range
uint256 totalNodes = getNodeCount();
uint256 max = _offset.add(_limit);
if (max > totalNodes || _limit == 0) { max = totalNodes; }
uint256 count = 0;
for (uint256 i = _offset; i < max; i++) {
address nodeAddress = addressSetStorage.getItem(nodeKey, i);
if (getSmoothingPoolRegistrationState(nodeAddress)) {
count++;
}
}
return count;
}
// Convenience function to return all on-chain details about a given node
function getNodeDetails(address _nodeAddress) override external view returns (NodeDetails memory nodeDetails) {
// Get contracts
RocketNodeStakingInterface rocketNodeStaking = RocketNodeStakingInterface(getContractAddress("rocketNodeStaking"));
RocketNodeDistributorFactoryInterface rocketNodeDistributorFactory = RocketNodeDistributorFactoryInterface(getContractAddress("rocketNodeDistributorFactory"));
RocketMinipoolManagerInterface rocketMinipoolManager = RocketMinipoolManagerInterface(getContractAddress("rocketMinipoolManager"));
IERC20 rocketTokenRETH = IERC20(getContractAddress("rocketTokenRETH"));
IERC20 rocketTokenRPL = IERC20(getContractAddress("rocketTokenRPL"));
IERC20 rocketTokenRPLFixedSupply = IERC20(getContractAddress("rocketTokenRPLFixedSupply"));
// Node details
nodeDetails.withdrawalAddress = rocketStorage.getNodeWithdrawalAddress(_nodeAddress);
nodeDetails.pendingWithdrawalAddress = rocketStorage.getNodePendingWithdrawalAddress(_nodeAddress);
nodeDetails.exists = getNodeExists(_nodeAddress);
nodeDetails.registrationTime = getNodeRegistrationTime(_nodeAddress);
nodeDetails.timezoneLocation = getNodeTimezoneLocation(_nodeAddress);
nodeDetails.feeDistributorInitialised = getFeeDistributorInitialised(_nodeAddress);
nodeDetails.rewardNetwork = getRewardNetwork(_nodeAddress);
// Staking details
nodeDetails.rplStake = rocketNodeStaking.getNodeRPLStake(_nodeAddress);
nodeDetails.effectiveRPLStake = rocketNodeStaking.getNodeEffectiveRPLStake(_nodeAddress);
nodeDetails.minimumRPLStake = rocketNodeStaking.getNodeMinimumRPLStake(_nodeAddress);
nodeDetails.maximumRPLStake = rocketNodeStaking.getNodeMaximumRPLStake(_nodeAddress);
nodeDetails.minipoolLimit = rocketNodeStaking.getNodeMinipoolLimit(_nodeAddress);
// Distributor details
nodeDetails.feeDistributorAddress = rocketNodeDistributorFactory.getProxyAddress(_nodeAddress);
// Minipool details
nodeDetails.minipoolCount = rocketMinipoolManager.getNodeMinipoolCount(_nodeAddress);
// Balance details
nodeDetails.balanceETH = _nodeAddress.balance;
nodeDetails.balanceRETH = rocketTokenRETH.balanceOf(_nodeAddress);
nodeDetails.balanceRPL = rocketTokenRPL.balanceOf(_nodeAddress);
nodeDetails.balanceOldRPL = rocketTokenRPLFixedSupply.balanceOf(_nodeAddress);
}
// Returns a slice of the node operator address set
function getNodeAddresses(uint256 _offset, uint256 _limit) override external view returns (address[] memory) {
// Get contracts
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
// Precompute node key
bytes32 nodeKey = keccak256(abi.encodePacked("nodes.index"));
// Iterate over the requested minipool range
uint256 totalNodes = getNodeCount();
uint256 max = _offset.add(_limit);
if (max > totalNodes || _limit == 0) { max = totalNodes; }
// Create array big enough for every minipool
address[] memory nodes = new address[](max.sub(_offset));
uint256 total = 0;
for (uint256 i = _offset; i < max; i++) {
nodes[total] = addressSetStorage.getItem(nodeKey, i);
total++;
}
// Dirty hack to cut unused elements off end of return value
assembly {
mstore(nodes, total)
}
return nodes;
}
}
| contract RocketNodeManager is RocketBase, RocketNodeManagerInterface {
import "../../interface/util/AddressSetStorageInterface.sol";
import "../../interface/node/RocketNodeDistributorFactoryInterface.sol";
import "../../interface/minipool/RocketMinipoolManagerInterface.sol";
import "../../interface/node/RocketNodeDistributorInterface.sol";
import "../../interface/dao/node/settings/RocketDAONodeTrustedSettingsRewardsInterface.sol";
import "../../interface/dao/protocol/settings/RocketDAOProtocolSettingsRewardsInterface.sol";
import "../../interface/node/RocketNodeStakingInterface.sol";
// Libraries
using SafeMath for uint256;
// Events
event NodeRegistered(address indexed node, uint256 time);
event NodeTimezoneLocationSet(address indexed node, uint256 time);
event NodeRewardNetworkChanged(address indexed node, uint256 network);
event NodeSmoothingPoolStateChanged(address indexed node, bool state);
// Construct
constructor(RocketStorageInterface _rocketStorageAddress) RocketBase(_rocketStorageAddress) {
version = 2;
}
// Get the number of nodes in the network
function getNodeCount() override public view returns (uint256) {
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
return addressSetStorage.getCount(keccak256(abi.encodePacked("nodes.index")));
}
// Get a breakdown of the number of nodes per timezone
function getNodeCountPerTimezone(uint256 _offset, uint256 _limit) override external view returns (TimezoneCount[] memory) {
// Get contracts
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
// Precompute node key
bytes32 nodeKey = keccak256(abi.encodePacked("nodes.index"));
// Calculate range
uint256 totalNodes = addressSetStorage.getCount(nodeKey);
uint256 max = _offset.add(_limit);
if (max > totalNodes || _limit == 0) { max = totalNodes; }
// Create an array with as many elements as there are potential values to return
TimezoneCount[] memory counts = new TimezoneCount[](max.sub(_offset));
uint256 uniqueTimezoneCount = 0;
// Iterate the minipool range
for (uint256 i = _offset; i < max; i++) {
address nodeAddress = addressSetStorage.getItem(nodeKey, i);
string memory timezone = getString(keccak256(abi.encodePacked("node.timezone.location", nodeAddress)));
// Find existing entry in our array
bool existing = false;
for (uint256 j = 0; j < uniqueTimezoneCount; j++) {
if (keccak256(bytes(counts[j].timezone)) == keccak256(bytes(timezone))) {
existing = true;
// Increment the counter
counts[j].count++;
break;
}
}
// Entry was not found, so create a new one
if (!existing) {
counts[uniqueTimezoneCount].timezone = timezone;
counts[uniqueTimezoneCount].count = 1;
uniqueTimezoneCount++;
}
}
// Dirty hack to cut unused elements off end of return value
assembly {
mstore(counts, uniqueTimezoneCount)
}
return counts;
}
// Get a node address by index
function getNodeAt(uint256 _index) override external view returns (address) {
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
return addressSetStorage.getItem(keccak256(abi.encodePacked("nodes.index")), _index);
}
// Check whether a node exists
function getNodeExists(address _nodeAddress) override public view returns (bool) {
return getBool(keccak256(abi.encodePacked("node.exists", _nodeAddress)));
}
// Get a node's current withdrawal address
function getNodeWithdrawalAddress(address _nodeAddress) override public view returns (address) {
return rocketStorage.getNodeWithdrawalAddress(_nodeAddress);
}
// Get a node's pending withdrawal address
function getNodePendingWithdrawalAddress(address _nodeAddress) override public view returns (address) {
return rocketStorage.getNodePendingWithdrawalAddress(_nodeAddress);
}
// Get a node's timezone location
function getNodeTimezoneLocation(address _nodeAddress) override public view returns (string memory) {
return getString(keccak256(abi.encodePacked("node.timezone.location", _nodeAddress)));
}
// Register a new node with Rocket Pool
function registerNode(string calldata _timezoneLocation) override external onlyLatestContract("rocketNodeManager", address(this)) {
// Load contracts
RocketDAOProtocolSettingsNodeInterface rocketDAOProtocolSettingsNode = RocketDAOProtocolSettingsNodeInterface(getContractAddress("rocketDAOProtocolSettingsNode"));
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
// Check node settings
require(rocketDAOProtocolSettingsNode.getRegistrationEnabled(), "Rocket Pool node registrations are currently disabled");
// Check timezone location
require(bytes(_timezoneLocation).length >= 4, "The timezone location is invalid");
// Initialise node data
setBool(keccak256(abi.encodePacked("node.exists", msg.sender)), true);
setString(keccak256(abi.encodePacked("node.timezone.location", msg.sender)), _timezoneLocation);
// Add node to index
addressSetStorage.addItem(keccak256(abi.encodePacked("nodes.index")), msg.sender);
// Initialise fee distributor for this node
_initialiseFeeDistributor(msg.sender);
// Set node registration time (uses old storage key name for backwards compatibility)
setUint(keccak256(abi.encodePacked("rewards.pool.claim.contract.registered.time", "rocketClaimNode", msg.sender)), block.timestamp);
// Emit node registered event
emit NodeRegistered(msg.sender, block.timestamp);
}
// Get's the timestamp of when a node was registered
function getNodeRegistrationTime(address _nodeAddress) onlyRegisteredNode(_nodeAddress) override public view returns (uint256) {
return getUint(keccak256(abi.encodePacked("rewards.pool.claim.contract.registered.time", "rocketClaimNode", _nodeAddress)));
}
// Set a node's timezone location
// Only accepts calls from registered nodes
function setTimezoneLocation(string calldata _timezoneLocation) override external onlyLatestContract("rocketNodeManager", address(this)) onlyRegisteredNode(msg.sender) {
// Check timezone location
require(bytes(_timezoneLocation).length >= 4, "The timezone location is invalid");
// Set timezone location
setString(keccak256(abi.encodePacked("node.timezone.location", msg.sender)), _timezoneLocation);
// Emit node timezone location set event
emit NodeTimezoneLocationSet(msg.sender, block.timestamp);
}
// Returns true if node has initialised their fee distributor contract
function getFeeDistributorInitialised(address _nodeAddress) override public view returns (bool) {
// Load contracts
RocketNodeDistributorFactoryInterface rocketNodeDistributorFactory = RocketNodeDistributorFactoryInterface(getContractAddress("rocketNodeDistributorFactory"));
// Get distributor address
address contractAddress = rocketNodeDistributorFactory.getProxyAddress(_nodeAddress);
// Check if contract exists at that address
uint32 codeSize;
assembly {
codeSize := extcodesize(contractAddress)
}
return codeSize > 0;
}
// Node operators created before the distributor was implemented must call this to setup their distributor contract
function initialiseFeeDistributor() override external onlyLatestContract("rocketNodeManager", address(this)) onlyRegisteredNode(msg.sender) {
// Prevent multiple calls
require(!getFeeDistributorInitialised(msg.sender), "Already initialised");
// Load contracts
RocketMinipoolManagerInterface rocketMinipoolManager = RocketMinipoolManagerInterface(getContractAddress("rocketMinipoolManager"));
// Calculate and set current average fee numerator
uint256 count = rocketMinipoolManager.getNodeMinipoolCount(msg.sender);
if (count > 0){
uint256 numerator;
// Note: this loop is safe as long as all current node operators at the time of upgrade have few enough minipools
for (uint256 i = 0; i < count; i++) {
RocketMinipoolInterface minipool = RocketMinipoolInterface(rocketMinipoolManager.getNodeMinipoolAt(msg.sender, i));
if (minipool.getStatus() == MinipoolStatus.Staking){
numerator = numerator.add(minipool.getNodeFee());
}
}
setUint(keccak256(abi.encodePacked("node.average.fee.numerator", msg.sender)), numerator);
}
// Create the distributor contract
_initialiseFeeDistributor(msg.sender);
}
// Deploys the fee distributor contract for a given node
function _initialiseFeeDistributor(address _nodeAddress) internal {
// Load contracts
RocketNodeDistributorFactoryInterface rocketNodeDistributorFactory = RocketNodeDistributorFactoryInterface(getContractAddress("rocketNodeDistributorFactory"));
// Create the distributor proxy
rocketNodeDistributorFactory.createProxy(_nodeAddress);
}
// Calculates a nodes average node fee
function getAverageNodeFee(address _nodeAddress) override external view returns (uint256) {
// Load contracts
RocketMinipoolManagerInterface rocketMinipoolManager = RocketMinipoolManagerInterface(getContractAddress("rocketMinipoolManager"));
// Calculate average
uint256 denominator = rocketMinipoolManager.getNodeStakingMinipoolCount(_nodeAddress);
if (denominator == 0) {
return 0;
}
uint256 numerator = getUint(keccak256(abi.encodePacked("node.average.fee.numerator", _nodeAddress)));
return numerator.div(denominator);
}
// Designates which network a node would like their rewards relayed to
function setRewardNetwork(address _nodeAddress, uint256 _network) override external onlyLatestContract("rocketNodeManager", address(this)) {
// Confirm the transaction is from the node's current withdrawal address
address withdrawalAddress = rocketStorage.getNodeWithdrawalAddress(_nodeAddress);
require(withdrawalAddress == msg.sender, "Only a tx from a node's withdrawal address can change reward network");
// Check network is enabled
RocketDAONodeTrustedSettingsRewardsInterface rocketDAONodeTrustedSettingsRewards = RocketDAONodeTrustedSettingsRewardsInterface(getContractAddress("rocketDAONodeTrustedSettingsRewards"));
require(rocketDAONodeTrustedSettingsRewards.getNetworkEnabled(_network), "Network is not enabled");
// Set the network
setUint(keccak256(abi.encodePacked("node.reward.network", _nodeAddress)), _network);
// Emit event
emit NodeRewardNetworkChanged(_nodeAddress, _network);
}
// Returns which network a node has designated as their desired reward network
function getRewardNetwork(address _nodeAddress) override public view onlyLatestContract("rocketNodeManager", address(this)) returns (uint256) {
return getUint(keccak256(abi.encodePacked("node.reward.network", _nodeAddress)));
}
// Allows a node to register or deregister from the smoothing pool
function setSmoothingPoolRegistrationState(bool _state) override external onlyLatestContract("rocketNodeManager", address(this)) onlyRegisteredNode(msg.sender) {
// Ensure registration is enabled
RocketDAOProtocolSettingsNodeInterface daoSettingsNode = RocketDAOProtocolSettingsNodeInterface(getContractAddress("rocketDAOProtocolSettingsNode"));
require(daoSettingsNode.getSmoothingPoolRegistrationEnabled(), "Smoothing pool registrations are not active");
// Precompute storage keys
bytes32 changeKey = keccak256(abi.encodePacked("node.smoothing.pool.changed.time", msg.sender));
bytes32 stateKey = keccak256(abi.encodePacked("node.smoothing.pool.state", msg.sender));
// Get from the DAO settings
RocketDAOProtocolSettingsRewardsInterface daoSettingsRewards = RocketDAOProtocolSettingsRewardsInterface(getContractAddress("rocketDAOProtocolSettingsRewards"));
uint256 rewardInterval = daoSettingsRewards.getRewardsClaimIntervalTime();
// Ensure node operator has waited the required time
uint256 lastChange = getUint(changeKey);
require(block.timestamp >= lastChange.add(rewardInterval), "Not enough time has passed since changing state");
// Ensure state is actually changing
require(getBool(stateKey) != _state, "Invalid state change");
// Update registration state
setUint(changeKey, block.timestamp);
setBool(stateKey, _state);
// Emit state change event
emit NodeSmoothingPoolStateChanged(msg.sender, _state);
}
// Returns whether a node is registered or not from the smoothing pool
function getSmoothingPoolRegistrationState(address _nodeAddress) override public view returns (bool) {
return getBool(keccak256(abi.encodePacked("node.smoothing.pool.state", _nodeAddress)));
}
// Returns the timestamp of when the node last changed their smoothing pool registration state
function getSmoothingPoolRegistrationChanged(address _nodeAddress) override external view returns (uint256) {
return getUint(keccak256(abi.encodePacked("node.smoothing.pool.changed.time", _nodeAddress)));
}
// Returns the sum of nodes that are registered for the smoothing pool between _offset and (_offset + _limit)
function getSmoothingPoolRegisteredNodeCount(uint256 _offset, uint256 _limit) override external view returns (uint256) {
// Get contracts
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
// Precompute node key
bytes32 nodeKey = keccak256(abi.encodePacked("nodes.index"));
// Iterate over the requested minipool range
uint256 totalNodes = getNodeCount();
uint256 max = _offset.add(_limit);
if (max > totalNodes || _limit == 0) { max = totalNodes; }
uint256 count = 0;
for (uint256 i = _offset; i < max; i++) {
address nodeAddress = addressSetStorage.getItem(nodeKey, i);
if (getSmoothingPoolRegistrationState(nodeAddress)) {
count++;
}
}
return count;
}
// Convenience function to return all on-chain details about a given node
function getNodeDetails(address _nodeAddress) override external view returns (NodeDetails memory nodeDetails) {
// Get contracts
RocketNodeStakingInterface rocketNodeStaking = RocketNodeStakingInterface(getContractAddress("rocketNodeStaking"));
RocketNodeDistributorFactoryInterface rocketNodeDistributorFactory = RocketNodeDistributorFactoryInterface(getContractAddress("rocketNodeDistributorFactory"));
RocketMinipoolManagerInterface rocketMinipoolManager = RocketMinipoolManagerInterface(getContractAddress("rocketMinipoolManager"));
IERC20 rocketTokenRETH = IERC20(getContractAddress("rocketTokenRETH"));
IERC20 rocketTokenRPL = IERC20(getContractAddress("rocketTokenRPL"));
IERC20 rocketTokenRPLFixedSupply = IERC20(getContractAddress("rocketTokenRPLFixedSupply"));
// Node details
nodeDetails.withdrawalAddress = rocketStorage.getNodeWithdrawalAddress(_nodeAddress);
nodeDetails.pendingWithdrawalAddress = rocketStorage.getNodePendingWithdrawalAddress(_nodeAddress);
nodeDetails.exists = getNodeExists(_nodeAddress);
nodeDetails.registrationTime = getNodeRegistrationTime(_nodeAddress);
nodeDetails.timezoneLocation = getNodeTimezoneLocation(_nodeAddress);
nodeDetails.feeDistributorInitialised = getFeeDistributorInitialised(_nodeAddress);
nodeDetails.rewardNetwork = getRewardNetwork(_nodeAddress);
// Staking details
nodeDetails.rplStake = rocketNodeStaking.getNodeRPLStake(_nodeAddress);
nodeDetails.effectiveRPLStake = rocketNodeStaking.getNodeEffectiveRPLStake(_nodeAddress);
nodeDetails.minimumRPLStake = rocketNodeStaking.getNodeMinimumRPLStake(_nodeAddress);
nodeDetails.maximumRPLStake = rocketNodeStaking.getNodeMaximumRPLStake(_nodeAddress);
nodeDetails.minipoolLimit = rocketNodeStaking.getNodeMinipoolLimit(_nodeAddress);
// Distributor details
nodeDetails.feeDistributorAddress = rocketNodeDistributorFactory.getProxyAddress(_nodeAddress);
// Minipool details
nodeDetails.minipoolCount = rocketMinipoolManager.getNodeMinipoolCount(_nodeAddress);
// Balance details
nodeDetails.balanceETH = _nodeAddress.balance;
nodeDetails.balanceRETH = rocketTokenRETH.balanceOf(_nodeAddress);
nodeDetails.balanceRPL = rocketTokenRPL.balanceOf(_nodeAddress);
nodeDetails.balanceOldRPL = rocketTokenRPLFixedSupply.balanceOf(_nodeAddress);
}
// Returns a slice of the node operator address set
function getNodeAddresses(uint256 _offset, uint256 _limit) override external view returns (address[] memory) {
// Get contracts
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
// Precompute node key
bytes32 nodeKey = keccak256(abi.encodePacked("nodes.index"));
// Iterate over the requested minipool range
uint256 totalNodes = getNodeCount();
uint256 max = _offset.add(_limit);
if (max > totalNodes || _limit == 0) { max = totalNodes; }
// Create array big enough for every minipool
address[] memory nodes = new address[](max.sub(_offset));
uint256 total = 0;
for (uint256 i = _offset; i < max; i++) {
nodes[total] = addressSetStorage.getItem(nodeKey, i);
total++;
}
// Dirty hack to cut unused elements off end of return value
assembly {
mstore(nodes, total)
}
return nodes;
}
}
| 21,702 |
118 | // Address receives the funds collected from the sale. | address public fundsReceiver;
| address public fundsReceiver;
| 32,327 |
55 | // increase totaltokens | _totalTokens = _totalTokens.add(_89percent);
| _totalTokens = _totalTokens.add(_89percent);
| 16,718 |
12 | // HARDCODED FOR COORDINATOR: 0x7a1bac17ccc5b313516c5e16fb24f7659aa5ebed / | constructor(
uint64 subscriptionId
)
VRFConsumerBaseV2(vrfCoordinator)
ConfirmedOwner(msg.sender)
| constructor(
uint64 subscriptionId
)
VRFConsumerBaseV2(vrfCoordinator)
ConfirmedOwner(msg.sender)
| 20,099 |
44 | // solium-disable security/no-block-members // TokenVesting A token holder contract that can release its token balance gradually like atypical vesting scheme, with a cliff and vesting period. Optionally revocable by theowner. / | contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
)
public
{
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param _token ERC20 token which is being vested
*/
function release(ERC20 _token) public {
uint256 unreleased = releasableAmount(_token);
require(unreleased > 0);
released[_token] = released[_token].add(unreleased);
_token.safeTransfer(beneficiary, unreleased);
emit Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param _token ERC20 token which is being vested
*/
function revoke(ERC20 _token) public onlyOwner {
require(revocable);
require(!revoked[_token]);
uint256 balance = _token.balanceOf(address(this));
uint256 unreleased = releasableAmount(_token);
uint256 refund = balance.sub(unreleased);
revoked[_token] = true;
_token.safeTransfer(owner, refund);
emit Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param _token ERC20 token which is being vested
*/
function releasableAmount(ERC20 _token) public view returns (uint256) {
return vestedAmount(_token).sub(released[_token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param _token ERC20 token which is being vested
*/
function vestedAmount(ERC20 _token) public view returns (uint256) {
uint256 currentBalance = _token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[_token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[_token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
} | contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
)
public
{
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param _token ERC20 token which is being vested
*/
function release(ERC20 _token) public {
uint256 unreleased = releasableAmount(_token);
require(unreleased > 0);
released[_token] = released[_token].add(unreleased);
_token.safeTransfer(beneficiary, unreleased);
emit Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param _token ERC20 token which is being vested
*/
function revoke(ERC20 _token) public onlyOwner {
require(revocable);
require(!revoked[_token]);
uint256 balance = _token.balanceOf(address(this));
uint256 unreleased = releasableAmount(_token);
uint256 refund = balance.sub(unreleased);
revoked[_token] = true;
_token.safeTransfer(owner, refund);
emit Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param _token ERC20 token which is being vested
*/
function releasableAmount(ERC20 _token) public view returns (uint256) {
return vestedAmount(_token).sub(released[_token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param _token ERC20 token which is being vested
*/
function vestedAmount(ERC20 _token) public view returns (uint256) {
uint256 currentBalance = _token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[_token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[_token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
} | 17,693 |
203 | // Sets base URI for all tokens, only able to be called by contract owner | function setBaseURI(string memory baseURI_) external onlyOwner {
_baseURIExtended = baseURI_;
}
| function setBaseURI(string memory baseURI_) external onlyOwner {
_baseURIExtended = baseURI_;
}
| 3,965 |
20 | // HumanityApplicant Convenient interface for applying to the Humanity registry. / | contract HumanityApplicant {
using SafeMath for uint;
IGovernance public governance;
IRegistry public registry;
IERC20 public humanity;
constructor(IGovernance _governance, IRegistry _registry, IERC20 _humanity) public {
governance = _governance;
registry = _registry;
humanity = _humanity;
humanity.approve(address(governance), uint(-1));
}
function applyFor(address who) public returns (uint) {
uint fee = governance.proposalFee();
uint balance = humanity.balanceOf(address(this));
if (fee > balance) {
require(humanity.transferFrom(msg.sender, address(this), fee.sub(balance)), "HumanityApplicant::applyFor: Transfer failed");
}
bytes memory data = abi.encodeWithSelector(registry.add.selector, who);
return governance.proposeWithFeeRecipient(msg.sender, address(registry), data);
}
}
| contract HumanityApplicant {
using SafeMath for uint;
IGovernance public governance;
IRegistry public registry;
IERC20 public humanity;
constructor(IGovernance _governance, IRegistry _registry, IERC20 _humanity) public {
governance = _governance;
registry = _registry;
humanity = _humanity;
humanity.approve(address(governance), uint(-1));
}
function applyFor(address who) public returns (uint) {
uint fee = governance.proposalFee();
uint balance = humanity.balanceOf(address(this));
if (fee > balance) {
require(humanity.transferFrom(msg.sender, address(this), fee.sub(balance)), "HumanityApplicant::applyFor: Transfer failed");
}
bytes memory data = abi.encodeWithSelector(registry.add.selector, who);
return governance.proposeWithFeeRecipient(msg.sender, address(registry), data);
}
}
| 10,967 |
594 | // Calculate rewards by ((delegateStakeToSP / totalActiveFunds)totalRewards) | uint256 rewardsPriorToSPCut = (
delegateStakeToSP.mul(_totalRewards)
).div(_totalActiveFunds);
| uint256 rewardsPriorToSPCut = (
delegateStakeToSP.mul(_totalRewards)
).div(_totalActiveFunds);
| 38,619 |
34 | // he can withdraw whatever is available at the contract, up to his balance | return balance >= _amount ? _amount : balance;
| return balance >= _amount ? _amount : balance;
| 16,503 |
102 | // populate the string starting with the least-significant character | j = input;
for (uint256 i = length; i > 0; ) {
| j = input;
for (uint256 i = length; i > 0; ) {
| 3,002 |
207 | // supposed to be called once while initializing. one of the contracts that inherits this contract follows proxy pattern so it is not possible to do this in a constructor | function _initializeEIP712(
string memory name
)
internal
initializer
| function _initializeEIP712(
string memory name
)
internal
initializer
| 4,176 |
190 | // Specify the time that a particular person's lock will be released |
function setReleaseTime(address _holder, uint256 _release_time)
public
onlyOwner
returns (bool)
|
function setReleaseTime(address _holder, uint256 _release_time)
public
onlyOwner
returns (bool)
| 45,183 |
126 | // Changes the contract allowed to freeze before depositing/newDepositor - address of the new depositor contract | function updateDepositor(address newDepositor)
external
onlyAdmin
notToZeroAddress(newDepositor)
| function updateDepositor(address newDepositor)
external
onlyAdmin
notToZeroAddress(newDepositor)
| 79,235 |
0 | // 儘管array被宣告為public,從測試案例讀取array需要建立函數 | function get() public view returns(uint[]) {return data;}
function set(uint[] _data) public { data = _data; }
function sort() public {
if (data.length == 0)
return;
quickSort(data, 0, data.length - 1);
}
| function get() public view returns(uint[]) {return data;}
function set(uint[] _data) public { data = _data; }
function sort() public {
if (data.length == 0)
return;
quickSort(data, 0, data.length - 1);
}
| 11,035 |
396 | // Ensure price is acceptable to buyer | if (maxPrice < price) revert NoLossCollateralAuction__takeCollateral_tooExpensive();
| if (maxPrice < price) revert NoLossCollateralAuction__takeCollateral_tooExpensive();
| 46,402 |
29 | // uniExchange.call.value(amount)(abi.encodeWithSignature("ethToTokenSwapInput(uint256,uint256)", min, 999999999999999999999)); | Uniswap(uniExchange).ethToTokenSwapInput.value(amount)(min, 999999999999999999999);
| Uniswap(uniExchange).ethToTokenSwapInput.value(amount)(min, 999999999999999999999);
| 6,125 |
171 | // Governance //Sets a new transfer rate for the Orbs pool. | function setMaxAnnualRate(uint256 annual_rate) external; /* onlyMigrationManager */
| function setMaxAnnualRate(uint256 annual_rate) external; /* onlyMigrationManager */
| 36,726 |
85 | // Returns a boolean flag indicating if the `initialize` function has been called. | function isInitialized() public view returns(bool) {
return validatorSetContract != IValidatorSetAuRa(0);
}
| function isInitialized() public view returns(bool) {
return validatorSetContract != IValidatorSetAuRa(0);
}
| 22,659 |
10 | // Getter function for debt token addressreturn debt token price / | function getDebtTokenAddress() public view returns (address) {
return debt.tokenAddress;
}
| function getDebtTokenAddress() public view returns (address) {
return debt.tokenAddress;
}
| 41,110 |
43 | // reward rate 520.00% per year | uint public constant rewardRate = 52000;
uint public constant rewardInterval = 365 days; // 10% per week
| uint public constant rewardRate = 52000;
uint public constant rewardInterval = 365 days; // 10% per week
| 31,950 |
40 | // 4 - calculated Payout | uint calculatedPayout;
| uint calculatedPayout;
| 30,308 |
9 | // Flag to enable total amount of lp that can be staked by all users | bool public enablePoolLpLimit;
| bool public enablePoolLpLimit;
| 35,291 |
Subsets and Splits