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
|
|---|---|---|---|---|
19
|
// claim & deduct mint rewards for an address /
|
function _claimAllMintRewards(address tokenOwner) internal {
uint[] memory _tokens = _tokensByOwner(tokenOwner);
require(_tokens.length > 0, "Tokens not found in wallet");
uint _allEarned;
uint _tEarned;
for (uint i = 0; i < _tokens.length; i++) {
_tEarned = _totalDividend - _claimedDividends[_tokens[i]];
if (_tEarned > 0) {
_allEarned += _tEarned;
_claimedDividends[_tokens[i]] += _tEarned;
}
}
require(_allEarned > 0, "Insufficient balance");
_balanceReflections -= _allEarned;
payable(_msgSender()).transfer(_allEarned);
emit MintRewardsClaimed(_allEarned, _balanceReflections);
}
|
function _claimAllMintRewards(address tokenOwner) internal {
uint[] memory _tokens = _tokensByOwner(tokenOwner);
require(_tokens.length > 0, "Tokens not found in wallet");
uint _allEarned;
uint _tEarned;
for (uint i = 0; i < _tokens.length; i++) {
_tEarned = _totalDividend - _claimedDividends[_tokens[i]];
if (_tEarned > 0) {
_allEarned += _tEarned;
_claimedDividends[_tokens[i]] += _tEarned;
}
}
require(_allEarned > 0, "Insufficient balance");
_balanceReflections -= _allEarned;
payable(_msgSender()).transfer(_allEarned);
emit MintRewardsClaimed(_allEarned, _balanceReflections);
}
| 4,998
|
17
|
// chi.mint needs tokens as a unit
|
chi.mint(chi_fee / 10**18);
chi.transfer(beneficiary, chi.balanceOf(address(this)));
|
chi.mint(chi_fee / 10**18);
chi.transfer(beneficiary, chi.balanceOf(address(this)));
| 4,844
|
233
|
// Return the final result.
|
return realResult;
|
return realResult;
| 9,306
|
35
|
// (market => base unit) The base unit (1 of) for this market underlying
|
mapping(address => uint) public baseUnits;
|
mapping(address => uint) public baseUnits;
| 25,717
|
17
|
// Initiliazes the contract, like a constructor.
|
function initialize(
address _defaultAdmin,
string memory _name,
string memory _symbol,
string memory _contractURI,
address[] memory _trustedForwarders,
address _saleRecipient,
address _royaltyRecipient,
uint128 _royaltyBps,
uint128 _platformFeeBps,
|
function initialize(
address _defaultAdmin,
string memory _name,
string memory _symbol,
string memory _contractURI,
address[] memory _trustedForwarders,
address _saleRecipient,
address _royaltyRecipient,
uint128 _royaltyBps,
uint128 _platformFeeBps,
| 48,829
|
188
|
// mint anumber of NFTs in presale
|
function presaleMint(uint256 number, uint8 _v, bytes32 _r, bytes32 _s) onlyValidAccess(_v, _r, _s) public payable {
State saleState_ = saleState();
require(saleState_ != State.NoSale, "Sale in not open yet!");
require(saleState_ == State.Presale, "Presale has finished!");
require(totalSupply() + number <= maxTotalTokens, "Not enough NFTs left to mint..");
require(mintsPerAddress[msg.sender] + number <= maxMintPresale, "Maximum 2 Mints per Address allowed!");
require(msg.value >= mintCost() * number, "Not sufficient Ether to mint this amount of NFTs (Cost = 0.04 ether each NFT)");
for (uint256 i = 0; i < number; i++) {
uint256 tid = tokenId();
_safeMint(msg.sender, tid);
mintsPerAddress[msg.sender] += 1;
}
}
|
function presaleMint(uint256 number, uint8 _v, bytes32 _r, bytes32 _s) onlyValidAccess(_v, _r, _s) public payable {
State saleState_ = saleState();
require(saleState_ != State.NoSale, "Sale in not open yet!");
require(saleState_ == State.Presale, "Presale has finished!");
require(totalSupply() + number <= maxTotalTokens, "Not enough NFTs left to mint..");
require(mintsPerAddress[msg.sender] + number <= maxMintPresale, "Maximum 2 Mints per Address allowed!");
require(msg.value >= mintCost() * number, "Not sufficient Ether to mint this amount of NFTs (Cost = 0.04 ether each NFT)");
for (uint256 i = 0; i < number; i++) {
uint256 tid = tokenId();
_safeMint(msg.sender, tid);
mintsPerAddress[msg.sender] += 1;
}
}
| 8,177
|
1
|
// Spend tokens on user's behalf. Only an authority can call this./ from The user to spend token from./ token The address of the token./ to The recipient of the trasnfer./ amount Amount to spend.
|
function spendFromUserTo(
address from,
address token,
address to,
uint256 amount
) external;
|
function spendFromUserTo(
address from,
address token,
address to,
uint256 amount
) external;
| 24,817
|
17
|
// Begin solidity-cborutilsMIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
library Buffer {
struct buffer {
bytes buf;
uint256 capacity;
}
function init(buffer memory _buf, uint256 _capacity) internal pure {
uint256 capacity = _capacity;
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
_buf.capacity = capacity; // Allocate space for the buffer data
assembly {
let ptr := mload(0x40)
mstore(_buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory _buf, uint256 _capacity) private pure {
bytes memory oldbuf = _buf.buf;
init(_buf, _capacity);
append(_buf, oldbuf);
}
function max(uint256 _a, uint256 _b) private pure returns (uint256 _max) {
if (_a > _b) {
return _a;
}
return _b;
}
/**
* @dev Appends a byte array to the end of the buffer. Resizes if doing so
* would exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return The original buffer.
*
*/
function append(
buffer memory _buf,
bytes memory _data
)
internal
pure
returns (buffer memory _buffer)
{
if (_data.length + _buf.buf.length > _buf.capacity) {
resize(_buf, max(_buf.capacity, _data.length) * 2);
}
uint256 dest;
uint256 src;
uint256 len = _data.length;
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length)
mstore(bufptr, add(buflen, mload(_data))) // Update buffer length
src := add(_data, 32)
}
for(; len >= 32; len -= 32) { // Copy word-length chunks while possible
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask = 256 ** (32 - len) - 1; // Copy remaining bytes
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return _buf;
}
/**
*
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return The original buffer.
*
*/
function append(buffer memory _buf, uint8 _data) internal pure {
if (_buf.buf.length + 1 > _buf.capacity) {
resize(_buf, _buf.capacity * 2);
}
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length)
mstore8(dest, _data)
mstore(bufptr, add(buflen, 1)) // Update buffer length
}
}
/**
*
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return The original buffer.
*
*/
function appendInt(
buffer memory _buf,
uint256 _data,
uint256 _len
)
internal
pure
returns (buffer memory _buffer)
{
if (_len + _buf.buf.length > _buf.capacity) {
resize(_buf, max(_buf.capacity, _len) * 2);
}
uint256 mask = 256 ** _len - 1;
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
let dest := add(add(bufptr, buflen), _len) // Address = buffer address + buffer length + sizeof(buffer length) + len
mstore(dest, or(and(mload(dest), not(mask)), _data))
mstore(bufptr, add(buflen, _len)) // Update buffer length
}
return _buf;
}
}
|
library Buffer {
struct buffer {
bytes buf;
uint256 capacity;
}
function init(buffer memory _buf, uint256 _capacity) internal pure {
uint256 capacity = _capacity;
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
_buf.capacity = capacity; // Allocate space for the buffer data
assembly {
let ptr := mload(0x40)
mstore(_buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory _buf, uint256 _capacity) private pure {
bytes memory oldbuf = _buf.buf;
init(_buf, _capacity);
append(_buf, oldbuf);
}
function max(uint256 _a, uint256 _b) private pure returns (uint256 _max) {
if (_a > _b) {
return _a;
}
return _b;
}
/**
* @dev Appends a byte array to the end of the buffer. Resizes if doing so
* would exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return The original buffer.
*
*/
function append(
buffer memory _buf,
bytes memory _data
)
internal
pure
returns (buffer memory _buffer)
{
if (_data.length + _buf.buf.length > _buf.capacity) {
resize(_buf, max(_buf.capacity, _data.length) * 2);
}
uint256 dest;
uint256 src;
uint256 len = _data.length;
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length)
mstore(bufptr, add(buflen, mload(_data))) // Update buffer length
src := add(_data, 32)
}
for(; len >= 32; len -= 32) { // Copy word-length chunks while possible
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask = 256 ** (32 - len) - 1; // Copy remaining bytes
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return _buf;
}
/**
*
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return The original buffer.
*
*/
function append(buffer memory _buf, uint8 _data) internal pure {
if (_buf.buf.length + 1 > _buf.capacity) {
resize(_buf, _buf.capacity * 2);
}
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length)
mstore8(dest, _data)
mstore(bufptr, add(buflen, 1)) // Update buffer length
}
}
/**
*
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return The original buffer.
*
*/
function appendInt(
buffer memory _buf,
uint256 _data,
uint256 _len
)
internal
pure
returns (buffer memory _buffer)
{
if (_len + _buf.buf.length > _buf.capacity) {
resize(_buf, max(_buf.capacity, _len) * 2);
}
uint256 mask = 256 ** _len - 1;
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
let dest := add(add(bufptr, buflen), _len) // Address = buffer address + buffer length + sizeof(buffer length) + len
mstore(dest, or(and(mload(dest), not(mask)), _data))
mstore(bufptr, add(buflen, _len)) // Update buffer length
}
return _buf;
}
}
| 38,719
|
202
|
// Store the list of tokens in the pool, and balances NOTE that the token list is only used to store the pool tokens between construction and createPool - thereafter, use the underlying BPool's list (avoids synchronization issues)
|
address[] private _initialTokens;
uint[] private _initialBalances;
|
address[] private _initialTokens;
uint[] private _initialBalances;
| 33,577
|
37
|
// the public function for checking if more tokens can be minted
|
function maxSupplyNotExceeded(uint32 amount) public view returns (bool) {
require(
_tokenIdTracker.current()+(amount-(1)) <= _maxTokenId,
"NX7NFT: max NFT limit exceeded"
);
return true;
}
|
function maxSupplyNotExceeded(uint32 amount) public view returns (bool) {
require(
_tokenIdTracker.current()+(amount-(1)) <= _maxTokenId,
"NX7NFT: max NFT limit exceeded"
);
return true;
}
| 9,524
|
113
|
// Actions userInfo[msg.sender].rewardDebt = userInfo[msg.sender].rewardDebt.add(_amount); userInfo[msg.sender].lastBlock = _currentBlockNumber; if (_amount > 0) { milk.mint(msg.sender, _amount); } emit Harvest(msg.sender, _amount, _currentBlockNumber);
|
return (signedBy, actualMsg, actualMsg.toEthSignedMessageHash());
|
return (signedBy, actualMsg, actualMsg.toEthSignedMessageHash());
| 12,919
|
8
|
// Set the token. Must only be called after the IICO contract receives the tokens to be sold._token The token to be sold. /
|
function setToken(ERC20 _token) public onlyOwner {
require(address(token) == address(0)); // Make sure the token is not already set.
token = _token;
tokensForSale = token.balanceOf(this);
}
|
function setToken(ERC20 _token) public onlyOwner {
require(address(token) == address(0)); // Make sure the token is not already set.
token = _token;
tokensForSale = token.balanceOf(this);
}
| 25,724
|
7
|
// Mint state flag
|
bool private _isMintEnabled;
|
bool private _isMintEnabled;
| 20,815
|
23
|
// input added/epochNumber which epoch this input belongs to/inputIndex index of the input just added/sender msg.sender/timestamp block.timestamp/input input data
|
event InputAdded(
uint256 indexed epochNumber,
uint256 indexed inputIndex,
address sender,
uint256 timestamp,
bytes input
);
|
event InputAdded(
uint256 indexed epochNumber,
uint256 indexed inputIndex,
address sender,
uint256 timestamp,
bytes input
);
| 10,343
|
159
|
// This function can set the server side address/_signerAddress The address derived from server's private key
|
function setSignerAddress(address _signerAddress) external onlyOwner {
// EC rcover returns 0 in case of error therefore, this CANNOT be 0.
require(_signerAddress != 0);
signerAddress = _signerAddress;
SignerChanged(signerAddress);
}
|
function setSignerAddress(address _signerAddress) external onlyOwner {
// EC rcover returns 0 in case of error therefore, this CANNOT be 0.
require(_signerAddress != 0);
signerAddress = _signerAddress;
SignerChanged(signerAddress);
}
| 42,162
|
99
|
// console.log("reserve0,reserve1",reserve0,reserve1);
|
uint256 c = sqrt(uint256(reserve0).div(1e14))*sqrt(uint256(reserve1).div(1e2)).mul(1e14);
return c.sub(uint256(reserve0));
|
uint256 c = sqrt(uint256(reserve0).div(1e14))*sqrt(uint256(reserve1).div(1e2)).mul(1e14);
return c.sub(uint256(reserve0));
| 8,245
|
75
|
// Inflation rate reaches 10%. Decrease inflation rate by 0.5% from here on out until it reaches 1%.
|
else if (inflationRate > 10) {
inflationRate = inflationRate.sub(5);
}
|
else if (inflationRate > 10) {
inflationRate = inflationRate.sub(5);
}
| 37,324
|
98
|
// dev can never set sells below 0.1% of circulating/initial supply
|
require((newMaxWallet >= minLimit && newMaxSell >= minLimit),
"limits cannot be <0.1% of supply");
_limits = MaxLimits(newMaxWallet, newMaxSell, newMaxBuy);
_limitRatios = LimitRatios(newMaxWalletRatio, newMaxSellRatio, newMaxBuyRatio, newDivisor);
|
require((newMaxWallet >= minLimit && newMaxSell >= minLimit),
"limits cannot be <0.1% of supply");
_limits = MaxLimits(newMaxWallet, newMaxSell, newMaxBuy);
_limitRatios = LimitRatios(newMaxWalletRatio, newMaxSellRatio, newMaxBuyRatio, newDivisor);
| 18,651
|
34
|
// Increases the balance of the address._owner Address to increase the balance of._value Value to increase./
|
function increaseBalance(address _owner, uint256 _value) public onlyOwner {
balances[_owner] = balances[_owner].add(_value);
}
|
function increaseBalance(address _owner, uint256 _value) public onlyOwner {
balances[_owner] = balances[_owner].add(_value);
}
| 50,568
|
145
|
// `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point one. Recall that fixed point multiplication requires dividing by ONE_20.
|
int256 product = ONE_20;
if (x >= x2) {
x -= x2;
product = (product * a2) / ONE_20;
}
|
int256 product = ONE_20;
if (x >= x2) {
x -= x2;
product = (product * a2) / ONE_20;
}
| 2,052
|
48
|
// ====== INTERNAL FUNCTIONS ====== // /
|
function adjust(uint256 _index) internal {
Adjust memory adjustment = adjustments[_index];
if (adjustment.rate != 0) {
if (adjustment.add) {
// if rate should increase
info[_index].rate = info[_index].rate.add(adjustment.rate); // raise rate
if (info[_index].rate >= adjustment.target) {
// if target met
adjustments[_index].rate = 0; // turn off adjustment
info[_index].rate = adjustment.target; // set to target
}
} else {
// if rate should decrease
if (info[_index].rate > adjustment.rate) { // protect from underflow
info[_index].rate = info[_index].rate.sub(adjustment.rate); // lower rate
} else {
info[_index].rate = 0;
}
if (info[_index].rate <= adjustment.target) {
// if target met
adjustments[_index].rate = 0; // turn off adjustment
info[_index].rate = adjustment.target; // set to target
}
}
}
}
|
function adjust(uint256 _index) internal {
Adjust memory adjustment = adjustments[_index];
if (adjustment.rate != 0) {
if (adjustment.add) {
// if rate should increase
info[_index].rate = info[_index].rate.add(adjustment.rate); // raise rate
if (info[_index].rate >= adjustment.target) {
// if target met
adjustments[_index].rate = 0; // turn off adjustment
info[_index].rate = adjustment.target; // set to target
}
} else {
// if rate should decrease
if (info[_index].rate > adjustment.rate) { // protect from underflow
info[_index].rate = info[_index].rate.sub(adjustment.rate); // lower rate
} else {
info[_index].rate = 0;
}
if (info[_index].rate <= adjustment.target) {
// if target met
adjustments[_index].rate = 0; // turn off adjustment
info[_index].rate = adjustment.target; // set to target
}
}
}
}
| 33,144
|
159
|
// Onesplit params
|
uint256 expected;
uint256[] memory distribution;
IERC20(_from).safeApprove(onesplit, 0);
IERC20(_from).safeApprove(onesplit, _amount);
(expected, distribution) = OneSplitAudit(onesplit).getExpectedReturn(
_from,
_to,
_amount,
|
uint256 expected;
uint256[] memory distribution;
IERC20(_from).safeApprove(onesplit, 0);
IERC20(_from).safeApprove(onesplit, _amount);
(expected, distribution) = OneSplitAudit(onesplit).getExpectedReturn(
_from,
_to,
_amount,
| 24,167
|
32
|
// Royal NFTSupports EIP-2981 royalties on NFT secondary salesSupports OpenSea contract metadata royaltiesIntroduces "owner" to support OpenSea collections /
|
abstract contract RoyalNFT is EIP2981, TinyERC721 {
/**
* @dev OpenSea expects NFTs to be "Ownable", that is having an "owner",
* we introduce a fake "owner" here with no authority
*/
address public owner;
/**
* @dev Constructs/deploys ERC721 with EIP-2981 instance with the name and symbol specified
*
* @param _name name of the token to be accessible as `name()`,
* ERC-20 compatible descriptive name for a collection of NFTs in this contract
* @param _symbol token symbol to be accessible as `symbol()`,
* ERC-20 compatible descriptive name for a collection of NFTs in this contract
*/
constructor(string memory _name, string memory _symbol) TinyERC721(_name, _symbol) {
// initialize the "owner" as a deployer account
owner = msg.sender;
}
/**
* @dev Fired in setContractURI()
*
* @param _by an address which executed update
* @param _oldVal old contractURI value
* @param _newVal new contractURI value
*/
event ContractURIUpdated(address indexed _by, string _oldVal, string _newVal);
/**
* @dev Fired in setRoyaltyInfo()
*
* @param _by an address which executed update
* @param _oldReceiver old royaltyReceiver value
* @param _newReceiver new royaltyReceiver value
* @param _oldPercentage old royaltyPercentage value
* @param _newPercentage new royaltyPercentage value
*/
event RoyaltyInfoUpdated(
address indexed _by,
address indexed _oldReceiver,
address indexed _newReceiver,
uint16 _oldPercentage,
uint16 _newPercentage
);
/**
* @dev Fired in setOwner()
*
* @param _by an address which set the new "owner"
* @param _oldVal previous "owner" address
* @param _newVal new "owner" address
*/
event OwnerUpdated(address indexed _by, address indexed _oldVal, address indexed _newVal);
/**
* @notice Royalty manager is responsible for managing the EIP2981 royalty info
*
* @dev Role ROLE_ROYALTY_MANAGER allows updating the royalty information
* (executing `setRoyaltyInfo` function)
*/
uint32 public constant ROLE_ROYALTY_MANAGER = 0x0020_0000;
/**
* @notice Owner manager is responsible for setting/updating an "owner" field
*
* @dev Role ROLE_OWNER_MANAGER allows updating the "owner" field
* (executing `setOwner` function)
*/
uint32 public constant ROLE_OWNER_MANAGER = 0x0040_0000;
/**
* @notice Address to receive EIP-2981 royalties from secondary sales
* see https://eips.ethereum.org/EIPS/eip-2981
*/
address public royaltyReceiver = address(0x379e2119f6e0D6088537da82968e2a7ea178dDcF);
/**
* @notice Percentage of token sale price to be used for EIP-2981 royalties from secondary sales
* see https://eips.ethereum.org/EIPS/eip-2981
*
* @dev Has 2 decimal precision. E.g. a value of 500 would result in a 5% royalty fee
*/
uint16 public royaltyPercentage = 750;
/**
* @notice Contract level metadata to define collection name, description, and royalty fees.
* see https://docs.opensea.io/docs/contract-level-metadata
*
* @dev Should be overwritten by inheriting contracts. By default only includes royalty information
*/
string public contractURI = "https://gateway.pinata.cloud/ipfs/QmU92w8iKpcaabCoyHtMg7iivWGqW2gW1hgARDtqCmJUWv";
/**
* @dev Restricted access function which updates the contract uri
*
* @dev Requires executor to have ROLE_URI_MANAGER permission
*
* @param _contractURI new contract URI to set
*/
function setContractURI(string memory _contractURI) public {
// verify the access permission
require(isSenderInRole(ROLE_URI_MANAGER), "access denied");
// emit an event first - to log both old and new values
emit ContractURIUpdated(msg.sender, contractURI, _contractURI);
// update the contract URI
contractURI = _contractURI;
}
/**
* @notice EIP-2981 function to calculate royalties for sales in secondary marketplaces.
* see https://eips.ethereum.org/EIPS/eip-2981
*
* @param _tokenId the token id to calculate royalty info for
* @param _salePrice the price (in any unit, .e.g wei, ERC20 token, et.c.) of the token to be sold
*
* @return receiver the royalty receiver
* @return royaltyAmount royalty amount in the same unit as _salePrice
*/
function royaltyInfo(
uint256 _tokenId,
uint256 _salePrice
) external view override returns (
address receiver,
uint256 royaltyAmount
) {
// simply calculate the values and return the result
return (royaltyReceiver, _salePrice * royaltyPercentage / 100_00);
}
/**
* @dev Restricted access function which updates the royalty info
*
* @dev Requires executor to have ROLE_ROYALTY_MANAGER permission
*
* @param _royaltyReceiver new royalty receiver to set
* @param _royaltyPercentage new royalty percentage to set
*/
function setRoyaltyInfo(
address _royaltyReceiver,
uint16 _royaltyPercentage
) public {
// verify the access permission
require(isSenderInRole(ROLE_ROYALTY_MANAGER), "access denied");
// verify royalty percentage is zero if receiver is also zero
require(_royaltyReceiver != address(0) || _royaltyPercentage == 0, "invalid receiver");
// emit an event first - to log both old and new values
emit RoyaltyInfoUpdated(
msg.sender,
royaltyReceiver,
_royaltyReceiver,
royaltyPercentage,
_royaltyPercentage
);
// update the values
royaltyReceiver = _royaltyReceiver;
royaltyPercentage = _royaltyPercentage;
}
/**
* @notice Checks if the address supplied is an "owner" of the smart contract
* Note: an "owner" doesn't have any authority on the smart contract and is "nominal"
*
* @return true if the caller is the current owner.
*/
function isOwner(address _addr) public view returns(bool) {
// just evaluate and return the result
return _addr == owner;
}
/**
* @dev Restricted access function to set smart contract "owner"
* Note: an "owner" set doesn't have any authority, and cannot even update "owner"
*
* @dev Requires executor to have ROLE_OWNER_MANAGER permission
*
* @param _owner new "owner" of the smart contract
*/
function transferOwnership(address _owner) public {
// verify the access permission
require(isSenderInRole(ROLE_OWNER_MANAGER), "access denied");
// emit an event first - to log both old and new values
emit OwnerUpdated(msg.sender, owner, _owner);
// update "owner"
owner = _owner;
}
/**
* @inheritdoc ERC165
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, TinyERC721) returns (bool) {
// construct the interface support from EIP-2981 and super interfaces
return interfaceId == type(EIP2981).interfaceId || super.supportsInterface(interfaceId);
}
}
|
abstract contract RoyalNFT is EIP2981, TinyERC721 {
/**
* @dev OpenSea expects NFTs to be "Ownable", that is having an "owner",
* we introduce a fake "owner" here with no authority
*/
address public owner;
/**
* @dev Constructs/deploys ERC721 with EIP-2981 instance with the name and symbol specified
*
* @param _name name of the token to be accessible as `name()`,
* ERC-20 compatible descriptive name for a collection of NFTs in this contract
* @param _symbol token symbol to be accessible as `symbol()`,
* ERC-20 compatible descriptive name for a collection of NFTs in this contract
*/
constructor(string memory _name, string memory _symbol) TinyERC721(_name, _symbol) {
// initialize the "owner" as a deployer account
owner = msg.sender;
}
/**
* @dev Fired in setContractURI()
*
* @param _by an address which executed update
* @param _oldVal old contractURI value
* @param _newVal new contractURI value
*/
event ContractURIUpdated(address indexed _by, string _oldVal, string _newVal);
/**
* @dev Fired in setRoyaltyInfo()
*
* @param _by an address which executed update
* @param _oldReceiver old royaltyReceiver value
* @param _newReceiver new royaltyReceiver value
* @param _oldPercentage old royaltyPercentage value
* @param _newPercentage new royaltyPercentage value
*/
event RoyaltyInfoUpdated(
address indexed _by,
address indexed _oldReceiver,
address indexed _newReceiver,
uint16 _oldPercentage,
uint16 _newPercentage
);
/**
* @dev Fired in setOwner()
*
* @param _by an address which set the new "owner"
* @param _oldVal previous "owner" address
* @param _newVal new "owner" address
*/
event OwnerUpdated(address indexed _by, address indexed _oldVal, address indexed _newVal);
/**
* @notice Royalty manager is responsible for managing the EIP2981 royalty info
*
* @dev Role ROLE_ROYALTY_MANAGER allows updating the royalty information
* (executing `setRoyaltyInfo` function)
*/
uint32 public constant ROLE_ROYALTY_MANAGER = 0x0020_0000;
/**
* @notice Owner manager is responsible for setting/updating an "owner" field
*
* @dev Role ROLE_OWNER_MANAGER allows updating the "owner" field
* (executing `setOwner` function)
*/
uint32 public constant ROLE_OWNER_MANAGER = 0x0040_0000;
/**
* @notice Address to receive EIP-2981 royalties from secondary sales
* see https://eips.ethereum.org/EIPS/eip-2981
*/
address public royaltyReceiver = address(0x379e2119f6e0D6088537da82968e2a7ea178dDcF);
/**
* @notice Percentage of token sale price to be used for EIP-2981 royalties from secondary sales
* see https://eips.ethereum.org/EIPS/eip-2981
*
* @dev Has 2 decimal precision. E.g. a value of 500 would result in a 5% royalty fee
*/
uint16 public royaltyPercentage = 750;
/**
* @notice Contract level metadata to define collection name, description, and royalty fees.
* see https://docs.opensea.io/docs/contract-level-metadata
*
* @dev Should be overwritten by inheriting contracts. By default only includes royalty information
*/
string public contractURI = "https://gateway.pinata.cloud/ipfs/QmU92w8iKpcaabCoyHtMg7iivWGqW2gW1hgARDtqCmJUWv";
/**
* @dev Restricted access function which updates the contract uri
*
* @dev Requires executor to have ROLE_URI_MANAGER permission
*
* @param _contractURI new contract URI to set
*/
function setContractURI(string memory _contractURI) public {
// verify the access permission
require(isSenderInRole(ROLE_URI_MANAGER), "access denied");
// emit an event first - to log both old and new values
emit ContractURIUpdated(msg.sender, contractURI, _contractURI);
// update the contract URI
contractURI = _contractURI;
}
/**
* @notice EIP-2981 function to calculate royalties for sales in secondary marketplaces.
* see https://eips.ethereum.org/EIPS/eip-2981
*
* @param _tokenId the token id to calculate royalty info for
* @param _salePrice the price (in any unit, .e.g wei, ERC20 token, et.c.) of the token to be sold
*
* @return receiver the royalty receiver
* @return royaltyAmount royalty amount in the same unit as _salePrice
*/
function royaltyInfo(
uint256 _tokenId,
uint256 _salePrice
) external view override returns (
address receiver,
uint256 royaltyAmount
) {
// simply calculate the values and return the result
return (royaltyReceiver, _salePrice * royaltyPercentage / 100_00);
}
/**
* @dev Restricted access function which updates the royalty info
*
* @dev Requires executor to have ROLE_ROYALTY_MANAGER permission
*
* @param _royaltyReceiver new royalty receiver to set
* @param _royaltyPercentage new royalty percentage to set
*/
function setRoyaltyInfo(
address _royaltyReceiver,
uint16 _royaltyPercentage
) public {
// verify the access permission
require(isSenderInRole(ROLE_ROYALTY_MANAGER), "access denied");
// verify royalty percentage is zero if receiver is also zero
require(_royaltyReceiver != address(0) || _royaltyPercentage == 0, "invalid receiver");
// emit an event first - to log both old and new values
emit RoyaltyInfoUpdated(
msg.sender,
royaltyReceiver,
_royaltyReceiver,
royaltyPercentage,
_royaltyPercentage
);
// update the values
royaltyReceiver = _royaltyReceiver;
royaltyPercentage = _royaltyPercentage;
}
/**
* @notice Checks if the address supplied is an "owner" of the smart contract
* Note: an "owner" doesn't have any authority on the smart contract and is "nominal"
*
* @return true if the caller is the current owner.
*/
function isOwner(address _addr) public view returns(bool) {
// just evaluate and return the result
return _addr == owner;
}
/**
* @dev Restricted access function to set smart contract "owner"
* Note: an "owner" set doesn't have any authority, and cannot even update "owner"
*
* @dev Requires executor to have ROLE_OWNER_MANAGER permission
*
* @param _owner new "owner" of the smart contract
*/
function transferOwnership(address _owner) public {
// verify the access permission
require(isSenderInRole(ROLE_OWNER_MANAGER), "access denied");
// emit an event first - to log both old and new values
emit OwnerUpdated(msg.sender, owner, _owner);
// update "owner"
owner = _owner;
}
/**
* @inheritdoc ERC165
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, TinyERC721) returns (bool) {
// construct the interface support from EIP-2981 and super interfaces
return interfaceId == type(EIP2981).interfaceId || super.supportsInterface(interfaceId);
}
}
| 9,638
|
94
|
// get the required fee for the released ETH bonus -------------------------------------------------------------------------------param _user --> the address of the user----------------------------------------------------------returns the fee amount. /
|
function calculateETHBonusFee(address _user) external view returns(uint ETH_Fee) {
uint wethReleased = _calculateETHReleasedAmount(_user);
if (wethReleased > 0) {
(uint feeForWethInUtoken,) = _calculateETHFee(wethReleased);
return feeForWethInUtoken;
} else return 0;
}
|
function calculateETHBonusFee(address _user) external view returns(uint ETH_Fee) {
uint wethReleased = _calculateETHReleasedAmount(_user);
if (wethReleased > 0) {
(uint feeForWethInUtoken,) = _calculateETHFee(wethReleased);
return feeForWethInUtoken;
} else return 0;
}
| 22,294
|
78
|
// Event for token purchase logging_purchaser Participant who paid for CHR tokens _value Amount in WEI paid for token _tokensAmount of tokens purchased /
|
event TokenPurchase(address indexed _purchaser, uint256 _value, uint256 _tokens);
|
event TokenPurchase(address indexed _purchaser, uint256 _value, uint256 _tokens);
| 9,327
|
39
|
// Derives the root role of the manager/manager Manager address/ return rootRole Root role
|
function _deriveRootRole(address manager)
internal
pure
returns (bytes32 rootRole)
|
function _deriveRootRole(address manager)
internal
pure
returns (bytes32 rootRole)
| 33,328
|
31
|
// Create a pangolin pair for this new token
|
pangolinPair = IPangolinFactory(_pangolinRouter.factory())
.createPair(address(this), _pangolinRouter.WAVAX());
|
pangolinPair = IPangolinFactory(_pangolinRouter.factory())
.createPair(address(this), _pangolinRouter.WAVAX());
| 1,503
|
27
|
// Atomically increases the allowance granted to `spender` by the caller.
|
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
* Emits an {Approval} event indicating the updated allowance.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
|
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
* Emits an {Approval} event indicating the updated allowance.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
| 12,302
|
269
|
// =================== mutative function =================== /
|
) external returns (address) {
require( owner != address(0), "you must set a address");
Collection collectionaddress = new Collection(_name,_symbol,_baseuri,owner);
collectionowner[address(collectionaddress)] = owner;
collections.push(address(collectionaddress));
emit createNFT( _name, _symbol, address(collectionaddress));
return address(collectionaddress);
}
|
) external returns (address) {
require( owner != address(0), "you must set a address");
Collection collectionaddress = new Collection(_name,_symbol,_baseuri,owner);
collectionowner[address(collectionaddress)] = owner;
collections.push(address(collectionaddress));
emit createNFT( _name, _symbol, address(collectionaddress));
return address(collectionaddress);
}
| 13,395
|
112
|
// AAVE
|
address dc=0x580D4Fdc4BF8f9b5ae2fb9225D584fED4AD5375c; // LendingPoolAddressesProvider
address execute_receiver = 0x18330752672D343876Ed47989B7efc9cB625dD79; // Can also be a separate contract 0x65fB1d0657cDC90F570dE8c6ea0E6Cf9CEc29b34
bytes params='';
address asset = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // kovan eth
uint256 aave_amount=10000000000000000; // kredit iz AavE
|
address dc=0x580D4Fdc4BF8f9b5ae2fb9225D584fED4AD5375c; // LendingPoolAddressesProvider
address execute_receiver = 0x18330752672D343876Ed47989B7efc9cB625dD79; // Can also be a separate contract 0x65fB1d0657cDC90F570dE8c6ea0E6Cf9CEc29b34
bytes params='';
address asset = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // kovan eth
uint256 aave_amount=10000000000000000; // kredit iz AavE
| 12,970
|
21
|
// F1 - F10: OK C1 - C24: OK All safeTransfer, _swap, _toUBE, _convertStep: X1 - X5: OK
|
function _convertStep(
address token0,
address token1,
uint256 amount0,
uint256 amount1
|
function _convertStep(
address token0,
address token1,
uint256 amount0,
uint256 amount1
| 30,044
|
25
|
// Get the current invariant
|
uint256 currentInvariant = _calculateInvariant(amp, balances, true);
|
uint256 currentInvariant = _calculateInvariant(amp, balances, true);
| 24,333
|
41
|
// if the user doesn't rent the full amount, create a new rental.
|
uint32 remainingAmount = rental.amount - _amountToRent;
if (remainingAmount > 0) {
|
uint32 remainingAmount = rental.amount - _amountToRent;
if (remainingAmount > 0) {
| 36,283
|
69
|
// Sets or unsets the approval of a given operatorAn operator is allowed to transfer all tokens of the sender on their behalf to operator address to set the approval approved representing the status of the approval to be set /
|
function setApprovalForAll(address to, bool approved) public {
require(to != msg.sender);
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
|
function setApprovalForAll(address to, bool approved) public {
require(to != msg.sender);
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
| 7,326
|
77
|
// Tracking total minted
|
uint256 internal _totalMinted;
|
uint256 internal _totalMinted;
| 41,778
|
51
|
// Attach a module/module a module to attach/enabled if the module is enabled by default/canModuleMint if the module has to be given the minter role
|
function attachModule(
address module,
bool enabled,
bool canModuleMint
) external;
|
function attachModule(
address module,
bool enabled,
bool canModuleMint
) external;
| 20,812
|
185
|
// If it is after expiry, we need to settle the short position using the normal way Delete the vault and withdraw all remaining collateral from the vault If it is before expiry, we need to burn otokens in order to withdraw collateral from the vault
|
if (settlementAllowed) {
actions = new IController.ActionArgs[](1);
actions[0] = IController.ActionArgs(
IController.ActionType.SettleVault,
address(this), // owner
address(this), // address to transfer to
address(0), // not used
vaultID, // vaultId
0, // not used
|
if (settlementAllowed) {
actions = new IController.ActionArgs[](1);
actions[0] = IController.ActionArgs(
IController.ActionType.SettleVault,
address(this), // owner
address(this), // address to transfer to
address(0), // not used
vaultID, // vaultId
0, // not used
| 12,777
|
0
|
// The account to send the tokens
|
mapping(address=>address) public accounts;
|
mapping(address=>address) public accounts;
| 14,218
|
22
|
// set new highest bidder
|
highestBidder = msg.sender;
highestBindingBid = newBid;
|
highestBidder = msg.sender;
highestBindingBid = newBid;
| 49,069
|
228
|
// Initiates the shutdown process, in case of an emergency. /
|
function emergencyShutdown() external;
|
function emergencyShutdown() external;
| 17,188
|
566
|
// Recalls funds from active vault if less than amt exist locally//amt amount of funds that need to exist locally to fulfill pending request
|
function ensureSufficientFundsExistLocally(uint256 amt) internal {
uint256 currentBal = IERC20Burnable(token).balanceOf(address(this));
if (currentBal < amt) {
uint256 diff = amt - currentBal;
// get enough funds from active vault to replenish local holdings & fulfill claim request
_recallExcessFundsFromActiveVault(plantableThreshold.add(diff));
}
}
|
function ensureSufficientFundsExistLocally(uint256 amt) internal {
uint256 currentBal = IERC20Burnable(token).balanceOf(address(this));
if (currentBal < amt) {
uint256 diff = amt - currentBal;
// get enough funds from active vault to replenish local holdings & fulfill claim request
_recallExcessFundsFromActiveVault(plantableThreshold.add(diff));
}
}
| 36,846
|
763
|
// If they have no debt, they're a new issuer; record this.
|
state.incrementTotalIssuerCount();
|
state.incrementTotalIssuerCount();
| 29,599
|
2
|
// Emitted when a payout execution fails tokenAddress - Address of the token being paid out to - Address of the recipient amount - Amount being paid out payoutNonce - Nonce of the payout /
|
event PayoutFailed(
|
event PayoutFailed(
| 20,051
|
1,124
|
// https:etherscan.io/address/0x6DF798ec713b33BE823b917F27820f2aA0cf7662;
|
Synth newSynth = Synth(0x6DF798ec713b33BE823b917F27820f2aA0cf7662);
newSynth.setTotalSupply(existingSynth.totalSupply());
|
Synth newSynth = Synth(0x6DF798ec713b33BE823b917F27820f2aA0cf7662);
newSynth.setTotalSupply(existingSynth.totalSupply());
| 34,553
|
58
|
// Gets the locked amount of a given beneficiary, ie. non vested amount, at a specific time. _to The beneficiary to be checked. _time uint64 The time to be checkedreturn An uint256 representing the non vested amounts of a specific grant on thepassed time frame. /
|
function getLockedAmountOf(address _to, uint256 _time) public view returns (uint256) {
VestingGrant storage grant = grants[_to];
if (grant.grantedAmount == 0) return 0;
return calculateLocked(grant.grantedAmount, uint256(_time), uint256(grant.start),
uint256(grant.cliff), uint256(grant.vesting));
}
|
function getLockedAmountOf(address _to, uint256 _time) public view returns (uint256) {
VestingGrant storage grant = grants[_to];
if (grant.grantedAmount == 0) return 0;
return calculateLocked(grant.grantedAmount, uint256(_time), uint256(grant.start),
uint256(grant.cliff), uint256(grant.vesting));
}
| 22,272
|
2
|
// Registers a list of tokens in a Minimal Swap Info Pool. This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting. Requirements: - `tokens` must not be registered in the Pool- `tokens` must not contain duplicates /
|
function _registerMinimalSwapInfoPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal {
EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId];
for (uint256 i = 0; i < tokens.length; ++i) {
bool added = poolTokens.add(address(tokens[i]));
_require(added, Errors.TOKEN_ALREADY_REGISTERED);
// Note that we don't initialize the balance mapping: the default value of zero corresponds to an empty
// balance.
}
}
|
function _registerMinimalSwapInfoPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal {
EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId];
for (uint256 i = 0; i < tokens.length; ++i) {
bool added = poolTokens.add(address(tokens[i]));
_require(added, Errors.TOKEN_ALREADY_REGISTERED);
// Note that we don't initialize the balance mapping: the default value of zero corresponds to an empty
// balance.
}
}
| 12,187
|
19
|
// Address of the operator.
|
address public operatorAddress;
|
address public operatorAddress;
| 12,408
|
58
|
// Apply the rule with the specified parameters of a PolicyHook/_comptrollerProxy The fund's ComptrollerProxy address/_encodedArgs Encoded args with which to validate the rule/ return isValid_ True if the rule passes
|
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
|
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
| 18,326
|
96
|
// internal
|
function _approve(address to, uint tokenId) internal{
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
|
function _approve(address to, uint tokenId) internal{
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
| 19,514
|
62
|
// RariGovernanceTokenDistributor RariGovernanceTokenDistributor distributes RGT (Rari Governance Token) to Rari Stable Pool, Yield Pool, and Ethereum Pool holders. /
|
contract RariGovernanceTokenDistributor is Initializable, Ownable {
using SafeMath for uint256;
/**
* @dev Initializer that sets the distribution start block, distribution end block, fund manager contracts, fund token contracts, and ETH/USD price feed.
*/
function initialize(uint256 startBlock, IRariFundManager[3] memory fundManagers, IERC20[3] memory fundTokens) public initializer {
Ownable.initialize(msg.sender);
require(fundManagers.length == 3 && fundTokens.length == 3, "Fund manager and fund token array lengths must be equal to 3.");
distributionStartBlock = startBlock;
distributionEndBlock = distributionStartBlock + DISTRIBUTION_PERIOD;
rariFundManagers = fundManagers;
rariFundTokens = fundTokens;
_ethUsdPriceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
}
/**
* @notice Boolean indicating if this contract is disabled.
*/
bool public disabled;
/**
* @dev Emitted when the primary functionality of this RariGovernanceTokenDistributor contract has been disabled.
*/
event Disabled();
/**
* @dev Emitted when the primary functionality of this RariGovernanceTokenDistributor contract has been enabled.
*/
event Enabled();
/**
* @dev Disables/enables primary functionality of this RariGovernanceTokenDistributor so contract(s) can be upgraded.
*/
function setDisabled(bool _disabled) external onlyOwner {
require(_disabled != disabled, "No change to enabled/disabled status.");
disabled = _disabled;
if (_disabled) emit Disabled(); else emit Enabled();
}
/**
* @dev Throws if fund is disabled.
*/
modifier enabled() {
require(!disabled, "This governance token distributor contract is disabled. This may be due to an upgrade.");
_;
}
/**
* @dev The RariGovernanceToken contract.
*/
RariGovernanceToken rariGovernanceToken;
/**
* @dev Sets the RariGovernanceToken distributed by ths RariGovernanceTokenDistributor.
* @param governanceToken The new RariGovernanceToken contract.
*/
function setGovernanceToken(RariGovernanceToken governanceToken) external onlyOwner {
if (address(rariGovernanceToken) != address(0)) require(disabled, "This governance token distributor contract must be disabled before changing the governance token contract.");
require(address(governanceToken) != address(0), "New governance token contract cannot be the zero address.");
rariGovernanceToken = governanceToken;
}
/**
* @notice Enum for the Rari pools to which distributions are rewarded.
*/
enum RariPool {
Stable,
Yield,
Ethereum
}
/**
* @dev The RariFundManager contracts for each RariPool.
*/
IRariFundManager[3] rariFundManagers;
/**
* @dev The RariFundToken contracts for each RariPool.
*/
IERC20[3] rariFundTokens;
/**
* @dev Sets the RariFundManager for `pool`.
* @param pool The pool associated with this RariFundManager.
* @param fundManager The RariFundManager associated with this pool.
*/
function setFundManager(RariPool pool, IRariFundManager fundManager) external onlyOwner {
require(disabled, "This governance token distributor contract must be disabled before changing fund manager contracts.");
require(address(fundManager) != address(0), "New fund manager contract cannot be the zero address.");
rariFundManagers[uint8(pool)] = fundManager;
}
/**
* @dev Sets the RariFundToken for `pool`.
* @param pool The pool associated with this RariFundToken.
* @param fundToken The RariFundToken associated with this pool.
*/
function setFundToken(RariPool pool, IERC20 fundToken) external onlyOwner {
require(disabled, "This governance token distributor contract must be disabled before changing fund token contracts.");
require(address(fundToken) != address(0), "New fund token contract cannot be the zero address.");
rariFundTokens[uint8(pool)] = fundToken;
}
/**
* @notice Starting block number of the distribution.
*/
uint256 public distributionStartBlock;
/**
* @notice Ending block number of the distribution.
*/
uint256 public distributionEndBlock;
/**
* @notice Length in blocks of the distribution period.
*/
uint256 public constant DISTRIBUTION_PERIOD = 390000;
/**
* @notice Total and final quantity of all RGT to be distributed by the end of the period.
*/
uint256 public constant FINAL_RGT_DISTRIBUTION = 8750000e18;
/**
* @notice Returns the amount of RGT earned via liquidity mining at the given `blockNumber`.
* See the following graph for a visualization of RGT distributed via liquidity mining vs. blocks since distribution started: https://www.desmos.com/calculator/2yvnflg4ir
* @param blockNumber The block number to check.
*/
function getRgtDistributed(uint256 blockNumber) public view returns (uint256) {
if (blockNumber <= distributionStartBlock) return 0;
if (blockNumber >= distributionEndBlock) return FINAL_RGT_DISTRIBUTION;
uint256 blocks = blockNumber.sub(distributionStartBlock);
if (blocks < 97500) return uint256(1e18).mul(blocks ** 2).div(2730).add(uint256(1450e18).mul(blocks).div(273));
if (blocks < 195000) return uint256(14600e18).mul(blocks).div(273).sub(uint256(2e18).mul(blocks ** 2).div(17745)).sub(uint256(1000000e18).div(7));
if (blocks < 292500) return uint256(1e18).mul(blocks ** 2).div(35490).add(uint256(39250000e18).div(7)).sub(uint256(950e18).mul(blocks).div(273));
return uint256(1e18).mul(blocks ** 2).div(35490).add(uint256(34750000e18).div(7)).sub(uint256(50e18).mul(blocks).div(39));
}
/**
* @dev Caches fund balances (to calculate distribution speeds).
*/
uint256[3] _fundBalancesCache;
/**
* @dev Maps RariPool indexes to the quantity of RGT distributed per RSPT/RYPT/REPT at the last speed update.
*/
uint256[3] _rgtPerRftAtLastSpeedUpdate;
/**
* @dev The total amount of RGT distributed at the last speed update.
*/
uint256 _rgtDistributedAtLastSpeedUpdate;
/**
* @dev Maps RariPool indexes to holder addresses to the quantity of RGT distributed per RSPT/RYPT/REPT at their last claim.
*/
mapping (address => uint256)[3] _rgtPerRftAtLastDistribution;
/**
* @dev Throws if the distribution period has ended.
*/
modifier beforeDistributionPeriodEnded() {
require(block.number < distributionEndBlock, "The governance token distribution period has already ended.");
_;
}
/**
* @dev Updates RGT distribution speeds for each pool given one `pool` and its `newBalance` (only accessible by the RariFundManager corresponding to `pool`).
* @param pool The pool whose balance should be refreshed.
* @param newBalance The new balance of the pool to be refreshed.
*/
function refreshDistributionSpeeds(RariPool pool, uint256 newBalance) external enabled {
require(msg.sender == address(rariFundManagers[uint8(pool)]), "Caller is not the fund manager corresponding to this pool.");
if (block.number >= distributionEndBlock) return;
storeRgtDistributedPerRft();
_fundBalancesCache[uint8(pool)] = newBalance;
}
/**
* @notice Updates RGT distribution speeds for each pool given one `pool` whose balance should be refreshed.
* @param pool The pool whose balance should be refreshed.
*/
function refreshDistributionSpeeds(RariPool pool) external enabled beforeDistributionPeriodEnded {
storeRgtDistributedPerRft();
_fundBalancesCache[uint8(pool)] = rariFundManagers[uint8(pool)].getFundBalance();
}
/**
* @notice Updates RGT distribution speeds for each pool.
*/
function refreshDistributionSpeeds() external enabled beforeDistributionPeriodEnded {
storeRgtDistributedPerRft();
for (uint256 i = 0; i < 3; i++) _fundBalancesCache[i] = rariFundManagers[i].getFundBalance();
}
/**
* @dev Chainlink price feed for ETH/USD.
*/
AggregatorV3Interface private _ethUsdPriceFeed;
/**
* @dev Retrives the latest ETH/USD price.
*/
function getEthUsdPrice() public view returns (uint256) {
(, int256 price, , , ) = _ethUsdPriceFeed.latestRoundData();
return price >= 0 ? uint256(price) : 0;
}
/**
* @dev Stores the latest quantity of RGT distributed per RFT for all pools (so speeds can be updated immediately afterwards).
*/
function storeRgtDistributedPerRft() internal {
uint256 rgtDistributed = getRgtDistributed(block.number);
uint256 rgtToDistribute = rgtDistributed.sub(_rgtDistributedAtLastSpeedUpdate);
if (rgtToDistribute <= 0) return;
uint256 ethFundBalanceUsd = _fundBalancesCache[2] > 0 ? _fundBalancesCache[2].mul(getEthUsdPrice()).div(1e8) : 0;
uint256 fundBalanceSum = 0;
for (uint256 i = 0; i < 3; i++) fundBalanceSum = fundBalanceSum.add(i == 2 ? ethFundBalanceUsd : _fundBalancesCache[i]);
if (fundBalanceSum <= 0) return;
_rgtDistributedAtLastSpeedUpdate = rgtDistributed;
for (uint256 i = 0; i < 3; i++) {
uint256 totalSupply = rariFundTokens[i].totalSupply();
if (totalSupply > 0) _rgtPerRftAtLastSpeedUpdate[i] = _rgtPerRftAtLastSpeedUpdate[i].add(rgtToDistribute.mul(i == 2 ? ethFundBalanceUsd : _fundBalancesCache[i]).div(fundBalanceSum).mul(1e18).div(totalSupply));
}
}
/**
* @dev Gets RGT distributed per RFT for all pools.
*/
function getRgtDistributedPerRft() internal view returns (uint256[3] memory rgtPerRftByPool) {
uint256 rgtDistributed = getRgtDistributed(block.number);
uint256 rgtToDistribute = rgtDistributed.sub(_rgtDistributedAtLastSpeedUpdate);
if (rgtToDistribute <= 0) return _rgtPerRftAtLastSpeedUpdate;
uint256 ethFundBalanceUsd = _fundBalancesCache[2] > 0 ? _fundBalancesCache[2].mul(getEthUsdPrice()).div(1e8) : 0;
uint256 fundBalanceSum = 0;
for (uint256 i = 0; i < 3; i++) fundBalanceSum = fundBalanceSum.add(i == 2 ? ethFundBalanceUsd : _fundBalancesCache[i]);
if (fundBalanceSum <= 0) return _rgtPerRftAtLastSpeedUpdate;
for (uint256 i = 0; i < 3; i++) {
uint256 totalSupply = rariFundTokens[i].totalSupply();
rgtPerRftByPool[i] = totalSupply > 0 ? _rgtPerRftAtLastSpeedUpdate[i].add(rgtToDistribute.mul(i == 2 ? ethFundBalanceUsd : _fundBalancesCache[i]).div(fundBalanceSum).mul(1e18).div(totalSupply)) : _rgtPerRftAtLastSpeedUpdate[i];
}
}
/**
* @dev Maps holder addresses to the quantity of RGT distributed to each.
*/
mapping (address => uint256) _rgtDistributedByHolder;
/**
* @dev Maps holder addresses to the quantity of RGT claimed by each.
*/
mapping (address => uint256) _rgtClaimedByHolder;
/**
* @dev Distributes all undistributed RGT earned by `holder` in `pool` (without reverting if no RGT is available to distribute).
* @param holder The holder of RSPT, RYPT, or REPT whose RGT is to be distributed.
* @param pool The Rari pool for which to distribute RGT.
* @return The quantity of RGT distributed.
*/
function distributeRgt(address holder, RariPool pool) external enabled returns (uint256) {
// Get RFT balance of this holder
uint256 rftBalance = rariFundTokens[uint8(pool)].balanceOf(holder);
if (rftBalance <= 0) return 0;
// Store RGT distributed per RFT
storeRgtDistributedPerRft();
// Get undistributed RGT
uint256 undistributedRgt = _rgtPerRftAtLastSpeedUpdate[uint8(pool)].sub(_rgtPerRftAtLastDistribution[uint8(pool)][holder]).mul(rftBalance).div(1e18);
if (undistributedRgt <= 0) return 0;
// Distribute RGT
_rgtPerRftAtLastDistribution[uint8(pool)][holder] = _rgtPerRftAtLastSpeedUpdate[uint8(pool)];
_rgtDistributedByHolder[holder] = _rgtDistributedByHolder[holder].add(undistributedRgt);
return undistributedRgt;
}
/**
* @dev Distributes all undistributed RGT earned by `holder` in all pools (without reverting if no RGT is available to distribute).
* @param holder The holder of RSPT, RYPT, and/or REPT whose RGT is to be distributed.
* @return The quantity of RGT distributed.
*/
function distributeRgt(address holder) internal enabled returns (uint256) {
// Store RGT distributed per RFT
storeRgtDistributedPerRft();
// Get undistributed RGT
uint256 undistributedRgt = 0;
for (uint256 i = 0; i < 3; i++) {
// Get RFT balance of this holder in this pool
uint256 rftBalance = rariFundTokens[i].balanceOf(holder);
if (rftBalance <= 0) continue;
// Add undistributed RGT
undistributedRgt += _rgtPerRftAtLastSpeedUpdate[i].sub(_rgtPerRftAtLastDistribution[i][holder]).mul(rftBalance).div(1e18);
}
if (undistributedRgt <= 0) return 0;
// Add undistributed to distributed
for (uint256 i = 0; i < 3; i++) if (rariFundTokens[i].balanceOf(holder) > 0) _rgtPerRftAtLastDistribution[i][holder] = _rgtPerRftAtLastSpeedUpdate[i];
_rgtDistributedByHolder[holder] = _rgtDistributedByHolder[holder].add(undistributedRgt);
return undistributedRgt;
}
/**
* @dev Stores the RGT distributed per RSPT/RYPT/REPT right before `holder`'s first incoming RSPT/RYPT/REPT transfer since having a zero balance.
* @param holder The holder of RSPT, RYPT, and/or REPT.
* @param pool The Rari pool of the pool token.
*/
function beforeFirstPoolTokenTransferIn(address holder, RariPool pool) external enabled {
require(rariFundTokens[uint8(pool)].balanceOf(holder) == 0, "Pool token balance is not equal to 0.");
storeRgtDistributedPerRft();
_rgtPerRftAtLastDistribution[uint8(pool)][holder] = _rgtPerRftAtLastSpeedUpdate[uint8(pool)];
}
/**
* @dev Returns the quantity of undistributed RGT earned by `holder` via liquidity mining across all pools.
* @param holder The holder of RSPT, RYPT, or REPT.
* @return The quantity of unclaimed RGT.
*/
function getUndistributedRgt(address holder) internal view returns (uint256) {
// Get RGT distributed per RFT
uint256[3] memory rgtPerRftByPool = getRgtDistributedPerRft();
// Get undistributed RGT
uint256 undistributedRgt = 0;
for (uint256 i = 0; i < 3; i++) {
// Get RFT balance of this holder in this pool
uint256 rftBalance = rariFundTokens[i].balanceOf(holder);
if (rftBalance <= 0) continue;
// Add undistributed RGT
undistributedRgt += rgtPerRftByPool[i].sub(_rgtPerRftAtLastDistribution[i][holder]).mul(rftBalance).div(1e18);
}
return undistributedRgt;
}
/**
* @notice Returns the quantity of unclaimed RGT earned by `holder` via liquidity mining across all pools.
* @param holder The holder of RSPT, RYPT, or REPT.
* @return The quantity of unclaimed RGT.
*/
function getUnclaimedRgt(address holder) external view returns (uint256) {
return _rgtDistributedByHolder[holder].sub(_rgtClaimedByHolder[holder]).add(getUndistributedRgt(holder));
}
/**
* @notice Returns the public RGT claim fee for users during liquidity mining (scaled by 1e18) at `blockNumber`.
*/
function getPublicRgtClaimFee(uint256 blockNumber) public view returns (uint256) {
if (blockNumber <= distributionStartBlock) return 0.33e18;
if (blockNumber >= distributionEndBlock) return 0;
return uint256(0.33e18).mul(distributionEndBlock.sub(blockNumber)).div(DISTRIBUTION_PERIOD);
}
/**
* @dev Event emitted when `claimed` RGT is claimed by `holder`.
*/
event Claim(address holder, uint256 claimed, uint256 transferred, uint256 burned);
/**
* @notice Claims `amount` unclaimed RGT earned by `msg.sender` in all pools.
* @param amount The amount of RGT to claim.
*/
function claimRgt(uint256 amount) public enabled {
// Distribute RGT to holder
distributeRgt(msg.sender);
// Get unclaimed RGT
uint256 unclaimedRgt = _rgtDistributedByHolder[msg.sender].sub(_rgtClaimedByHolder[msg.sender]);
require(amount <= unclaimedRgt, "Claim amount cannot be greater than unclaimed RGT.");
// Claim RGT
uint256 burnRgt = amount.mul(getPublicRgtClaimFee(block.number)).div(1e18);
uint256 transferRgt = amount.sub(burnRgt);
_rgtClaimedByHolder[msg.sender] = _rgtClaimedByHolder[msg.sender].add(amount);
require(rariGovernanceToken.transfer(msg.sender, transferRgt), "Failed to transfer RGT from liquidity mining reserve.");
rariGovernanceToken.burn(burnRgt);
emit Claim(msg.sender, amount, transferRgt, burnRgt);
}
/**
* @notice Claims all unclaimed RGT earned by `msg.sender` in all pools.
* @return The quantity of RGT claimed.
*/
function claimAllRgt() public enabled returns (uint256) {
// Distribute RGT to holder
distributeRgt(msg.sender);
// Get unclaimed RGT
uint256 unclaimedRgt = _rgtDistributedByHolder[msg.sender].sub(_rgtClaimedByHolder[msg.sender]);
require(unclaimedRgt > 0, "Unclaimed RGT not greater than 0.");
// Claim RGT
uint256 burnRgt = unclaimedRgt.mul(getPublicRgtClaimFee(block.number)).div(1e18);
uint256 transferRgt = unclaimedRgt.sub(burnRgt);
_rgtClaimedByHolder[msg.sender] = _rgtClaimedByHolder[msg.sender].add(unclaimedRgt);
require(rariGovernanceToken.transfer(msg.sender, transferRgt), "Failed to transfer RGT from liquidity mining reserve.");
rariGovernanceToken.burn(burnRgt);
emit Claim(msg.sender, unclaimedRgt, transferRgt, burnRgt);
return unclaimedRgt;
}
/**
* @dev Forwards all RGT to a new RariGovernanceTokenDistributor contract.
* @param 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)));
}
/**
* @dev Sets the ETH/USD price feed if not initialized due to upgrade.
*/
function setEthUsdPriceFeed() external onlyOwner {
_ethUsdPriceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
}
}
|
contract RariGovernanceTokenDistributor is Initializable, Ownable {
using SafeMath for uint256;
/**
* @dev Initializer that sets the distribution start block, distribution end block, fund manager contracts, fund token contracts, and ETH/USD price feed.
*/
function initialize(uint256 startBlock, IRariFundManager[3] memory fundManagers, IERC20[3] memory fundTokens) public initializer {
Ownable.initialize(msg.sender);
require(fundManagers.length == 3 && fundTokens.length == 3, "Fund manager and fund token array lengths must be equal to 3.");
distributionStartBlock = startBlock;
distributionEndBlock = distributionStartBlock + DISTRIBUTION_PERIOD;
rariFundManagers = fundManagers;
rariFundTokens = fundTokens;
_ethUsdPriceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
}
/**
* @notice Boolean indicating if this contract is disabled.
*/
bool public disabled;
/**
* @dev Emitted when the primary functionality of this RariGovernanceTokenDistributor contract has been disabled.
*/
event Disabled();
/**
* @dev Emitted when the primary functionality of this RariGovernanceTokenDistributor contract has been enabled.
*/
event Enabled();
/**
* @dev Disables/enables primary functionality of this RariGovernanceTokenDistributor so contract(s) can be upgraded.
*/
function setDisabled(bool _disabled) external onlyOwner {
require(_disabled != disabled, "No change to enabled/disabled status.");
disabled = _disabled;
if (_disabled) emit Disabled(); else emit Enabled();
}
/**
* @dev Throws if fund is disabled.
*/
modifier enabled() {
require(!disabled, "This governance token distributor contract is disabled. This may be due to an upgrade.");
_;
}
/**
* @dev The RariGovernanceToken contract.
*/
RariGovernanceToken rariGovernanceToken;
/**
* @dev Sets the RariGovernanceToken distributed by ths RariGovernanceTokenDistributor.
* @param governanceToken The new RariGovernanceToken contract.
*/
function setGovernanceToken(RariGovernanceToken governanceToken) external onlyOwner {
if (address(rariGovernanceToken) != address(0)) require(disabled, "This governance token distributor contract must be disabled before changing the governance token contract.");
require(address(governanceToken) != address(0), "New governance token contract cannot be the zero address.");
rariGovernanceToken = governanceToken;
}
/**
* @notice Enum for the Rari pools to which distributions are rewarded.
*/
enum RariPool {
Stable,
Yield,
Ethereum
}
/**
* @dev The RariFundManager contracts for each RariPool.
*/
IRariFundManager[3] rariFundManagers;
/**
* @dev The RariFundToken contracts for each RariPool.
*/
IERC20[3] rariFundTokens;
/**
* @dev Sets the RariFundManager for `pool`.
* @param pool The pool associated with this RariFundManager.
* @param fundManager The RariFundManager associated with this pool.
*/
function setFundManager(RariPool pool, IRariFundManager fundManager) external onlyOwner {
require(disabled, "This governance token distributor contract must be disabled before changing fund manager contracts.");
require(address(fundManager) != address(0), "New fund manager contract cannot be the zero address.");
rariFundManagers[uint8(pool)] = fundManager;
}
/**
* @dev Sets the RariFundToken for `pool`.
* @param pool The pool associated with this RariFundToken.
* @param fundToken The RariFundToken associated with this pool.
*/
function setFundToken(RariPool pool, IERC20 fundToken) external onlyOwner {
require(disabled, "This governance token distributor contract must be disabled before changing fund token contracts.");
require(address(fundToken) != address(0), "New fund token contract cannot be the zero address.");
rariFundTokens[uint8(pool)] = fundToken;
}
/**
* @notice Starting block number of the distribution.
*/
uint256 public distributionStartBlock;
/**
* @notice Ending block number of the distribution.
*/
uint256 public distributionEndBlock;
/**
* @notice Length in blocks of the distribution period.
*/
uint256 public constant DISTRIBUTION_PERIOD = 390000;
/**
* @notice Total and final quantity of all RGT to be distributed by the end of the period.
*/
uint256 public constant FINAL_RGT_DISTRIBUTION = 8750000e18;
/**
* @notice Returns the amount of RGT earned via liquidity mining at the given `blockNumber`.
* See the following graph for a visualization of RGT distributed via liquidity mining vs. blocks since distribution started: https://www.desmos.com/calculator/2yvnflg4ir
* @param blockNumber The block number to check.
*/
function getRgtDistributed(uint256 blockNumber) public view returns (uint256) {
if (blockNumber <= distributionStartBlock) return 0;
if (blockNumber >= distributionEndBlock) return FINAL_RGT_DISTRIBUTION;
uint256 blocks = blockNumber.sub(distributionStartBlock);
if (blocks < 97500) return uint256(1e18).mul(blocks ** 2).div(2730).add(uint256(1450e18).mul(blocks).div(273));
if (blocks < 195000) return uint256(14600e18).mul(blocks).div(273).sub(uint256(2e18).mul(blocks ** 2).div(17745)).sub(uint256(1000000e18).div(7));
if (blocks < 292500) return uint256(1e18).mul(blocks ** 2).div(35490).add(uint256(39250000e18).div(7)).sub(uint256(950e18).mul(blocks).div(273));
return uint256(1e18).mul(blocks ** 2).div(35490).add(uint256(34750000e18).div(7)).sub(uint256(50e18).mul(blocks).div(39));
}
/**
* @dev Caches fund balances (to calculate distribution speeds).
*/
uint256[3] _fundBalancesCache;
/**
* @dev Maps RariPool indexes to the quantity of RGT distributed per RSPT/RYPT/REPT at the last speed update.
*/
uint256[3] _rgtPerRftAtLastSpeedUpdate;
/**
* @dev The total amount of RGT distributed at the last speed update.
*/
uint256 _rgtDistributedAtLastSpeedUpdate;
/**
* @dev Maps RariPool indexes to holder addresses to the quantity of RGT distributed per RSPT/RYPT/REPT at their last claim.
*/
mapping (address => uint256)[3] _rgtPerRftAtLastDistribution;
/**
* @dev Throws if the distribution period has ended.
*/
modifier beforeDistributionPeriodEnded() {
require(block.number < distributionEndBlock, "The governance token distribution period has already ended.");
_;
}
/**
* @dev Updates RGT distribution speeds for each pool given one `pool` and its `newBalance` (only accessible by the RariFundManager corresponding to `pool`).
* @param pool The pool whose balance should be refreshed.
* @param newBalance The new balance of the pool to be refreshed.
*/
function refreshDistributionSpeeds(RariPool pool, uint256 newBalance) external enabled {
require(msg.sender == address(rariFundManagers[uint8(pool)]), "Caller is not the fund manager corresponding to this pool.");
if (block.number >= distributionEndBlock) return;
storeRgtDistributedPerRft();
_fundBalancesCache[uint8(pool)] = newBalance;
}
/**
* @notice Updates RGT distribution speeds for each pool given one `pool` whose balance should be refreshed.
* @param pool The pool whose balance should be refreshed.
*/
function refreshDistributionSpeeds(RariPool pool) external enabled beforeDistributionPeriodEnded {
storeRgtDistributedPerRft();
_fundBalancesCache[uint8(pool)] = rariFundManagers[uint8(pool)].getFundBalance();
}
/**
* @notice Updates RGT distribution speeds for each pool.
*/
function refreshDistributionSpeeds() external enabled beforeDistributionPeriodEnded {
storeRgtDistributedPerRft();
for (uint256 i = 0; i < 3; i++) _fundBalancesCache[i] = rariFundManagers[i].getFundBalance();
}
/**
* @dev Chainlink price feed for ETH/USD.
*/
AggregatorV3Interface private _ethUsdPriceFeed;
/**
* @dev Retrives the latest ETH/USD price.
*/
function getEthUsdPrice() public view returns (uint256) {
(, int256 price, , , ) = _ethUsdPriceFeed.latestRoundData();
return price >= 0 ? uint256(price) : 0;
}
/**
* @dev Stores the latest quantity of RGT distributed per RFT for all pools (so speeds can be updated immediately afterwards).
*/
function storeRgtDistributedPerRft() internal {
uint256 rgtDistributed = getRgtDistributed(block.number);
uint256 rgtToDistribute = rgtDistributed.sub(_rgtDistributedAtLastSpeedUpdate);
if (rgtToDistribute <= 0) return;
uint256 ethFundBalanceUsd = _fundBalancesCache[2] > 0 ? _fundBalancesCache[2].mul(getEthUsdPrice()).div(1e8) : 0;
uint256 fundBalanceSum = 0;
for (uint256 i = 0; i < 3; i++) fundBalanceSum = fundBalanceSum.add(i == 2 ? ethFundBalanceUsd : _fundBalancesCache[i]);
if (fundBalanceSum <= 0) return;
_rgtDistributedAtLastSpeedUpdate = rgtDistributed;
for (uint256 i = 0; i < 3; i++) {
uint256 totalSupply = rariFundTokens[i].totalSupply();
if (totalSupply > 0) _rgtPerRftAtLastSpeedUpdate[i] = _rgtPerRftAtLastSpeedUpdate[i].add(rgtToDistribute.mul(i == 2 ? ethFundBalanceUsd : _fundBalancesCache[i]).div(fundBalanceSum).mul(1e18).div(totalSupply));
}
}
/**
* @dev Gets RGT distributed per RFT for all pools.
*/
function getRgtDistributedPerRft() internal view returns (uint256[3] memory rgtPerRftByPool) {
uint256 rgtDistributed = getRgtDistributed(block.number);
uint256 rgtToDistribute = rgtDistributed.sub(_rgtDistributedAtLastSpeedUpdate);
if (rgtToDistribute <= 0) return _rgtPerRftAtLastSpeedUpdate;
uint256 ethFundBalanceUsd = _fundBalancesCache[2] > 0 ? _fundBalancesCache[2].mul(getEthUsdPrice()).div(1e8) : 0;
uint256 fundBalanceSum = 0;
for (uint256 i = 0; i < 3; i++) fundBalanceSum = fundBalanceSum.add(i == 2 ? ethFundBalanceUsd : _fundBalancesCache[i]);
if (fundBalanceSum <= 0) return _rgtPerRftAtLastSpeedUpdate;
for (uint256 i = 0; i < 3; i++) {
uint256 totalSupply = rariFundTokens[i].totalSupply();
rgtPerRftByPool[i] = totalSupply > 0 ? _rgtPerRftAtLastSpeedUpdate[i].add(rgtToDistribute.mul(i == 2 ? ethFundBalanceUsd : _fundBalancesCache[i]).div(fundBalanceSum).mul(1e18).div(totalSupply)) : _rgtPerRftAtLastSpeedUpdate[i];
}
}
/**
* @dev Maps holder addresses to the quantity of RGT distributed to each.
*/
mapping (address => uint256) _rgtDistributedByHolder;
/**
* @dev Maps holder addresses to the quantity of RGT claimed by each.
*/
mapping (address => uint256) _rgtClaimedByHolder;
/**
* @dev Distributes all undistributed RGT earned by `holder` in `pool` (without reverting if no RGT is available to distribute).
* @param holder The holder of RSPT, RYPT, or REPT whose RGT is to be distributed.
* @param pool The Rari pool for which to distribute RGT.
* @return The quantity of RGT distributed.
*/
function distributeRgt(address holder, RariPool pool) external enabled returns (uint256) {
// Get RFT balance of this holder
uint256 rftBalance = rariFundTokens[uint8(pool)].balanceOf(holder);
if (rftBalance <= 0) return 0;
// Store RGT distributed per RFT
storeRgtDistributedPerRft();
// Get undistributed RGT
uint256 undistributedRgt = _rgtPerRftAtLastSpeedUpdate[uint8(pool)].sub(_rgtPerRftAtLastDistribution[uint8(pool)][holder]).mul(rftBalance).div(1e18);
if (undistributedRgt <= 0) return 0;
// Distribute RGT
_rgtPerRftAtLastDistribution[uint8(pool)][holder] = _rgtPerRftAtLastSpeedUpdate[uint8(pool)];
_rgtDistributedByHolder[holder] = _rgtDistributedByHolder[holder].add(undistributedRgt);
return undistributedRgt;
}
/**
* @dev Distributes all undistributed RGT earned by `holder` in all pools (without reverting if no RGT is available to distribute).
* @param holder The holder of RSPT, RYPT, and/or REPT whose RGT is to be distributed.
* @return The quantity of RGT distributed.
*/
function distributeRgt(address holder) internal enabled returns (uint256) {
// Store RGT distributed per RFT
storeRgtDistributedPerRft();
// Get undistributed RGT
uint256 undistributedRgt = 0;
for (uint256 i = 0; i < 3; i++) {
// Get RFT balance of this holder in this pool
uint256 rftBalance = rariFundTokens[i].balanceOf(holder);
if (rftBalance <= 0) continue;
// Add undistributed RGT
undistributedRgt += _rgtPerRftAtLastSpeedUpdate[i].sub(_rgtPerRftAtLastDistribution[i][holder]).mul(rftBalance).div(1e18);
}
if (undistributedRgt <= 0) return 0;
// Add undistributed to distributed
for (uint256 i = 0; i < 3; i++) if (rariFundTokens[i].balanceOf(holder) > 0) _rgtPerRftAtLastDistribution[i][holder] = _rgtPerRftAtLastSpeedUpdate[i];
_rgtDistributedByHolder[holder] = _rgtDistributedByHolder[holder].add(undistributedRgt);
return undistributedRgt;
}
/**
* @dev Stores the RGT distributed per RSPT/RYPT/REPT right before `holder`'s first incoming RSPT/RYPT/REPT transfer since having a zero balance.
* @param holder The holder of RSPT, RYPT, and/or REPT.
* @param pool The Rari pool of the pool token.
*/
function beforeFirstPoolTokenTransferIn(address holder, RariPool pool) external enabled {
require(rariFundTokens[uint8(pool)].balanceOf(holder) == 0, "Pool token balance is not equal to 0.");
storeRgtDistributedPerRft();
_rgtPerRftAtLastDistribution[uint8(pool)][holder] = _rgtPerRftAtLastSpeedUpdate[uint8(pool)];
}
/**
* @dev Returns the quantity of undistributed RGT earned by `holder` via liquidity mining across all pools.
* @param holder The holder of RSPT, RYPT, or REPT.
* @return The quantity of unclaimed RGT.
*/
function getUndistributedRgt(address holder) internal view returns (uint256) {
// Get RGT distributed per RFT
uint256[3] memory rgtPerRftByPool = getRgtDistributedPerRft();
// Get undistributed RGT
uint256 undistributedRgt = 0;
for (uint256 i = 0; i < 3; i++) {
// Get RFT balance of this holder in this pool
uint256 rftBalance = rariFundTokens[i].balanceOf(holder);
if (rftBalance <= 0) continue;
// Add undistributed RGT
undistributedRgt += rgtPerRftByPool[i].sub(_rgtPerRftAtLastDistribution[i][holder]).mul(rftBalance).div(1e18);
}
return undistributedRgt;
}
/**
* @notice Returns the quantity of unclaimed RGT earned by `holder` via liquidity mining across all pools.
* @param holder The holder of RSPT, RYPT, or REPT.
* @return The quantity of unclaimed RGT.
*/
function getUnclaimedRgt(address holder) external view returns (uint256) {
return _rgtDistributedByHolder[holder].sub(_rgtClaimedByHolder[holder]).add(getUndistributedRgt(holder));
}
/**
* @notice Returns the public RGT claim fee for users during liquidity mining (scaled by 1e18) at `blockNumber`.
*/
function getPublicRgtClaimFee(uint256 blockNumber) public view returns (uint256) {
if (blockNumber <= distributionStartBlock) return 0.33e18;
if (blockNumber >= distributionEndBlock) return 0;
return uint256(0.33e18).mul(distributionEndBlock.sub(blockNumber)).div(DISTRIBUTION_PERIOD);
}
/**
* @dev Event emitted when `claimed` RGT is claimed by `holder`.
*/
event Claim(address holder, uint256 claimed, uint256 transferred, uint256 burned);
/**
* @notice Claims `amount` unclaimed RGT earned by `msg.sender` in all pools.
* @param amount The amount of RGT to claim.
*/
function claimRgt(uint256 amount) public enabled {
// Distribute RGT to holder
distributeRgt(msg.sender);
// Get unclaimed RGT
uint256 unclaimedRgt = _rgtDistributedByHolder[msg.sender].sub(_rgtClaimedByHolder[msg.sender]);
require(amount <= unclaimedRgt, "Claim amount cannot be greater than unclaimed RGT.");
// Claim RGT
uint256 burnRgt = amount.mul(getPublicRgtClaimFee(block.number)).div(1e18);
uint256 transferRgt = amount.sub(burnRgt);
_rgtClaimedByHolder[msg.sender] = _rgtClaimedByHolder[msg.sender].add(amount);
require(rariGovernanceToken.transfer(msg.sender, transferRgt), "Failed to transfer RGT from liquidity mining reserve.");
rariGovernanceToken.burn(burnRgt);
emit Claim(msg.sender, amount, transferRgt, burnRgt);
}
/**
* @notice Claims all unclaimed RGT earned by `msg.sender` in all pools.
* @return The quantity of RGT claimed.
*/
function claimAllRgt() public enabled returns (uint256) {
// Distribute RGT to holder
distributeRgt(msg.sender);
// Get unclaimed RGT
uint256 unclaimedRgt = _rgtDistributedByHolder[msg.sender].sub(_rgtClaimedByHolder[msg.sender]);
require(unclaimedRgt > 0, "Unclaimed RGT not greater than 0.");
// Claim RGT
uint256 burnRgt = unclaimedRgt.mul(getPublicRgtClaimFee(block.number)).div(1e18);
uint256 transferRgt = unclaimedRgt.sub(burnRgt);
_rgtClaimedByHolder[msg.sender] = _rgtClaimedByHolder[msg.sender].add(unclaimedRgt);
require(rariGovernanceToken.transfer(msg.sender, transferRgt), "Failed to transfer RGT from liquidity mining reserve.");
rariGovernanceToken.burn(burnRgt);
emit Claim(msg.sender, unclaimedRgt, transferRgt, burnRgt);
return unclaimedRgt;
}
/**
* @dev Forwards all RGT to a new RariGovernanceTokenDistributor contract.
* @param 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)));
}
/**
* @dev Sets the ETH/USD price feed if not initialized due to upgrade.
*/
function setEthUsdPriceFeed() external onlyOwner {
_ethUsdPriceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
}
}
| 9,516
|
35
|
// True if tokens transfers are currently frozen, false otherwise. /
|
bool frozen = false;
|
bool frozen = false;
| 26,411
|
0
|
// . ^-.^+. '^``^^'. `_. '^``^^'i?--?_^ '^^^^^' :_; `+?---__--]i.'^``^^' .'.''.;?; `<------__?l '^^^^^' .^^^^. '>-___+_^. .`^^^^^^' `<-__--_-_?l.`^^`^^' .^^^^.''>?-___-`. .```````' """"".`<-------_?I .`^^^^^^^^^^^^' .^^^^. ._]-__----??;.`^^^^^^`'_--?_"`<-------_?I`^^`^^^^^^^^^' .^`^^.+-__----__-I'^^^^^^^` .''.'.'>--_--<^ `<-------_?I`^^`^`^^^^^^^' .^^^^.+?---__-__-I`^^^^^^^` '^^^^`. '<-__-_+" `<-------_?l..`^^^^^^^^^^^^' .^^`^`''''' +?-----__--I`^^^^^^^` '^`^^^'<---_-+^```"+--_-----?i`^llllll:`^^`^^^`^''''``..^`^``^^`^`.+-----_--_-I``'`'````.'
|
// '^`^^^ '<---_-+" `^^,+--_----_?i`^+--_-?i`^^^^`^^`^``"""`'""^`^^^`^`. +---_-_----I`<-?--;``. ;{: //
// '^`^^^ '<---_-+^ `^`,+--_----_?li[_---___-^`"`^^^``',+------!`'^^^^`. ~---------_I`<-__-;``. ;}, .. //
|
// '^`^^^ '<---_-+" `^^,+--_----_?i`^+--_-?i`^^^^`^^`^``"""`'""^`^^^`^`. +---_-_----I`<-?--;``. ;{: //
// '^`^^^ '<---_-+^ `^`,+--_----_?li[_---___-^`"`^^^``',+------!`'^^^^`. ~---------_I`<-__-;``. ;}, .. //
| 26,555
|
13
|
// Function to stop minting new tokens.return True if the operation was successful. /
|
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
|
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
| 43,103
|
511
|
// if the caller is spawning the point to themselves,assume it knows what it's doing and resolve right away
|
if (msg.sender == _target)
{
doSpawn(_point, _target, true, 0x0);
}
|
if (msg.sender == _target)
{
doSpawn(_point, _target, true, 0x0);
}
| 52,054
|
40
|
// Recipes for each block type, as whole tokens.
|
uint256[NUM_RESOURCES][NUM_RESOURCES] internal RECIPES = [
[3, 1, 1],
[1, 3, 1],
[1, 1, 3]
];
|
uint256[NUM_RESOURCES][NUM_RESOURCES] internal RECIPES = [
[3, 1, 1],
[1, 3, 1],
[1, 1, 3]
];
| 49,589
|
4
|
// Function returns current (with accrual) amount of funds available for manager to borrowreturn Current available to borrow funds /
|
function availableToBorrow() external view returns (uint256) {
return _availableToBorrow(_accrueInterestVirtual());
}
|
function availableToBorrow() external view returns (uint256) {
return _availableToBorrow(_accrueInterestVirtual());
}
| 8,298
|
2
|
// emergency pause
|
bool public isPaused;
|
bool public isPaused;
| 4,927
|
308
|
// Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with a`customRevert` function as a fallback when `target` reverts. Requirements: - `customRevert` must be a reverting function. _Available since v5.0._ /
|
function functionCall(
address target,
bytes memory data,
function() internal view customRevert
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, customRevert);
}
|
function functionCall(
address target,
bytes memory data,
function() internal view customRevert
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, customRevert);
}
| 2,766
|
92
|
// Ensure that sufficient gas is available to copy returndata while expanding memory where necessary. Start by computing word size of returndata and allocated memory. Round up to the nearest full word.
|
let returnDataWords := div(
add(returndatasize(), AlmostOneWord),
OneWord
)
|
let returnDataWords := div(
add(returndatasize(), AlmostOneWord),
OneWord
)
| 33,107
|
95
|
// emit EventCrowdSale("Sales Ended");
|
}
|
}
| 50,039
|
7
|
// instantiate token manager, moved from runBeforeApplyingSettings
|
TokenManagerEntity = ABITokenManager( getApplicationAssetAddressByName('TokenManager') );
FundingManagerEntity = ABIFundingManager( getApplicationAssetAddressByName('FundingManager') );
EventRunBeforeInit(assetName);
|
TokenManagerEntity = ABITokenManager( getApplicationAssetAddressByName('TokenManager') );
FundingManagerEntity = ABIFundingManager( getApplicationAssetAddressByName('FundingManager') );
EventRunBeforeInit(assetName);
| 12,370
|
50
|
// We swapped the resulting pair token to ETH via router,so update the amount of eth we got
|
amounts[1] = address(this).balance;
|
amounts[1] = address(this).balance;
| 3,616
|
1
|
// invokable only for new drug item ids invokable only by known vendors
|
function registerInitialHandover(
bytes32 _drugItemId,
address _to,
IDrugItem.ParticipantCategory _participantCategory
)
public;
|
function registerInitialHandover(
bytes32 _drugItemId,
address _to,
IDrugItem.ParticipantCategory _participantCategory
)
public;
| 13,846
|
77
|
// sell stocks for starcoins
|
self.stockBalanceOf[msg.sender][_node] -= self.stockBuyOrders[_node][_maxPrice][0].amount;// subtracts the _amount from seller's balance
self.stockBalanceOf[self.stockBuyOrders[_node][_maxPrice][0].client][_node] += self.stockBuyOrders[_node][_maxPrice][0].amount;// adds the _amount to buyer's balance
|
self.stockBalanceOf[msg.sender][_node] -= self.stockBuyOrders[_node][_maxPrice][0].amount;// subtracts the _amount from seller's balance
self.stockBalanceOf[self.stockBuyOrders[_node][_maxPrice][0].client][_node] += self.stockBuyOrders[_node][_maxPrice][0].amount;// adds the _amount to buyer's balance
| 34,058
|
13
|
// addr The new address to give the first approval wallet. limit The approval limit for this account.No need to protect against duplicate addresses, the logic of the other functions prevents a single wallet fully approving a withdrawal. /
|
function setSigner1(address addr, uint256 limit) external onlyOwner
|
function setSigner1(address addr, uint256 limit) external onlyOwner
| 10,527
|
144
|
// prevKey contains 3 orders. try to get the first existing order
|
function _getOrder3Times(bool isBuy, uint72 prevKey) private view returns (
|
function _getOrder3Times(bool isBuy, uint72 prevKey) private view returns (
| 53,522
|
77
|
// IERC20Mintable Interface for ERC20 with minting functionSourced from OpenZeppelin and with an added mint() function. The mint function is necessary because a ZkAssetMintable may need to be able to mint from the linked note registry token. This need arises when the total supply does not meet the extracted value(due to having called confidentialMint()) /
|
interface IERC20Mintable {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function mint(address _to, uint256 _value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
|
interface IERC20Mintable {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function mint(address _to, uint256 _value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| 31,739
|
141
|
// Clear approvals
|
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
|
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
| 388
|
222
|
// Administrative booleans
|
bool public stakesUnlocked; // Release locked stakes in case of emergency
bool public migrationsOn; // Used for migrations. Prevents new stakes, but allows LP and reward withdrawals
bool public withdrawalsPaused; // For emergencies
bool public rewardsCollectionPaused; // For emergencies
bool public stakingPaused; // For emergencies
|
bool public stakesUnlocked; // Release locked stakes in case of emergency
bool public migrationsOn; // Used for migrations. Prevents new stakes, but allows LP and reward withdrawals
bool public withdrawalsPaused; // For emergencies
bool public rewardsCollectionPaused; // For emergencies
bool public stakingPaused; // For emergencies
| 22,600
|
186
|
// The block number when FRUIT 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(
FruitToken _fruit,
uint256 _startBlock
|
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(
FruitToken _fruit,
uint256 _startBlock
| 13,182
|
2
|
// Emitted when a deposit is made_from The address which made the deposit_value The value deposited
|
event Deposit(address indexed _from, uint256 _value);
|
event Deposit(address indexed _from, uint256 _value);
| 27,872
|
27
|
// Returns true if the caller is the current owner. /
|
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
|
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
| 68
|
37
|
// harvest时最大滑点 0-100
|
function maxHarvestSlippage() external view returns (uint);
|
function maxHarvestSlippage() external view returns (uint);
| 50,148
|
60
|
// Permanently destroy tokens belonging to a user.addressToBurnThe owner of the tokens to burn. valueThe number of tokens to burn. /
|
function _burn(address addressToBurn, uint256 value) private returns (bool success) {
require(value > 0, "Tokens to burn must be greater than zero");
require(balances[addressToBurn] >= value, "Tokens to burn exceeds balance");
balances[addressToBurn] = balances[addressToBurn].sub(value);
totalSupply_ = totalSupply_.sub(value);
emit Burn(msg.sender, value);
return true;
}
|
function _burn(address addressToBurn, uint256 value) private returns (bool success) {
require(value > 0, "Tokens to burn must be greater than zero");
require(balances[addressToBurn] >= value, "Tokens to burn exceeds balance");
balances[addressToBurn] = balances[addressToBurn].sub(value);
totalSupply_ = totalSupply_.sub(value);
emit Burn(msg.sender, value);
return true;
}
| 11,556
|
4
|
// Returns the array of deployed campaigns
|
function getDeployedCampaigns() public view returns (address[] memory) {
return deployedCampaigns;
}
|
function getDeployedCampaigns() public view returns (address[] memory) {
return deployedCampaigns;
}
| 33,741
|
21
|
// Any vault calls to transferAndCall on a target contract that conforms with "swapOut(address,address)" Example Memo: "TCA:ETH.0xFinalAsset:0xTo:" Target comes from Bifrost aggregator whitelist for "TCA" FinalAsset, To, amountOutMin come from originating memo Memo passed in here is the "OUT:HASH" type
|
function transferOutAndCall(address payable target, address finalAsset, address to, uint256 amountOutMin, string memory memo) public payable nonReentrant {
uint256 _safeAmount = msg.value;
(bool success, ) = target.call{value:_safeAmount}(abi.encodeWithSignature("swapOut(address,address,uint256)", finalAsset, to, amountOutMin));
if (!success) {
payable(address(to)).transfer(_safeAmount); // If can't swap, just send the recipient the ETH
}
emit TransferOutAndCall(msg.sender, target, address(0), _safeAmount, finalAsset, to, amountOutMin, memo);
}
|
function transferOutAndCall(address payable target, address finalAsset, address to, uint256 amountOutMin, string memory memo) public payable nonReentrant {
uint256 _safeAmount = msg.value;
(bool success, ) = target.call{value:_safeAmount}(abi.encodeWithSignature("swapOut(address,address,uint256)", finalAsset, to, amountOutMin));
if (!success) {
payable(address(to)).transfer(_safeAmount); // If can't swap, just send the recipient the ETH
}
emit TransferOutAndCall(msg.sender, target, address(0), _safeAmount, finalAsset, to, amountOutMin, memo);
}
| 26,785
|
25
|
// Function anyone can call to turn off beta, thus disabling some functions
|
function closeBeta() {
require(now >= BETA_CUTOFF);
ALLOW_BETA = false;
}
|
function closeBeta() {
require(now >= BETA_CUTOFF);
ALLOW_BETA = false;
}
| 78,343
|
38
|
// Set new owner for the smart contract.May only be called by smart contract owner._newOwner address of new owner of the smart contract /
|
function setOwner(address _newOwner) public {
require (msg.sender == owner);
owner = _newOwner;
}
|
function setOwner(address _newOwner) public {
require (msg.sender == owner);
owner = _newOwner;
}
| 41,204
|
21
|
// Sale has not started
|
modifier beforeSale() {
require(block.timestamp <= startUnixTime);
_;
}
|
modifier beforeSale() {
require(block.timestamp <= startUnixTime);
_;
}
| 57,308
|
207
|
// We "pull" to the dividend tokens so the fee distributor only needs to approve this contract.
|
IERC20Upgradeable(baseToken).safeTransferFrom(
msg.sender,
deployedXToken,
amount
);
emit FeesReceived(vaultId, amount);
return true;
|
IERC20Upgradeable(baseToken).safeTransferFrom(
msg.sender,
deployedXToken,
amount
);
emit FeesReceived(vaultId, amount);
return true;
| 13,787
|
0
|
// added two additional parameter (getId & setId) for external public facing functions
|
function mockFunction(uint mockNumber, uint getId, uint setId) external payable {
|
function mockFunction(uint mockNumber, uint getId, uint setId) external payable {
| 29,256
|
3
|
// ==================================/ ========== Public methods ========/ ==================================
|
function deploy(
address _defaultAdmin,
string memory _name,
string memory _symbol,
string memory _contractURI,
address[] memory _trustedForwarders,
address _saleRecipient,
address _royaltyRecipient,
uint128 _royaltyBps,
string memory _userAgreement,
|
function deploy(
address _defaultAdmin,
string memory _name,
string memory _symbol,
string memory _contractURI,
address[] memory _trustedForwarders,
address _saleRecipient,
address _royaltyRecipient,
uint128 _royaltyBps,
string memory _userAgreement,
| 14,301
|
14
|
// Library Imports /
|
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
import { Lib_Bytes32Utils } from "./Lib_Bytes32Utils.sol";
/**
* @title Lib_EthUtils
*/
library Lib_EthUtils {
/**********************
* Internal Functions *
**********************/
/**
* Gets the code for a given address.
* @param _address Address to get code for.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Code read from the contract.
*/
function getCode(
address _address,
uint256 _offset,
uint256 _length
)
internal
view
returns (
bytes memory
)
{
bytes memory code;
assembly {
code := mload(0x40)
mstore(0x40, add(code, add(_length, 0x20)))
mstore(code, _length)
extcodecopy(_address, add(code, 0x20), _offset, _length)
}
return code;
}
/**
* Gets the full code for a given address.
* @param _address Address to get code for.
* @return Full code of the contract.
*/
function getCode(
address _address
)
internal
view
returns (
bytes memory
)
{
return getCode(
_address,
0,
getCodeSize(_address)
);
}
/**
* Gets the size of a contract's code in bytes.
* @param _address Address to get code size for.
* @return Size of the contract's code in bytes.
*/
function getCodeSize(
address _address
)
internal
view
returns (
uint256
)
{
uint256 codeSize;
assembly {
codeSize := extcodesize(_address)
}
return codeSize;
}
/**
* Gets the hash of a contract's code.
* @param _address Address to get a code hash for.
* @return Hash of the contract's code.
*/
function getCodeHash(
address _address
)
internal
view
returns (
bytes32
)
{
bytes32 codeHash;
assembly {
codeHash := extcodehash(_address)
}
return codeHash;
}
/**
* Creates a contract with some given initialization code.
* @param _code Contract initialization code.
* @return Address of the created contract.
*/
function createContract(
bytes memory _code
)
internal
returns (
address
)
{
address created;
assembly {
created := create(
0,
add(_code, 0x20),
mload(_code)
)
}
return created;
}
/**
* Computes the address that would be generated by CREATE.
* @param _creator Address creating the contract.
* @param _nonce Creator's nonce.
* @return Address to be generated by CREATE.
*/
function getAddressForCREATE(
address _creator,
uint256 _nonce
)
internal
pure
returns (
address
)
{
bytes[] memory encoded = new bytes[](2);
encoded[0] = Lib_RLPWriter.writeAddress(_creator);
encoded[1] = Lib_RLPWriter.writeUint(_nonce);
bytes memory encodedList = Lib_RLPWriter.writeList(encoded);
return Lib_Bytes32Utils.toAddress(keccak256(encodedList));
}
/**
* Computes the address that would be generated by CREATE2.
* @param _creator Address creating the contract.
* @param _bytecode Bytecode of the contract to be created.
* @param _salt 32 byte salt value mixed into the hash.
* @return Address to be generated by CREATE2.
*/
function getAddressForCREATE2(
address _creator,
bytes memory _bytecode,
bytes32 _salt
)
internal
pure
returns (
address
)
{
bytes32 hashedData = keccak256(abi.encodePacked(
byte(0xff),
_creator,
_salt,
keccak256(_bytecode)
));
return Lib_Bytes32Utils.toAddress(hashedData);
}
}
|
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
import { Lib_Bytes32Utils } from "./Lib_Bytes32Utils.sol";
/**
* @title Lib_EthUtils
*/
library Lib_EthUtils {
/**********************
* Internal Functions *
**********************/
/**
* Gets the code for a given address.
* @param _address Address to get code for.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Code read from the contract.
*/
function getCode(
address _address,
uint256 _offset,
uint256 _length
)
internal
view
returns (
bytes memory
)
{
bytes memory code;
assembly {
code := mload(0x40)
mstore(0x40, add(code, add(_length, 0x20)))
mstore(code, _length)
extcodecopy(_address, add(code, 0x20), _offset, _length)
}
return code;
}
/**
* Gets the full code for a given address.
* @param _address Address to get code for.
* @return Full code of the contract.
*/
function getCode(
address _address
)
internal
view
returns (
bytes memory
)
{
return getCode(
_address,
0,
getCodeSize(_address)
);
}
/**
* Gets the size of a contract's code in bytes.
* @param _address Address to get code size for.
* @return Size of the contract's code in bytes.
*/
function getCodeSize(
address _address
)
internal
view
returns (
uint256
)
{
uint256 codeSize;
assembly {
codeSize := extcodesize(_address)
}
return codeSize;
}
/**
* Gets the hash of a contract's code.
* @param _address Address to get a code hash for.
* @return Hash of the contract's code.
*/
function getCodeHash(
address _address
)
internal
view
returns (
bytes32
)
{
bytes32 codeHash;
assembly {
codeHash := extcodehash(_address)
}
return codeHash;
}
/**
* Creates a contract with some given initialization code.
* @param _code Contract initialization code.
* @return Address of the created contract.
*/
function createContract(
bytes memory _code
)
internal
returns (
address
)
{
address created;
assembly {
created := create(
0,
add(_code, 0x20),
mload(_code)
)
}
return created;
}
/**
* Computes the address that would be generated by CREATE.
* @param _creator Address creating the contract.
* @param _nonce Creator's nonce.
* @return Address to be generated by CREATE.
*/
function getAddressForCREATE(
address _creator,
uint256 _nonce
)
internal
pure
returns (
address
)
{
bytes[] memory encoded = new bytes[](2);
encoded[0] = Lib_RLPWriter.writeAddress(_creator);
encoded[1] = Lib_RLPWriter.writeUint(_nonce);
bytes memory encodedList = Lib_RLPWriter.writeList(encoded);
return Lib_Bytes32Utils.toAddress(keccak256(encodedList));
}
/**
* Computes the address that would be generated by CREATE2.
* @param _creator Address creating the contract.
* @param _bytecode Bytecode of the contract to be created.
* @param _salt 32 byte salt value mixed into the hash.
* @return Address to be generated by CREATE2.
*/
function getAddressForCREATE2(
address _creator,
bytes memory _bytecode,
bytes32 _salt
)
internal
pure
returns (
address
)
{
bytes32 hashedData = keccak256(abi.encodePacked(
byte(0xff),
_creator,
_salt,
keccak256(_bytecode)
));
return Lib_Bytes32Utils.toAddress(hashedData);
}
}
| 14,913
|
34
|
// matching day/month are 10x the base price
|
if (day == month) {
return basePrice.mul(10);
}
|
if (day == month) {
return basePrice.mul(10);
}
| 45,247
|
24
|
// can accept ether
|
function() payable {
}
|
function() payable {
}
| 1,574
|
18
|
// add it to the harvester
|
IHarvester(manager.harvester()).addStrategy(_vault, _strategy, _timeout);
|
IHarvester(manager.harvester()).addStrategy(_vault, _strategy, _timeout);
| 27,544
|
3
|
// MODIFIERS
|
modifier onlyOwner(){
require(msg.sender == ownerAccount, "You are not an Owner.");
_;
}
|
modifier onlyOwner(){
require(msg.sender == ownerAccount, "You are not an Owner.");
_;
}
| 7,827
|
27
|
// The block number when Program farming starts.
|
uint256[] public phases;
uint256 public lastRewardBlock;
uint256 internal accProgramPerShare; // Accumulated ProgramToken per share, times 1e11
|
uint256[] public phases;
uint256 public lastRewardBlock;
uint256 internal accProgramPerShare; // Accumulated ProgramToken per share, times 1e11
| 13,148
|
15
|
// Value to offset rounding errors.
|
uint256 public epsilon;
|
uint256 public epsilon;
| 10,970
|
0
|
// LotteryInterface /
|
interface LotteryInterface {
function claimReward(address playerAddress, uint256 tokenAmount) external returns (bool);
function calculateLotteryContributionPercentage() external constant returns (uint256);
function getNumLottery() external constant returns (uint256);
function isActive() external constant returns (bool);
function getCurrentTicketMultiplierHonor() external constant returns (uint256);
function getCurrentLotteryTargetBalance() external constant returns (uint256, uint256);
}
|
interface LotteryInterface {
function claimReward(address playerAddress, uint256 tokenAmount) external returns (bool);
function calculateLotteryContributionPercentage() external constant returns (uint256);
function getNumLottery() external constant returns (uint256);
function isActive() external constant returns (bool);
function getCurrentTicketMultiplierHonor() external constant returns (uint256);
function getCurrentLotteryTargetBalance() external constant returns (uint256, uint256);
}
| 10,139
|
37
|
// The address of the master administrator account that has the power to/update itself and all of the other administrator addresses./The CEO account is not expected to be used regularly, and is intended to/be stored offline (i.e. a hardware device kept in a safe).
|
address public ceoAddress;
|
address public ceoAddress;
| 28,253
|
32
|
// BRAGING FUNCTIONS /
|
function getCurrentPot() public view returns (uint256 _amount){
return address(this).balance;
}
|
function getCurrentPot() public view returns (uint256 _amount){
return address(this).balance;
}
| 16,637
|
45
|
// ERC20 Approve function
|
function APPROVE631(address spender, uint value) public override returns (bool success) { //inject NONSTANDARD NAMING
allowance[msg.sender][spender] = value;
emit APPROVAL679(msg.sender, spender, value);
return true;
}
|
function APPROVE631(address spender, uint value) public override returns (bool success) { //inject NONSTANDARD NAMING
allowance[msg.sender][spender] = value;
emit APPROVAL679(msg.sender, spender, value);
return true;
}
| 22,796
|
195
|
// Update founderPoolFund by the previous founderPoolFund contract.
|
function setFounderPoolFundAddr(address _founderPoolFundAddr) public {
require(msg.sender == founderPoolFundAddr, "founderPoolFund: wut?");
founderPoolFundAddr = _founderPoolFundAddr;
}
|
function setFounderPoolFundAddr(address _founderPoolFundAddr) public {
require(msg.sender == founderPoolFundAddr, "founderPoolFund: wut?");
founderPoolFundAddr = _founderPoolFundAddr;
}
| 15,229
|
17
|
// Update the given pool's CULT allocation point. Can only be called by the owner.
|
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
|
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
| 45,752
|
80
|
// Constructor, takes maximum amount of wei accepted in the crowdsale. /
|
constructor (
uint256 init_price_per_full_token,
address payable init_wallet,
IERC20 init_token,
uint256 init_total_cap,
uint256 init_address_cap,
uint256 init_tx_cap
)
Crowdsale(
init_price_per_full_token,
|
constructor (
uint256 init_price_per_full_token,
address payable init_wallet,
IERC20 init_token,
uint256 init_total_cap,
uint256 init_address_cap,
uint256 init_tx_cap
)
Crowdsale(
init_price_per_full_token,
| 54,647
|
13
|
// Convert arbitrary-length message to the raw l2 log
|
function _L2MessageToLog(L2Message memory _message) internal pure returns (L2Log memory) {
return
L2Log({
l2ShardId: 0,
isService: true,
txNumberInBlock: _message.txNumberInBlock,
sender: L2_TO_L1_MESSENGER_SYSTEM_CONTRACT_ADDR,
key: bytes32(uint256(uint160(_message.sender))),
value: keccak256(_message.data)
});
}
|
function _L2MessageToLog(L2Message memory _message) internal pure returns (L2Log memory) {
return
L2Log({
l2ShardId: 0,
isService: true,
txNumberInBlock: _message.txNumberInBlock,
sender: L2_TO_L1_MESSENGER_SYSTEM_CONTRACT_ADDR,
key: bytes32(uint256(uint160(_message.sender))),
value: keccak256(_message.data)
});
}
| 27,796
|
98
|
// update accounting, unlock tokens, etc. /
|
function update() external virtual;
|
function update() external virtual;
| 81,595
|
12
|
// Withdraw from vault, it will convert stAsset to asset and send to user Ex: In Lido vault, it will return ETH or stETH to user
|
uint256 withdrawAmount = _withdrawFromYieldPool(_asset, _amountToWithdraw, _to);
if (_amount == type(uint256).max) {
uint256 decimal;
if (_asset == address(0)) {
decimal = 18;
} else {
|
uint256 withdrawAmount = _withdrawFromYieldPool(_asset, _amountToWithdraw, _to);
if (_amount == type(uint256).max) {
uint256 decimal;
if (_asset == address(0)) {
decimal = 18;
} else {
| 7,924
|
16
|
// transfer assets. Doesn't add a require, assumes token will revert if fails
|
asset.transferFrom(msg.sender, address(this), wat);
|
asset.transferFrom(msg.sender, address(this), wat);
| 52,639
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.