contract_name
stringlengths 1
61
| file_path
stringlengths 5
50.4k
| contract_address
stringlengths 42
42
| language
stringclasses 1
value | class_name
stringlengths 1
61
| class_code
stringlengths 4
330k
| class_documentation
stringlengths 0
29.1k
| class_documentation_type
stringclasses 6
values | func_name
stringlengths 0
62
| func_code
stringlengths 1
303k
| func_documentation
stringlengths 2
14.9k
| func_documentation_type
stringclasses 4
values | compiler_version
stringlengths 15
42
| license_type
stringclasses 14
values | swarm_source
stringlengths 0
71
| meta
dict | __index_level_0__
int64 0
60.4k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GmStudioMindTheGap | contracts/collections/MindTheGap/MindTheGap.sol | 0x0e42ffbac75bcc30cd0015f8aaa608539ba35fbb | Solidity | GmStudioMindTheGap | contract GmStudioMindTheGap is
ERC721Common,
ReentrancyGuard,
ERC2981SinglePercentual
{
using EnumerableSet for EnumerableSet.AddressSet;
using SignatureChecker for EnumerableSet.AddressSet;
using Address for address payable;
/// @notice Price for minting
uint256 public constant MINT_PRICE = 0.15 ether;
/// @notice Splits payments between the Studio and the artist.
address payable public immutable paymentSplitter;
/// @notice Splits payments between the Studio and the artist.
address payable public immutable paymentSplitterRoyalties;
/// @notice Total maximum amount of tokens
uint32 public constant MAX_NUM_TOKENS = 999;
/// @notice Max number of mints per transaction.
/// @dev Only for public mints.
uint32 public constant MAX_MINT_PER_TX = 1;
/// @notice Number of mints throught the signed minting interface.
uint32 internal constant NUM_SIGNED_MINTS = 300;
/// @notice Number of mints for reserved the studio.
uint32 internal constant NUM_RESERVED_MINTS = 1;
/// @notice Currently minted supply of tokens
uint32 public totalSupply;
/// @notice Counter for the remaining signed mints
uint32 internal numSignedMintsRemaining;
/// @notice Locks the mintReserve function
bool internal reserveMinted;
/// @notice Locks the code storing function
bool internal codeStoreLocked;
/// @notice Timestamps to enables/eisables minting interfaces
/// @dev The following order is assumed
/// signedMintOpeningTimestamp < publicMintOpeningTimestamp < mintClosingTimestamp
struct MintConfig {
uint64 signedMintOpeningTimestamp;
uint64 publicMintOpeningTimestamp;
uint64 mintClosingTimestamp;
}
/// @notice The minting configuration
MintConfig public mintConfig;
/// @notice Stores the number of tokens minted from a signature
/// @dev Used in mintSigned
mapping(bytes32 => uint256) public numSignedMintsFrom;
/// @notice Signature signers for the early access phase.
/// @dev Removing signers invalidates the corresponding signatures.
EnumerableSet.AddressSet private _signers;
/// @notice tokenURI() base path.
/// @dev Without trailing slash
string internal _baseTokenURI;
constructor(
address newOwner,
address signer,
string memory baseTokenURI,
address[] memory payees,
uint256[] memory shares,
uint256[] memory sharesRoyalties
) ERC721Common("Mind the Gap by MountVitruvius", "MTG") {
_signers.add(signer);
_baseTokenURI = baseTokenURI;
paymentSplitter = payable(
PaymentSplitterDeployer.instance().deploy(payees, shares)
);
paymentSplitterRoyalties = payable(
PaymentSplitterDeployer.instance().deploy(payees, sharesRoyalties)
);
_setRoyaltyPercentage(750);
_setRoyaltyReceiver(paymentSplitterRoyalties);
numSignedMintsRemaining = NUM_SIGNED_MINTS;
transferOwnership(newOwner);
}
// -------------------------------------------------------------------------
//
// Minting
//
// -------------------------------------------------------------------------
/// @notice Toggle minting relevant flags.
function setMintConfig(MintConfig calldata config) external onlyOwner {
mintConfig = config;
}
/// @dev Reverts if we are not in the signed minting window or the if
/// `mintConfig` has not been set yet.
modifier onlyDuringSignedMintingPeriod() {
if (
block.timestamp < mintConfig.signedMintOpeningTimestamp ||
block.timestamp > mintConfig.publicMintOpeningTimestamp
) revert MintDisabled();
_;
}
/// @dev Reverts if we are not in the public minting window or the if
/// `mintConfig` has not been set yet.
modifier onlyDuringPublicMintingPeriod() {
if (
block.timestamp < mintConfig.publicMintOpeningTimestamp ||
block.timestamp > mintConfig.mintClosingTimestamp
) revert MintDisabled();
_;
}
/// @notice Mints tokens to a given address using a signed message.
/// @dev The minter might be different than the receiver.
/// @param to Token receiver
/// @param num Number of tokens to be minted.
/// @param numMax Max number of tokens that can be minted to the receiver
/// @param signature to prove that the receiver is allowed to get mints.
/// @dev The signed messages is generated from `to || numMax`.
function mintSigned(
address to,
uint32 num,
uint32 numMax,
uint256 nonce,
bytes calldata signature
) external payable nonReentrant onlyDuringSignedMintingPeriod {
bytes32 message = ECDSA.toEthSignedMessageHash(
abi.encodePacked(to, numMax, nonce)
);
if (num + numSignedMintsFrom[message] > numMax)
revert TooManyMintsRequested();
if (num > numSignedMintsRemaining)
revert InsufficientTokensRemanining();
if (num * MINT_PRICE != msg.value) revert InvalidPayment();
_signers.requireValidSignature(message, signature);
numSignedMintsFrom[message] += num;
numSignedMintsRemaining -= num;
_processPayment();
_processMint(to, num);
}
/// @notice Mints tokens to a given address.
/// @dev The minter might be different than the receiver.
/// @param to Token receiver
/// @param num Number of tokens to be minted.
function mintPublic(address to, uint32 num)
external
payable
nonReentrant
onlyDuringPublicMintingPeriod
{
if (num > MAX_MINT_PER_TX) revert TooManyMintsRequested();
uint256 numRemaining = MAX_NUM_TOKENS - totalSupply;
if (num > numRemaining) revert InsufficientTokensRemanining();
if (num * MINT_PRICE != msg.value) revert InvalidPayment();
_processPayment();
_processMint(to, num);
}
/// @notice Mints the DAO allocated tokens.
/// @dev The minter might be different than the receiver.
/// @param to Token receiver
function mintReserve(address to) external onlyOwner {
if (reserveMinted) revert MintDisabled();
reserveMinted = true;
_processMint(to, NUM_RESERVED_MINTS);
}
/// @notice Mints new tokens for the recipient.
function _processMint(address to, uint32 num) internal {
uint32 supply = totalSupply;
for (uint256 i = 0; i < num; i++) {
if (MAX_NUM_TOKENS <= supply) revert SoldOut();
ERC721._safeMint(to, supply);
supply++;
}
totalSupply = supply;
}
// -------------------------------------------------------------------------
//
// Signature validataion
//
// -------------------------------------------------------------------------
/// @notice Removes and adds addresses to the set of allowed signers.
/// @dev Removal is performed before addition.
function changeSigners(
address[] calldata delSigners,
address[] calldata addSigners
) external onlyOwner {
for (uint256 idx; idx < delSigners.length; ++idx) {
_signers.remove(delSigners[idx]);
}
for (uint256 idx; idx < addSigners.length; ++idx) {
_signers.add(addSigners[idx]);
}
}
/// @notice Returns the addresses that are used for signature verification
function getSigners() external view returns (address[] memory signers) {
uint256 len = _signers.length();
signers = new address[](len);
for (uint256 idx = 0; idx < len; ++idx) {
signers[idx] = _signers.at(idx);
}
}
// -------------------------------------------------------------------------
//
// Payment
//
// -------------------------------------------------------------------------
/// @notice Default function for receiving funds
/// @dev This enables the contract to be used as splitter for royalties.
receive() external payable {
_processPayment();
}
/// @notice Processes an incoming payment and sends it to the payment
/// splitter.
function _processPayment() internal {
paymentSplitter.sendValue(msg.value);
}
// -------------------------------------------------------------------------
//
// Metadata
//
// -------------------------------------------------------------------------
/// @notice This function is intended to store (genart) code onchain in
// calldata.
function storeCode(bytes calldata) external {
if (
codeStoreLocked ||
(mintConfig.signedMintOpeningTimestamp > 0 &&
block.timestamp > mintConfig.signedMintOpeningTimestamp)
) revert CodeStoreLocked();
codeStoreLocked = true;
}
/// @notice Change tokenURI() base path.
/// @param uri The new base path (must not contain trailing slash)
function setBaseTokenURI(string calldata uri) external onlyOwner {
_baseTokenURI = uri;
}
/// @notice Returns the URI for token metadata.
function tokenURI(uint256 tokenId)
public
view
override
tokenExists(tokenId)
returns (string memory)
{
return
string(
abi.encodePacked(
_baseTokenURI,
"/",
Strings.toString(tokenId),
".json"
)
);
}
// -------------------------------------------------------------------------
//
// Internals
//
// -------------------------------------------------------------------------
/// @dev See {IERC165-supportsInterface}.
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Common, ERC2981)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
// -------------------------------------------------------------------------
//
// Errors
//
// -------------------------------------------------------------------------
error MintDisabled();
error TooManyMintsRequested();
error InsufficientTokensRemanining();
error InvalidPayment();
error SoldOut();
error InvalidSignature();
error ExeedsOwnerAllocation();
error NotAllowedToOwnerMint();
error NotAllowToChangeAddress();
error CodeStoreLocked();
} | // __ __ __
// | \ | \ \
// ______ ______ ____ _______ _| ββ_ __ __ ____| ββ\ββ ______
// / \| \ \ / \ ββ \ | \ | \/ ββ \/ \
// | ββββββ\ ββββββ\ββββ\ | βββββββ\ββββββ | ββ | ββ βββββββ ββ ββββββ\
// | ββ | ββ ββ | ββ | ββ \ββ \ | ββ __| ββ | ββ ββ | ββ ββ ββ | ββ
// | ββ__| ββ ββ | ββ | ββ__ _\ββββββ\ | ββ| \ ββ__/ ββ ββ__| ββ ββ ββ__/ ββ
// \ββ ββ ββ | ββ | ββ \ | ββ \ββ ββ\ββ ββ\ββ ββ ββ\ββ ββ
// _\βββββββ\ββ \ββ \ββ\ββ \βββββββ \ββββ \ββββββ \βββββββ\ββ \ββββββ
// | \__| ββ
// \ββ ββ
// \ββββββ
// | LineComment | storeCode | function storeCode(bytes calldata) external {
if (
codeStoreLocked ||
(mintConfig.signedMintOpeningTimestamp > 0 &&
block.timestamp > mintConfig.signedMintOpeningTimestamp)
) revert CodeStoreLocked();
codeStoreLocked = true;
}
| // calldata. | LineComment | v0.8.11+commit.d7f03943 | Unlicense | {
"func_code_index": [
8679,
8977
]
} | 2,107 |
|
GmStudioMindTheGap | contracts/collections/MindTheGap/MindTheGap.sol | 0x0e42ffbac75bcc30cd0015f8aaa608539ba35fbb | Solidity | GmStudioMindTheGap | contract GmStudioMindTheGap is
ERC721Common,
ReentrancyGuard,
ERC2981SinglePercentual
{
using EnumerableSet for EnumerableSet.AddressSet;
using SignatureChecker for EnumerableSet.AddressSet;
using Address for address payable;
/// @notice Price for minting
uint256 public constant MINT_PRICE = 0.15 ether;
/// @notice Splits payments between the Studio and the artist.
address payable public immutable paymentSplitter;
/// @notice Splits payments between the Studio and the artist.
address payable public immutable paymentSplitterRoyalties;
/// @notice Total maximum amount of tokens
uint32 public constant MAX_NUM_TOKENS = 999;
/// @notice Max number of mints per transaction.
/// @dev Only for public mints.
uint32 public constant MAX_MINT_PER_TX = 1;
/// @notice Number of mints throught the signed minting interface.
uint32 internal constant NUM_SIGNED_MINTS = 300;
/// @notice Number of mints for reserved the studio.
uint32 internal constant NUM_RESERVED_MINTS = 1;
/// @notice Currently minted supply of tokens
uint32 public totalSupply;
/// @notice Counter for the remaining signed mints
uint32 internal numSignedMintsRemaining;
/// @notice Locks the mintReserve function
bool internal reserveMinted;
/// @notice Locks the code storing function
bool internal codeStoreLocked;
/// @notice Timestamps to enables/eisables minting interfaces
/// @dev The following order is assumed
/// signedMintOpeningTimestamp < publicMintOpeningTimestamp < mintClosingTimestamp
struct MintConfig {
uint64 signedMintOpeningTimestamp;
uint64 publicMintOpeningTimestamp;
uint64 mintClosingTimestamp;
}
/// @notice The minting configuration
MintConfig public mintConfig;
/// @notice Stores the number of tokens minted from a signature
/// @dev Used in mintSigned
mapping(bytes32 => uint256) public numSignedMintsFrom;
/// @notice Signature signers for the early access phase.
/// @dev Removing signers invalidates the corresponding signatures.
EnumerableSet.AddressSet private _signers;
/// @notice tokenURI() base path.
/// @dev Without trailing slash
string internal _baseTokenURI;
constructor(
address newOwner,
address signer,
string memory baseTokenURI,
address[] memory payees,
uint256[] memory shares,
uint256[] memory sharesRoyalties
) ERC721Common("Mind the Gap by MountVitruvius", "MTG") {
_signers.add(signer);
_baseTokenURI = baseTokenURI;
paymentSplitter = payable(
PaymentSplitterDeployer.instance().deploy(payees, shares)
);
paymentSplitterRoyalties = payable(
PaymentSplitterDeployer.instance().deploy(payees, sharesRoyalties)
);
_setRoyaltyPercentage(750);
_setRoyaltyReceiver(paymentSplitterRoyalties);
numSignedMintsRemaining = NUM_SIGNED_MINTS;
transferOwnership(newOwner);
}
// -------------------------------------------------------------------------
//
// Minting
//
// -------------------------------------------------------------------------
/// @notice Toggle minting relevant flags.
function setMintConfig(MintConfig calldata config) external onlyOwner {
mintConfig = config;
}
/// @dev Reverts if we are not in the signed minting window or the if
/// `mintConfig` has not been set yet.
modifier onlyDuringSignedMintingPeriod() {
if (
block.timestamp < mintConfig.signedMintOpeningTimestamp ||
block.timestamp > mintConfig.publicMintOpeningTimestamp
) revert MintDisabled();
_;
}
/// @dev Reverts if we are not in the public minting window or the if
/// `mintConfig` has not been set yet.
modifier onlyDuringPublicMintingPeriod() {
if (
block.timestamp < mintConfig.publicMintOpeningTimestamp ||
block.timestamp > mintConfig.mintClosingTimestamp
) revert MintDisabled();
_;
}
/// @notice Mints tokens to a given address using a signed message.
/// @dev The minter might be different than the receiver.
/// @param to Token receiver
/// @param num Number of tokens to be minted.
/// @param numMax Max number of tokens that can be minted to the receiver
/// @param signature to prove that the receiver is allowed to get mints.
/// @dev The signed messages is generated from `to || numMax`.
function mintSigned(
address to,
uint32 num,
uint32 numMax,
uint256 nonce,
bytes calldata signature
) external payable nonReentrant onlyDuringSignedMintingPeriod {
bytes32 message = ECDSA.toEthSignedMessageHash(
abi.encodePacked(to, numMax, nonce)
);
if (num + numSignedMintsFrom[message] > numMax)
revert TooManyMintsRequested();
if (num > numSignedMintsRemaining)
revert InsufficientTokensRemanining();
if (num * MINT_PRICE != msg.value) revert InvalidPayment();
_signers.requireValidSignature(message, signature);
numSignedMintsFrom[message] += num;
numSignedMintsRemaining -= num;
_processPayment();
_processMint(to, num);
}
/// @notice Mints tokens to a given address.
/// @dev The minter might be different than the receiver.
/// @param to Token receiver
/// @param num Number of tokens to be minted.
function mintPublic(address to, uint32 num)
external
payable
nonReentrant
onlyDuringPublicMintingPeriod
{
if (num > MAX_MINT_PER_TX) revert TooManyMintsRequested();
uint256 numRemaining = MAX_NUM_TOKENS - totalSupply;
if (num > numRemaining) revert InsufficientTokensRemanining();
if (num * MINT_PRICE != msg.value) revert InvalidPayment();
_processPayment();
_processMint(to, num);
}
/// @notice Mints the DAO allocated tokens.
/// @dev The minter might be different than the receiver.
/// @param to Token receiver
function mintReserve(address to) external onlyOwner {
if (reserveMinted) revert MintDisabled();
reserveMinted = true;
_processMint(to, NUM_RESERVED_MINTS);
}
/// @notice Mints new tokens for the recipient.
function _processMint(address to, uint32 num) internal {
uint32 supply = totalSupply;
for (uint256 i = 0; i < num; i++) {
if (MAX_NUM_TOKENS <= supply) revert SoldOut();
ERC721._safeMint(to, supply);
supply++;
}
totalSupply = supply;
}
// -------------------------------------------------------------------------
//
// Signature validataion
//
// -------------------------------------------------------------------------
/// @notice Removes and adds addresses to the set of allowed signers.
/// @dev Removal is performed before addition.
function changeSigners(
address[] calldata delSigners,
address[] calldata addSigners
) external onlyOwner {
for (uint256 idx; idx < delSigners.length; ++idx) {
_signers.remove(delSigners[idx]);
}
for (uint256 idx; idx < addSigners.length; ++idx) {
_signers.add(addSigners[idx]);
}
}
/// @notice Returns the addresses that are used for signature verification
function getSigners() external view returns (address[] memory signers) {
uint256 len = _signers.length();
signers = new address[](len);
for (uint256 idx = 0; idx < len; ++idx) {
signers[idx] = _signers.at(idx);
}
}
// -------------------------------------------------------------------------
//
// Payment
//
// -------------------------------------------------------------------------
/// @notice Default function for receiving funds
/// @dev This enables the contract to be used as splitter for royalties.
receive() external payable {
_processPayment();
}
/// @notice Processes an incoming payment and sends it to the payment
/// splitter.
function _processPayment() internal {
paymentSplitter.sendValue(msg.value);
}
// -------------------------------------------------------------------------
//
// Metadata
//
// -------------------------------------------------------------------------
/// @notice This function is intended to store (genart) code onchain in
// calldata.
function storeCode(bytes calldata) external {
if (
codeStoreLocked ||
(mintConfig.signedMintOpeningTimestamp > 0 &&
block.timestamp > mintConfig.signedMintOpeningTimestamp)
) revert CodeStoreLocked();
codeStoreLocked = true;
}
/// @notice Change tokenURI() base path.
/// @param uri The new base path (must not contain trailing slash)
function setBaseTokenURI(string calldata uri) external onlyOwner {
_baseTokenURI = uri;
}
/// @notice Returns the URI for token metadata.
function tokenURI(uint256 tokenId)
public
view
override
tokenExists(tokenId)
returns (string memory)
{
return
string(
abi.encodePacked(
_baseTokenURI,
"/",
Strings.toString(tokenId),
".json"
)
);
}
// -------------------------------------------------------------------------
//
// Internals
//
// -------------------------------------------------------------------------
/// @dev See {IERC165-supportsInterface}.
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Common, ERC2981)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
// -------------------------------------------------------------------------
//
// Errors
//
// -------------------------------------------------------------------------
error MintDisabled();
error TooManyMintsRequested();
error InsufficientTokensRemanining();
error InvalidPayment();
error SoldOut();
error InvalidSignature();
error ExeedsOwnerAllocation();
error NotAllowedToOwnerMint();
error NotAllowToChangeAddress();
error CodeStoreLocked();
} | // __ __ __
// | \ | \ \
// ______ ______ ____ _______ _| ββ_ __ __ ____| ββ\ββ ______
// / \| \ \ / \ ββ \ | \ | \/ ββ \/ \
// | ββββββ\ ββββββ\ββββ\ | βββββββ\ββββββ | ββ | ββ βββββββ ββ ββββββ\
// | ββ | ββ ββ | ββ | ββ \ββ \ | ββ __| ββ | ββ ββ | ββ ββ ββ | ββ
// | ββ__| ββ ββ | ββ | ββ__ _\ββββββ\ | ββ| \ ββ__/ ββ ββ__| ββ ββ ββ__/ ββ
// \ββ ββ ββ | ββ | ββ \ | ββ \ββ ββ\ββ ββ\ββ ββ ββ\ββ ββ
// _\βββββββ\ββ \ββ \ββ\ββ \βββββββ \ββββ \ββββββ \βββββββ\ββ \ββββββ
// | \__| ββ
// \ββ ββ
// \ββββββ
// | LineComment | setBaseTokenURI | function setBaseTokenURI(string calldata uri) external onlyOwner {
_baseTokenURI = uri;
}
| /// @notice Change tokenURI() base path.
/// @param uri The new base path (must not contain trailing slash) | NatSpecSingleLine | v0.8.11+commit.d7f03943 | Unlicense | {
"func_code_index": [
9095,
9200
]
} | 2,108 |
|
GmStudioMindTheGap | contracts/collections/MindTheGap/MindTheGap.sol | 0x0e42ffbac75bcc30cd0015f8aaa608539ba35fbb | Solidity | GmStudioMindTheGap | contract GmStudioMindTheGap is
ERC721Common,
ReentrancyGuard,
ERC2981SinglePercentual
{
using EnumerableSet for EnumerableSet.AddressSet;
using SignatureChecker for EnumerableSet.AddressSet;
using Address for address payable;
/// @notice Price for minting
uint256 public constant MINT_PRICE = 0.15 ether;
/// @notice Splits payments between the Studio and the artist.
address payable public immutable paymentSplitter;
/// @notice Splits payments between the Studio and the artist.
address payable public immutable paymentSplitterRoyalties;
/// @notice Total maximum amount of tokens
uint32 public constant MAX_NUM_TOKENS = 999;
/// @notice Max number of mints per transaction.
/// @dev Only for public mints.
uint32 public constant MAX_MINT_PER_TX = 1;
/// @notice Number of mints throught the signed minting interface.
uint32 internal constant NUM_SIGNED_MINTS = 300;
/// @notice Number of mints for reserved the studio.
uint32 internal constant NUM_RESERVED_MINTS = 1;
/// @notice Currently minted supply of tokens
uint32 public totalSupply;
/// @notice Counter for the remaining signed mints
uint32 internal numSignedMintsRemaining;
/// @notice Locks the mintReserve function
bool internal reserveMinted;
/// @notice Locks the code storing function
bool internal codeStoreLocked;
/// @notice Timestamps to enables/eisables minting interfaces
/// @dev The following order is assumed
/// signedMintOpeningTimestamp < publicMintOpeningTimestamp < mintClosingTimestamp
struct MintConfig {
uint64 signedMintOpeningTimestamp;
uint64 publicMintOpeningTimestamp;
uint64 mintClosingTimestamp;
}
/// @notice The minting configuration
MintConfig public mintConfig;
/// @notice Stores the number of tokens minted from a signature
/// @dev Used in mintSigned
mapping(bytes32 => uint256) public numSignedMintsFrom;
/// @notice Signature signers for the early access phase.
/// @dev Removing signers invalidates the corresponding signatures.
EnumerableSet.AddressSet private _signers;
/// @notice tokenURI() base path.
/// @dev Without trailing slash
string internal _baseTokenURI;
constructor(
address newOwner,
address signer,
string memory baseTokenURI,
address[] memory payees,
uint256[] memory shares,
uint256[] memory sharesRoyalties
) ERC721Common("Mind the Gap by MountVitruvius", "MTG") {
_signers.add(signer);
_baseTokenURI = baseTokenURI;
paymentSplitter = payable(
PaymentSplitterDeployer.instance().deploy(payees, shares)
);
paymentSplitterRoyalties = payable(
PaymentSplitterDeployer.instance().deploy(payees, sharesRoyalties)
);
_setRoyaltyPercentage(750);
_setRoyaltyReceiver(paymentSplitterRoyalties);
numSignedMintsRemaining = NUM_SIGNED_MINTS;
transferOwnership(newOwner);
}
// -------------------------------------------------------------------------
//
// Minting
//
// -------------------------------------------------------------------------
/// @notice Toggle minting relevant flags.
function setMintConfig(MintConfig calldata config) external onlyOwner {
mintConfig = config;
}
/// @dev Reverts if we are not in the signed minting window or the if
/// `mintConfig` has not been set yet.
modifier onlyDuringSignedMintingPeriod() {
if (
block.timestamp < mintConfig.signedMintOpeningTimestamp ||
block.timestamp > mintConfig.publicMintOpeningTimestamp
) revert MintDisabled();
_;
}
/// @dev Reverts if we are not in the public minting window or the if
/// `mintConfig` has not been set yet.
modifier onlyDuringPublicMintingPeriod() {
if (
block.timestamp < mintConfig.publicMintOpeningTimestamp ||
block.timestamp > mintConfig.mintClosingTimestamp
) revert MintDisabled();
_;
}
/// @notice Mints tokens to a given address using a signed message.
/// @dev The minter might be different than the receiver.
/// @param to Token receiver
/// @param num Number of tokens to be minted.
/// @param numMax Max number of tokens that can be minted to the receiver
/// @param signature to prove that the receiver is allowed to get mints.
/// @dev The signed messages is generated from `to || numMax`.
function mintSigned(
address to,
uint32 num,
uint32 numMax,
uint256 nonce,
bytes calldata signature
) external payable nonReentrant onlyDuringSignedMintingPeriod {
bytes32 message = ECDSA.toEthSignedMessageHash(
abi.encodePacked(to, numMax, nonce)
);
if (num + numSignedMintsFrom[message] > numMax)
revert TooManyMintsRequested();
if (num > numSignedMintsRemaining)
revert InsufficientTokensRemanining();
if (num * MINT_PRICE != msg.value) revert InvalidPayment();
_signers.requireValidSignature(message, signature);
numSignedMintsFrom[message] += num;
numSignedMintsRemaining -= num;
_processPayment();
_processMint(to, num);
}
/// @notice Mints tokens to a given address.
/// @dev The minter might be different than the receiver.
/// @param to Token receiver
/// @param num Number of tokens to be minted.
function mintPublic(address to, uint32 num)
external
payable
nonReentrant
onlyDuringPublicMintingPeriod
{
if (num > MAX_MINT_PER_TX) revert TooManyMintsRequested();
uint256 numRemaining = MAX_NUM_TOKENS - totalSupply;
if (num > numRemaining) revert InsufficientTokensRemanining();
if (num * MINT_PRICE != msg.value) revert InvalidPayment();
_processPayment();
_processMint(to, num);
}
/// @notice Mints the DAO allocated tokens.
/// @dev The minter might be different than the receiver.
/// @param to Token receiver
function mintReserve(address to) external onlyOwner {
if (reserveMinted) revert MintDisabled();
reserveMinted = true;
_processMint(to, NUM_RESERVED_MINTS);
}
/// @notice Mints new tokens for the recipient.
function _processMint(address to, uint32 num) internal {
uint32 supply = totalSupply;
for (uint256 i = 0; i < num; i++) {
if (MAX_NUM_TOKENS <= supply) revert SoldOut();
ERC721._safeMint(to, supply);
supply++;
}
totalSupply = supply;
}
// -------------------------------------------------------------------------
//
// Signature validataion
//
// -------------------------------------------------------------------------
/// @notice Removes and adds addresses to the set of allowed signers.
/// @dev Removal is performed before addition.
function changeSigners(
address[] calldata delSigners,
address[] calldata addSigners
) external onlyOwner {
for (uint256 idx; idx < delSigners.length; ++idx) {
_signers.remove(delSigners[idx]);
}
for (uint256 idx; idx < addSigners.length; ++idx) {
_signers.add(addSigners[idx]);
}
}
/// @notice Returns the addresses that are used for signature verification
function getSigners() external view returns (address[] memory signers) {
uint256 len = _signers.length();
signers = new address[](len);
for (uint256 idx = 0; idx < len; ++idx) {
signers[idx] = _signers.at(idx);
}
}
// -------------------------------------------------------------------------
//
// Payment
//
// -------------------------------------------------------------------------
/// @notice Default function for receiving funds
/// @dev This enables the contract to be used as splitter for royalties.
receive() external payable {
_processPayment();
}
/// @notice Processes an incoming payment and sends it to the payment
/// splitter.
function _processPayment() internal {
paymentSplitter.sendValue(msg.value);
}
// -------------------------------------------------------------------------
//
// Metadata
//
// -------------------------------------------------------------------------
/// @notice This function is intended to store (genart) code onchain in
// calldata.
function storeCode(bytes calldata) external {
if (
codeStoreLocked ||
(mintConfig.signedMintOpeningTimestamp > 0 &&
block.timestamp > mintConfig.signedMintOpeningTimestamp)
) revert CodeStoreLocked();
codeStoreLocked = true;
}
/// @notice Change tokenURI() base path.
/// @param uri The new base path (must not contain trailing slash)
function setBaseTokenURI(string calldata uri) external onlyOwner {
_baseTokenURI = uri;
}
/// @notice Returns the URI for token metadata.
function tokenURI(uint256 tokenId)
public
view
override
tokenExists(tokenId)
returns (string memory)
{
return
string(
abi.encodePacked(
_baseTokenURI,
"/",
Strings.toString(tokenId),
".json"
)
);
}
// -------------------------------------------------------------------------
//
// Internals
//
// -------------------------------------------------------------------------
/// @dev See {IERC165-supportsInterface}.
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Common, ERC2981)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
// -------------------------------------------------------------------------
//
// Errors
//
// -------------------------------------------------------------------------
error MintDisabled();
error TooManyMintsRequested();
error InsufficientTokensRemanining();
error InvalidPayment();
error SoldOut();
error InvalidSignature();
error ExeedsOwnerAllocation();
error NotAllowedToOwnerMint();
error NotAllowToChangeAddress();
error CodeStoreLocked();
} | // __ __ __
// | \ | \ \
// ______ ______ ____ _______ _| ββ_ __ __ ____| ββ\ββ ______
// / \| \ \ / \ ββ \ | \ | \/ ββ \/ \
// | ββββββ\ ββββββ\ββββ\ | βββββββ\ββββββ | ββ | ββ βββββββ ββ ββββββ\
// | ββ | ββ ββ | ββ | ββ \ββ \ | ββ __| ββ | ββ ββ | ββ ββ ββ | ββ
// | ββ__| ββ ββ | ββ | ββ__ _\ββββββ\ | ββ| \ ββ__/ ββ ββ__| ββ ββ ββ__/ ββ
// \ββ ββ ββ | ββ | ββ \ | ββ \ββ ββ\ββ ββ\ββ ββ ββ\ββ ββ
// _\βββββββ\ββ \ββ \ββ\ββ \βββββββ \ββββ \ββββββ \βββββββ\ββ \ββββββ
// | \__| ββ
// \ββ ββ
// \ββββββ
// | LineComment | tokenURI | function tokenURI(uint256 tokenId)
public
view
override
tokenExists(tokenId)
returns (string memory)
{
return
string(
abi.encodePacked(
_baseTokenURI,
"/",
Strings.toString(tokenId),
".json"
)
);
}
| /// @notice Returns the URI for token metadata. | NatSpecSingleLine | v0.8.11+commit.d7f03943 | Unlicense | {
"func_code_index": [
9254,
9647
]
} | 2,109 |
|
GmStudioMindTheGap | contracts/collections/MindTheGap/MindTheGap.sol | 0x0e42ffbac75bcc30cd0015f8aaa608539ba35fbb | Solidity | GmStudioMindTheGap | contract GmStudioMindTheGap is
ERC721Common,
ReentrancyGuard,
ERC2981SinglePercentual
{
using EnumerableSet for EnumerableSet.AddressSet;
using SignatureChecker for EnumerableSet.AddressSet;
using Address for address payable;
/// @notice Price for minting
uint256 public constant MINT_PRICE = 0.15 ether;
/// @notice Splits payments between the Studio and the artist.
address payable public immutable paymentSplitter;
/// @notice Splits payments between the Studio and the artist.
address payable public immutable paymentSplitterRoyalties;
/// @notice Total maximum amount of tokens
uint32 public constant MAX_NUM_TOKENS = 999;
/// @notice Max number of mints per transaction.
/// @dev Only for public mints.
uint32 public constant MAX_MINT_PER_TX = 1;
/// @notice Number of mints throught the signed minting interface.
uint32 internal constant NUM_SIGNED_MINTS = 300;
/// @notice Number of mints for reserved the studio.
uint32 internal constant NUM_RESERVED_MINTS = 1;
/// @notice Currently minted supply of tokens
uint32 public totalSupply;
/// @notice Counter for the remaining signed mints
uint32 internal numSignedMintsRemaining;
/// @notice Locks the mintReserve function
bool internal reserveMinted;
/// @notice Locks the code storing function
bool internal codeStoreLocked;
/// @notice Timestamps to enables/eisables minting interfaces
/// @dev The following order is assumed
/// signedMintOpeningTimestamp < publicMintOpeningTimestamp < mintClosingTimestamp
struct MintConfig {
uint64 signedMintOpeningTimestamp;
uint64 publicMintOpeningTimestamp;
uint64 mintClosingTimestamp;
}
/// @notice The minting configuration
MintConfig public mintConfig;
/// @notice Stores the number of tokens minted from a signature
/// @dev Used in mintSigned
mapping(bytes32 => uint256) public numSignedMintsFrom;
/// @notice Signature signers for the early access phase.
/// @dev Removing signers invalidates the corresponding signatures.
EnumerableSet.AddressSet private _signers;
/// @notice tokenURI() base path.
/// @dev Without trailing slash
string internal _baseTokenURI;
constructor(
address newOwner,
address signer,
string memory baseTokenURI,
address[] memory payees,
uint256[] memory shares,
uint256[] memory sharesRoyalties
) ERC721Common("Mind the Gap by MountVitruvius", "MTG") {
_signers.add(signer);
_baseTokenURI = baseTokenURI;
paymentSplitter = payable(
PaymentSplitterDeployer.instance().deploy(payees, shares)
);
paymentSplitterRoyalties = payable(
PaymentSplitterDeployer.instance().deploy(payees, sharesRoyalties)
);
_setRoyaltyPercentage(750);
_setRoyaltyReceiver(paymentSplitterRoyalties);
numSignedMintsRemaining = NUM_SIGNED_MINTS;
transferOwnership(newOwner);
}
// -------------------------------------------------------------------------
//
// Minting
//
// -------------------------------------------------------------------------
/// @notice Toggle minting relevant flags.
function setMintConfig(MintConfig calldata config) external onlyOwner {
mintConfig = config;
}
/// @dev Reverts if we are not in the signed minting window or the if
/// `mintConfig` has not been set yet.
modifier onlyDuringSignedMintingPeriod() {
if (
block.timestamp < mintConfig.signedMintOpeningTimestamp ||
block.timestamp > mintConfig.publicMintOpeningTimestamp
) revert MintDisabled();
_;
}
/// @dev Reverts if we are not in the public minting window or the if
/// `mintConfig` has not been set yet.
modifier onlyDuringPublicMintingPeriod() {
if (
block.timestamp < mintConfig.publicMintOpeningTimestamp ||
block.timestamp > mintConfig.mintClosingTimestamp
) revert MintDisabled();
_;
}
/// @notice Mints tokens to a given address using a signed message.
/// @dev The minter might be different than the receiver.
/// @param to Token receiver
/// @param num Number of tokens to be minted.
/// @param numMax Max number of tokens that can be minted to the receiver
/// @param signature to prove that the receiver is allowed to get mints.
/// @dev The signed messages is generated from `to || numMax`.
function mintSigned(
address to,
uint32 num,
uint32 numMax,
uint256 nonce,
bytes calldata signature
) external payable nonReentrant onlyDuringSignedMintingPeriod {
bytes32 message = ECDSA.toEthSignedMessageHash(
abi.encodePacked(to, numMax, nonce)
);
if (num + numSignedMintsFrom[message] > numMax)
revert TooManyMintsRequested();
if (num > numSignedMintsRemaining)
revert InsufficientTokensRemanining();
if (num * MINT_PRICE != msg.value) revert InvalidPayment();
_signers.requireValidSignature(message, signature);
numSignedMintsFrom[message] += num;
numSignedMintsRemaining -= num;
_processPayment();
_processMint(to, num);
}
/// @notice Mints tokens to a given address.
/// @dev The minter might be different than the receiver.
/// @param to Token receiver
/// @param num Number of tokens to be minted.
function mintPublic(address to, uint32 num)
external
payable
nonReentrant
onlyDuringPublicMintingPeriod
{
if (num > MAX_MINT_PER_TX) revert TooManyMintsRequested();
uint256 numRemaining = MAX_NUM_TOKENS - totalSupply;
if (num > numRemaining) revert InsufficientTokensRemanining();
if (num * MINT_PRICE != msg.value) revert InvalidPayment();
_processPayment();
_processMint(to, num);
}
/// @notice Mints the DAO allocated tokens.
/// @dev The minter might be different than the receiver.
/// @param to Token receiver
function mintReserve(address to) external onlyOwner {
if (reserveMinted) revert MintDisabled();
reserveMinted = true;
_processMint(to, NUM_RESERVED_MINTS);
}
/// @notice Mints new tokens for the recipient.
function _processMint(address to, uint32 num) internal {
uint32 supply = totalSupply;
for (uint256 i = 0; i < num; i++) {
if (MAX_NUM_TOKENS <= supply) revert SoldOut();
ERC721._safeMint(to, supply);
supply++;
}
totalSupply = supply;
}
// -------------------------------------------------------------------------
//
// Signature validataion
//
// -------------------------------------------------------------------------
/// @notice Removes and adds addresses to the set of allowed signers.
/// @dev Removal is performed before addition.
function changeSigners(
address[] calldata delSigners,
address[] calldata addSigners
) external onlyOwner {
for (uint256 idx; idx < delSigners.length; ++idx) {
_signers.remove(delSigners[idx]);
}
for (uint256 idx; idx < addSigners.length; ++idx) {
_signers.add(addSigners[idx]);
}
}
/// @notice Returns the addresses that are used for signature verification
function getSigners() external view returns (address[] memory signers) {
uint256 len = _signers.length();
signers = new address[](len);
for (uint256 idx = 0; idx < len; ++idx) {
signers[idx] = _signers.at(idx);
}
}
// -------------------------------------------------------------------------
//
// Payment
//
// -------------------------------------------------------------------------
/// @notice Default function for receiving funds
/// @dev This enables the contract to be used as splitter for royalties.
receive() external payable {
_processPayment();
}
/// @notice Processes an incoming payment and sends it to the payment
/// splitter.
function _processPayment() internal {
paymentSplitter.sendValue(msg.value);
}
// -------------------------------------------------------------------------
//
// Metadata
//
// -------------------------------------------------------------------------
/// @notice This function is intended to store (genart) code onchain in
// calldata.
function storeCode(bytes calldata) external {
if (
codeStoreLocked ||
(mintConfig.signedMintOpeningTimestamp > 0 &&
block.timestamp > mintConfig.signedMintOpeningTimestamp)
) revert CodeStoreLocked();
codeStoreLocked = true;
}
/// @notice Change tokenURI() base path.
/// @param uri The new base path (must not contain trailing slash)
function setBaseTokenURI(string calldata uri) external onlyOwner {
_baseTokenURI = uri;
}
/// @notice Returns the URI for token metadata.
function tokenURI(uint256 tokenId)
public
view
override
tokenExists(tokenId)
returns (string memory)
{
return
string(
abi.encodePacked(
_baseTokenURI,
"/",
Strings.toString(tokenId),
".json"
)
);
}
// -------------------------------------------------------------------------
//
// Internals
//
// -------------------------------------------------------------------------
/// @dev See {IERC165-supportsInterface}.
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Common, ERC2981)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
// -------------------------------------------------------------------------
//
// Errors
//
// -------------------------------------------------------------------------
error MintDisabled();
error TooManyMintsRequested();
error InsufficientTokensRemanining();
error InvalidPayment();
error SoldOut();
error InvalidSignature();
error ExeedsOwnerAllocation();
error NotAllowedToOwnerMint();
error NotAllowToChangeAddress();
error CodeStoreLocked();
} | // __ __ __
// | \ | \ \
// ______ ______ ____ _______ _| ββ_ __ __ ____| ββ\ββ ______
// / \| \ \ / \ ββ \ | \ | \/ ββ \/ \
// | ββββββ\ ββββββ\ββββ\ | βββββββ\ββββββ | ββ | ββ βββββββ ββ ββββββ\
// | ββ | ββ ββ | ββ | ββ \ββ \ | ββ __| ββ | ββ ββ | ββ ββ ββ | ββ
// | ββ__| ββ ββ | ββ | ββ__ _\ββββββ\ | ββ| \ ββ__/ ββ ββ__| ββ ββ ββ__/ ββ
// \ββ ββ ββ | ββ | ββ \ | ββ \ββ ββ\ββ ββ\ββ ββ ββ\ββ ββ
// _\βββββββ\ββ \ββ \ββ\ββ \βββββββ \ββββ \ββββββ \βββββββ\ββ \ββββββ
// | \__| ββ
// \ββ ββ
// \ββββββ
// | LineComment | supportsInterface | function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Common, ERC2981)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
| /// @dev See {IERC165-supportsInterface}. | NatSpecSingleLine | v0.8.11+commit.d7f03943 | Unlicense | {
"func_code_index": [
9890,
10112
]
} | 2,110 |
|
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | totalSupply | function totalSupply() external view returns (uint256);
| /**
* @dev Returns the amount of tokens in existence.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
94,
154
]
} | 2,111 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | balanceOf | function balanceOf(address account) external view returns (uint256);
| /**
* @dev Returns the amount of tokens owned by `account`.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
235,
308
]
} | 2,112 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | transfer | function transfer(address recipient, uint256 amount) external returns (bool);
| /**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
530,
612
]
} | 2,113 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | allowance | function allowance(address owner, address spender) external view returns (uint256);
| /**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
889,
977
]
} | 2,114 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | approve | function approve(address spender, uint256 amount) external returns (bool);
| /**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
1639,
1718
]
} | 2,115 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | transferFrom | function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
| /**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
2029,
2131
]
} | 2,116 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | add | function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
| /**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
259,
445
]
} | 2,117 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | sub | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
| /**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
721,
862
]
} | 2,118 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | sub | function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
| /**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
1158,
1353
]
} | 2,119 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | mul | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
| /**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
1605,
2077
]
} | 2,120 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | div | function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
| /**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
2546,
2683
]
} | 2,121 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | div | function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| /**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
3172,
3453
]
} | 2,122 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | mod | function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
| /**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
3911,
4046
]
} | 2,123 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | mod | function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
| /**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
4524,
4695
]
} | 2,124 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | isContract | function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
| /**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
606,
1230
]
} | 2,125 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | sendValue | function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
| /**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
2158,
2560
]
} | 2,126 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | functionCall | function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
| /**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
3314,
3492
]
} | 2,127 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | functionCall | function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
3715,
3916
]
} | 2,128 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | functionCallWithValue | function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
4284,
4515
]
} | 2,129 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | functionCallWithValue | function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
4764,
5085
]
} | 2,130 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | Ownable | contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | owner | function owner() public view returns (address) {
return _owner;
}
| /**
* @dev Returns the address of the current owner.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
493,
577
]
} | 2,131 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | Ownable | contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | renounceOwnership | function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
| /**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
1131,
1284
]
} | 2,132 |
||
GFARM | GFARM.sol | 0x05504f48e8093ce95f2092372cbbe09980365789 | Solidity | Ownable | contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | transferOwnership | function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| /**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://a0e8dd6059356d1f673d5edb7d22995f9793cc4a04b9256ca283cffda7f1ca23 | {
"func_code_index": [
1432,
1681
]
} | 2,133 |
||
TokenDevs | TokenDevs.sol | 0x01aec44dd1be1bf86f4fe4f768fc8fd46008b166 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | totalSupply | function totalSupply() constant returns (uint256 supply) {}
| /// @return total amount of tokens | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://f359f058ab0d0682f60297a3de328fe4217fb07f450fb4442f54863f8e0fee3c | {
"func_code_index": [
64,
128
]
} | 2,134 |
|||
TokenDevs | TokenDevs.sol | 0x01aec44dd1be1bf86f4fe4f768fc8fd46008b166 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | balanceOf | function balanceOf(address _owner) constant returns (uint256 balance) {}
| /// @param _owner The address from which the balance will be retrieved
/// @return The balance | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://f359f058ab0d0682f60297a3de328fe4217fb07f450fb4442f54863f8e0fee3c | {
"func_code_index": [
242,
319
]
} | 2,135 |
|||
TokenDevs | TokenDevs.sol | 0x01aec44dd1be1bf86f4fe4f768fc8fd46008b166 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | transfer | function transfer(address _to, uint256 _value) returns (bool success) {}
| /// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://f359f058ab0d0682f60297a3de328fe4217fb07f450fb4442f54863f8e0fee3c | {
"func_code_index": [
566,
643
]
} | 2,136 |
|||
TokenDevs | TokenDevs.sol | 0x01aec44dd1be1bf86f4fe4f768fc8fd46008b166 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | transferFrom | function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
| /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://f359f058ab0d0682f60297a3de328fe4217fb07f450fb4442f54863f8e0fee3c | {
"func_code_index": [
978,
1074
]
} | 2,137 |
|||
TokenDevs | TokenDevs.sol | 0x01aec44dd1be1bf86f4fe4f768fc8fd46008b166 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | approve | function approve(address _spender, uint256 _value) returns (bool success) {}
| /// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://f359f058ab0d0682f60297a3de328fe4217fb07f450fb4442f54863f8e0fee3c | {
"func_code_index": [
1368,
1449
]
} | 2,138 |
|||
TokenDevs | TokenDevs.sol | 0x01aec44dd1be1bf86f4fe4f768fc8fd46008b166 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | allowance | function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
| /// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://f359f058ab0d0682f60297a3de328fe4217fb07f450fb4442f54863f8e0fee3c | {
"func_code_index": [
1665,
1762
]
} | 2,139 |
|||
TokenDevs | TokenDevs.sol | 0x01aec44dd1be1bf86f4fe4f768fc8fd46008b166 | Solidity | TokenDevs | contract TokenDevs is StandardToken {
function () {
//if ether is sent to this address, send it back.
throw;
}
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme.
//
// CHANGE THESE VALUES FOR YOUR TOKEN
//
//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token
function TokenDevs(
) {
balances[msg.sender] = 100000000; // Give the creator all initial tokens (100000 for example)
totalSupply = 100000000; // Update total supply (100000 for example)
name = "TokenDevs"; // Set the name for display purposes
decimals = 0; // Amount of decimals for display purposes
symbol = "TDEV"; // Set the symbol for display purposes
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | //name this contract whatever you'd like | LineComment | TokenDevs | function TokenDevs(
) {
balances[msg.sender] = 100000000; // Give the creator all initial tokens (100000 for example)
totalSupply = 100000000; // Update total supply (100000 for example)
name = "TokenDevs"; // Set the name for display purposes
decimals = 0; // Amount of decimals for display purposes
symbol = "TDEV"; // Set the symbol for display purposes
}
| //human 0.1 standard. Just an arbitrary versioning scheme.
//
// CHANGE THESE VALUES FOR YOUR TOKEN
//
//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token | LineComment | v0.4.24+commit.e67f0147 | bzzr://f359f058ab0d0682f60297a3de328fe4217fb07f450fb4442f54863f8e0fee3c | {
"func_code_index": [
1198,
1761
]
} | 2,140 |
|
TokenDevs | TokenDevs.sol | 0x01aec44dd1be1bf86f4fe4f768fc8fd46008b166 | Solidity | TokenDevs | contract TokenDevs is StandardToken {
function () {
//if ether is sent to this address, send it back.
throw;
}
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme.
//
// CHANGE THESE VALUES FOR YOUR TOKEN
//
//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token
function TokenDevs(
) {
balances[msg.sender] = 100000000; // Give the creator all initial tokens (100000 for example)
totalSupply = 100000000; // Update total supply (100000 for example)
name = "TokenDevs"; // Set the name for display purposes
decimals = 0; // Amount of decimals for display purposes
symbol = "TDEV"; // Set the symbol for display purposes
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | //name this contract whatever you'd like | LineComment | approveAndCall | function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
| /* Approves and then calls the receiving contract */ | Comment | v0.4.24+commit.e67f0147 | bzzr://f359f058ab0d0682f60297a3de328fe4217fb07f450fb4442f54863f8e0fee3c | {
"func_code_index": [
1826,
2647
]
} | 2,141 |
|
Defix_POOLX_Core | @openzeppelin/contracts/access/Ownable.sol | 0x2b597f81eafdaae44a74a681992ae9026547a8e8 | Solidity | Ownable | contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | owner | function owner() public view returns (address) {
return _owner;
}
| /**
* @dev Returns the address of the current owner.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://acdab1d57408f507d9a2bb2c3890e5d0826c6b0ec5d087d425b69239d1921208 | {
"func_code_index": [
521,
605
]
} | 2,142 |
Defix_POOLX_Core | @openzeppelin/contracts/access/Ownable.sol | 0x2b597f81eafdaae44a74a681992ae9026547a8e8 | Solidity | Ownable | contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | renounceOwnership | function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
| /**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://acdab1d57408f507d9a2bb2c3890e5d0826c6b0ec5d087d425b69239d1921208 | {
"func_code_index": [
1163,
1316
]
} | 2,143 |
Defix_POOLX_Core | @openzeppelin/contracts/access/Ownable.sol | 0x2b597f81eafdaae44a74a681992ae9026547a8e8 | Solidity | Ownable | contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | transferOwnership | function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| /**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://acdab1d57408f507d9a2bb2c3890e5d0826c6b0ec5d087d425b69239d1921208 | {
"func_code_index": [
1466,
1752
]
} | 2,144 |
TCOREv1Router | contracts/libraries/Math.sol | 0xd4519f1f00e977f72ea74bc2755dd2596fe678da | Solidity | Math | library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
} | // a library for performing various math operations | LineComment | sqrt | function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
| // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) | LineComment | v0.6.12+commit.27d51765 | MIT | ipfs://9e6544b8527264a083bc57b954d307b6b5a4b0563563a80a6099de7e3762e3db | {
"func_code_index": [
230,
538
]
} | 2,145 |
CHAINBLOCK | CHAINBLOCK.sol | 0xf9472dcab9efa21dd01d5b7e9d1a40c7f96bd57e | Solidity | Ownable | contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | transferOwnership | function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
| /**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://7b08035e5ea6dcfe9c7f6965cf517485d520f560a369ba65c34042e03ca20d7f | {
"func_code_index": [
642,
823
]
} | 2,146 |
CHAINBLOCK | CHAINBLOCK.sol | 0xf9472dcab9efa21dd01d5b7e9d1a40c7f96bd57e | Solidity | StandardToken | contract StandardToken is ERC20Basic, Ownable {
uint256 public totalSupply;
using SafeMath for uint256;
mapping(address => uint256) balances;
// allowedAddresses will be able to transfer even when locked
// lockedAddresses will *not* be able to transfer even when *not locked*
mapping(address => bool) public allowedAddresses;
mapping(address => bool) public lockedAddresses;
bool public locked = true;
function allowAddress(address _addr, bool _allowed) public onlyOwner {
require(_addr != owner);
allowedAddresses[_addr] = _allowed;
}
function lockAddress(address _addr, bool _locked) public onlyOwner {
require(_addr != owner);
lockedAddresses[_addr] = _locked;
}
function setLocked(bool _locked) public onlyOwner {
locked = _locked;
}
function canTransfer(address _addr) public view returns (bool can1) {
if(locked){
if(!allowedAddresses[_addr]&&_addr!=owner) return false;
}else if(lockedAddresses[_addr]) return false;
return true;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public override returns (bool trans1) {
require(_to != address(0));
require(canTransfer(msg.sender));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
*/
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool trans) {
require(_to != address(0));
require(canTransfer(msg.sender));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public override returns (bool hello) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
*/
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | transfer | function transfer(address _to, uint256 _value) public override returns (bool trans1) {
require(_to != address(0));
require(canTransfer(msg.sender));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
| /**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://7b08035e5ea6dcfe9c7f6965cf517485d520f560a369ba65c34042e03ca20d7f | {
"func_code_index": [
1216,
1627
]
} | 2,147 |
CHAINBLOCK | CHAINBLOCK.sol | 0xf9472dcab9efa21dd01d5b7e9d1a40c7f96bd57e | Solidity | StandardToken | contract StandardToken is ERC20Basic, Ownable {
uint256 public totalSupply;
using SafeMath for uint256;
mapping(address => uint256) balances;
// allowedAddresses will be able to transfer even when locked
// lockedAddresses will *not* be able to transfer even when *not locked*
mapping(address => bool) public allowedAddresses;
mapping(address => bool) public lockedAddresses;
bool public locked = true;
function allowAddress(address _addr, bool _allowed) public onlyOwner {
require(_addr != owner);
allowedAddresses[_addr] = _allowed;
}
function lockAddress(address _addr, bool _locked) public onlyOwner {
require(_addr != owner);
lockedAddresses[_addr] = _locked;
}
function setLocked(bool _locked) public onlyOwner {
locked = _locked;
}
function canTransfer(address _addr) public view returns (bool can1) {
if(locked){
if(!allowedAddresses[_addr]&&_addr!=owner) return false;
}else if(lockedAddresses[_addr]) return false;
return true;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public override returns (bool trans1) {
require(_to != address(0));
require(canTransfer(msg.sender));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
*/
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool trans) {
require(_to != address(0));
require(canTransfer(msg.sender));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public override returns (bool hello) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
*/
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
| /**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://7b08035e5ea6dcfe9c7f6965cf517485d520f560a369ba65c34042e03ca20d7f | {
"func_code_index": [
1760,
1881
]
} | 2,148 |
CHAINBLOCK | CHAINBLOCK.sol | 0xf9472dcab9efa21dd01d5b7e9d1a40c7f96bd57e | Solidity | StandardToken | contract StandardToken is ERC20Basic, Ownable {
uint256 public totalSupply;
using SafeMath for uint256;
mapping(address => uint256) balances;
// allowedAddresses will be able to transfer even when locked
// lockedAddresses will *not* be able to transfer even when *not locked*
mapping(address => bool) public allowedAddresses;
mapping(address => bool) public lockedAddresses;
bool public locked = true;
function allowAddress(address _addr, bool _allowed) public onlyOwner {
require(_addr != owner);
allowedAddresses[_addr] = _allowed;
}
function lockAddress(address _addr, bool _locked) public onlyOwner {
require(_addr != owner);
lockedAddresses[_addr] = _locked;
}
function setLocked(bool _locked) public onlyOwner {
locked = _locked;
}
function canTransfer(address _addr) public view returns (bool can1) {
if(locked){
if(!allowedAddresses[_addr]&&_addr!=owner) return false;
}else if(lockedAddresses[_addr]) return false;
return true;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public override returns (bool trans1) {
require(_to != address(0));
require(canTransfer(msg.sender));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
*/
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool trans) {
require(_to != address(0));
require(canTransfer(msg.sender));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public override returns (bool hello) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
*/
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | transferFrom | function transferFrom(address _from, address _to, uint256 _value) public override returns (bool trans) {
require(_to != address(0));
require(canTransfer(msg.sender));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
| /**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://7b08035e5ea6dcfe9c7f6965cf517485d520f560a369ba65c34042e03ca20d7f | {
"func_code_index": [
2229,
2837
]
} | 2,149 |
CHAINBLOCK | CHAINBLOCK.sol | 0xf9472dcab9efa21dd01d5b7e9d1a40c7f96bd57e | Solidity | StandardToken | contract StandardToken is ERC20Basic, Ownable {
uint256 public totalSupply;
using SafeMath for uint256;
mapping(address => uint256) balances;
// allowedAddresses will be able to transfer even when locked
// lockedAddresses will *not* be able to transfer even when *not locked*
mapping(address => bool) public allowedAddresses;
mapping(address => bool) public lockedAddresses;
bool public locked = true;
function allowAddress(address _addr, bool _allowed) public onlyOwner {
require(_addr != owner);
allowedAddresses[_addr] = _allowed;
}
function lockAddress(address _addr, bool _locked) public onlyOwner {
require(_addr != owner);
lockedAddresses[_addr] = _locked;
}
function setLocked(bool _locked) public onlyOwner {
locked = _locked;
}
function canTransfer(address _addr) public view returns (bool can1) {
if(locked){
if(!allowedAddresses[_addr]&&_addr!=owner) return false;
}else if(lockedAddresses[_addr]) return false;
return true;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public override returns (bool trans1) {
require(_to != address(0));
require(canTransfer(msg.sender));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
*/
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool trans) {
require(_to != address(0));
require(canTransfer(msg.sender));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public override returns (bool hello) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
*/
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | approve | function approve(address _spender, uint256 _value) public override returns (bool hello) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
| /**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://7b08035e5ea6dcfe9c7f6965cf517485d520f560a369ba65c34042e03ca20d7f | {
"func_code_index": [
3469,
3679
]
} | 2,150 |
CHAINBLOCK | CHAINBLOCK.sol | 0xf9472dcab9efa21dd01d5b7e9d1a40c7f96bd57e | Solidity | StandardToken | contract StandardToken is ERC20Basic, Ownable {
uint256 public totalSupply;
using SafeMath for uint256;
mapping(address => uint256) balances;
// allowedAddresses will be able to transfer even when locked
// lockedAddresses will *not* be able to transfer even when *not locked*
mapping(address => bool) public allowedAddresses;
mapping(address => bool) public lockedAddresses;
bool public locked = true;
function allowAddress(address _addr, bool _allowed) public onlyOwner {
require(_addr != owner);
allowedAddresses[_addr] = _allowed;
}
function lockAddress(address _addr, bool _locked) public onlyOwner {
require(_addr != owner);
lockedAddresses[_addr] = _locked;
}
function setLocked(bool _locked) public onlyOwner {
locked = _locked;
}
function canTransfer(address _addr) public view returns (bool can1) {
if(locked){
if(!allowedAddresses[_addr]&&_addr!=owner) return false;
}else if(lockedAddresses[_addr]) return false;
return true;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public override returns (bool trans1) {
require(_to != address(0));
require(canTransfer(msg.sender));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
*/
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool trans) {
require(_to != address(0));
require(canTransfer(msg.sender));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public override returns (bool hello) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
*/
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | allowance | function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
| /**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://7b08035e5ea6dcfe9c7f6965cf517485d520f560a369ba65c34042e03ca20d7f | {
"func_code_index": [
3919,
4070
]
} | 2,151 |
CHAINBLOCK | CHAINBLOCK.sol | 0xf9472dcab9efa21dd01d5b7e9d1a40c7f96bd57e | Solidity | StandardToken | contract StandardToken is ERC20Basic, Ownable {
uint256 public totalSupply;
using SafeMath for uint256;
mapping(address => uint256) balances;
// allowedAddresses will be able to transfer even when locked
// lockedAddresses will *not* be able to transfer even when *not locked*
mapping(address => bool) public allowedAddresses;
mapping(address => bool) public lockedAddresses;
bool public locked = true;
function allowAddress(address _addr, bool _allowed) public onlyOwner {
require(_addr != owner);
allowedAddresses[_addr] = _allowed;
}
function lockAddress(address _addr, bool _locked) public onlyOwner {
require(_addr != owner);
lockedAddresses[_addr] = _locked;
}
function setLocked(bool _locked) public onlyOwner {
locked = _locked;
}
function canTransfer(address _addr) public view returns (bool can1) {
if(locked){
if(!allowedAddresses[_addr]&&_addr!=owner) return false;
}else if(lockedAddresses[_addr]) return false;
return true;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public override returns (bool trans1) {
require(_to != address(0));
require(canTransfer(msg.sender));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
*/
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool trans) {
require(_to != address(0));
require(canTransfer(msg.sender));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public override returns (bool hello) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
*/
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | increaseApproval | function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| /**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://7b08035e5ea6dcfe9c7f6965cf517485d520f560a369ba65c34042e03ca20d7f | {
"func_code_index": [
4315,
4593
]
} | 2,152 |
CHAINBLOCK | CHAINBLOCK.sol | 0xf9472dcab9efa21dd01d5b7e9d1a40c7f96bd57e | Solidity | BurnableToken | contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(burner, _value);
emit Transfer(burner, address(0), _value);
}
} | /**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/ | NatSpecMultiLine | burn | function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(burner, _value);
emit Transfer(burner, address(0), _value);
}
| /**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://7b08035e5ea6dcfe9c7f6965cf517485d520f560a369ba65c34042e03ca20d7f | {
"func_code_index": [
225,
770
]
} | 2,153 |
TCOREv1Router | @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol | 0xd4519f1f00e977f72ea74bc2755dd2596fe678da | Solidity | OwnableUpgradeSafe | contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | __Ownable_init | function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
| /**
* @dev Initializes the contract setting the deployer as the initial owner.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://9e6544b8527264a083bc57b954d307b6b5a4b0563563a80a6099de7e3762e3db | {
"func_code_index": [
292,
426
]
} | 2,154 |
TCOREv1Router | @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol | 0xd4519f1f00e977f72ea74bc2755dd2596fe678da | Solidity | OwnableUpgradeSafe | contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | owner | function owner() public view returns (address) {
return _owner;
}
| /**
* @dev Returns the address of the current owner.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://9e6544b8527264a083bc57b954d307b6b5a4b0563563a80a6099de7e3762e3db | {
"func_code_index": [
714,
798
]
} | 2,155 |
TCOREv1Router | @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol | 0xd4519f1f00e977f72ea74bc2755dd2596fe678da | Solidity | OwnableUpgradeSafe | contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | renounceOwnership | function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
| /**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://9e6544b8527264a083bc57b954d307b6b5a4b0563563a80a6099de7e3762e3db | {
"func_code_index": [
1356,
1509
]
} | 2,156 |
TCOREv1Router | @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol | 0xd4519f1f00e977f72ea74bc2755dd2596fe678da | Solidity | OwnableUpgradeSafe | contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | transferOwnership | function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| /**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://9e6544b8527264a083bc57b954d307b6b5a4b0563563a80a6099de7e3762e3db | {
"func_code_index": [
1659,
1908
]
} | 2,157 |
BECToken | BECToken.sol | 0x54facff15cf83dbcac3350ba1a00b3d4edf48359 | Solidity | BECToken | contract BECToken is StandardToken {
string public name = "BECoin";
string public symbol = "BEC";
uint public decimals = 3;
function BECToken (address _bank, uint _totalSupply) {
balances[_bank] += _totalSupply;
totalSupply += _totalSupply;
}
// Transfer amount of tokens from sender account to recipient.
function transfer(address _recipient, uint _amount)
returns (bool o_success)
{
return super.transfer(_recipient, _amount);
}
// Transfer amount of tokens from a specified address to a recipient.
function transferFrom(address _from, address _recipient, uint _amount)
returns (bool o_success)
{
return super.transferFrom(_from, _recipient, _amount);
}
} | transfer | function transfer(address _recipient, uint _amount)
returns (bool o_success)
{
return super.transfer(_recipient, _amount);
}
| // Transfer amount of tokens from sender account to recipient. | LineComment | v0.4.15+commit.bbb8e64f | bzzr://297030f766a938a97171a74048eaa85e976f553e471186d21dfd6f559a789840 | {
"func_code_index": [
337,
473
]
} | 2,158 |
|||
BECToken | BECToken.sol | 0x54facff15cf83dbcac3350ba1a00b3d4edf48359 | Solidity | BECToken | contract BECToken is StandardToken {
string public name = "BECoin";
string public symbol = "BEC";
uint public decimals = 3;
function BECToken (address _bank, uint _totalSupply) {
balances[_bank] += _totalSupply;
totalSupply += _totalSupply;
}
// Transfer amount of tokens from sender account to recipient.
function transfer(address _recipient, uint _amount)
returns (bool o_success)
{
return super.transfer(_recipient, _amount);
}
// Transfer amount of tokens from a specified address to a recipient.
function transferFrom(address _from, address _recipient, uint _amount)
returns (bool o_success)
{
return super.transferFrom(_from, _recipient, _amount);
}
} | transferFrom | function transferFrom(address _from, address _recipient, uint _amount)
returns (bool o_success)
{
return super.transferFrom(_from, _recipient, _amount);
}
| // Transfer amount of tokens from a specified address to a recipient. | LineComment | v0.4.15+commit.bbb8e64f | bzzr://297030f766a938a97171a74048eaa85e976f553e471186d21dfd6f559a789840 | {
"func_code_index": [
548,
714
]
} | 2,159 |
|||
YFPIPresaleRoundTwo | @openzeppelin/contracts/utils/Address.sol | 0xfaa1e3390f452d98a8fc4dd92aaad55a5e831dd9 | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | isContract | function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
| /**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | bzzr://008b35a2ff710804b9dfcc06dff11aaa52f28fd3f624dbef8829f38aeaf90c26 | {
"func_code_index": [
607,
1231
]
} | 2,160 |
YFPIPresaleRoundTwo | @openzeppelin/contracts/utils/Address.sol | 0xfaa1e3390f452d98a8fc4dd92aaad55a5e831dd9 | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | toPayable | function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
| /**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | bzzr://008b35a2ff710804b9dfcc06dff11aaa52f28fd3f624dbef8829f38aeaf90c26 | {
"func_code_index": [
1443,
1575
]
} | 2,161 |
YFPIPresaleRoundTwo | @openzeppelin/contracts/utils/Address.sol | 0xfaa1e3390f452d98a8fc4dd92aaad55a5e831dd9 | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | sendValue | function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
| /**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | bzzr://008b35a2ff710804b9dfcc06dff11aaa52f28fd3f624dbef8829f38aeaf90c26 | {
"func_code_index": [
2547,
2923
]
} | 2,162 |
MedicalCoinProxy | MedicalCoinProxy.sol | 0x33bb3221e512c812e7036c260a6c240b2c0bc317 | Solidity | Proxy | contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
function () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize)
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
} | /**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/ | NatSpecMultiLine | function () payable external {
_fallback();
}
| /**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://ec9335c22150829534e4959c0cd41265cf570076a191f2aa747348825af814fc | {
"func_code_index": [
113,
177
]
} | 2,163 |
||
MedicalCoinProxy | MedicalCoinProxy.sol | 0x33bb3221e512c812e7036c260a6c240b2c0bc317 | Solidity | Proxy | contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
function () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize)
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
} | /**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/ | NatSpecMultiLine | _implementation | function _implementation() internal view returns (address);
| /**
* @return The Address of the implementation.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://ec9335c22150829534e4959c0cd41265cf570076a191f2aa747348825af814fc | {
"func_code_index": [
249,
313
]
} | 2,164 |
|
MedicalCoinProxy | MedicalCoinProxy.sol | 0x33bb3221e512c812e7036c260a6c240b2c0bc317 | Solidity | Proxy | contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
function () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize)
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
} | /**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/ | NatSpecMultiLine | _delegate | function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize)
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
| /**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://ec9335c22150829534e4959c0cd41265cf570076a191f2aa747348825af814fc | {
"func_code_index": [
616,
1435
]
} | 2,165 |
|
MedicalCoinProxy | MedicalCoinProxy.sol | 0x33bb3221e512c812e7036c260a6c240b2c0bc317 | Solidity | Proxy | contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
function () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize)
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
} | /**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/ | NatSpecMultiLine | _willFallback | function _willFallback() internal {
}
| /**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://ec9335c22150829534e4959c0cd41265cf570076a191f2aa747348825af814fc | {
"func_code_index": [
1658,
1705
]
} | 2,166 |
|
MedicalCoinProxy | MedicalCoinProxy.sol | 0x33bb3221e512c812e7036c260a6c240b2c0bc317 | Solidity | Proxy | contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
function () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize)
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
} | /**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/ | NatSpecMultiLine | _fallback | function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
| /**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://ec9335c22150829534e4959c0cd41265cf570076a191f2aa747348825af814fc | {
"func_code_index": [
1811,
1919
]
} | 2,167 |
|
MedicalCoinProxy | MedicalCoinProxy.sol | 0x33bb3221e512c812e7036c260a6c240b2c0bc317 | Solidity | UpgradeabilityProxy | contract UpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is
* validated in the constructor.
*/
bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
/**
* @dev Contract constructor.
* @param _implementation Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _implementation, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation"));
_setImplementation(_implementation);
if(_data.length > 0) {
require(_implementation.delegatecall(_data));
}
}
/**
* @dev Returns the current implementation.
* @return Address of the current implementation
*/
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) private {
require(isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
} | /**
* @title UpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/ | NatSpecMultiLine | _implementation | function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
| /**
* @dev Returns the current implementation.
* @return Address of the current implementation
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://ec9335c22150829534e4959c0cd41265cf570076a191f2aa747348825af814fc | {
"func_code_index": [
1576,
1762
]
} | 2,168 |
|
MedicalCoinProxy | MedicalCoinProxy.sol | 0x33bb3221e512c812e7036c260a6c240b2c0bc317 | Solidity | UpgradeabilityProxy | contract UpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is
* validated in the constructor.
*/
bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
/**
* @dev Contract constructor.
* @param _implementation Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _implementation, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation"));
_setImplementation(_implementation);
if(_data.length > 0) {
require(_implementation.delegatecall(_data));
}
}
/**
* @dev Returns the current implementation.
* @return Address of the current implementation
*/
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) private {
require(isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
} | /**
* @title UpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/ | NatSpecMultiLine | _upgradeTo | function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
| /**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://ec9335c22150829534e4959c0cd41265cf570076a191f2aa747348825af814fc | {
"func_code_index": [
1908,
2068
]
} | 2,169 |
|
MedicalCoinProxy | MedicalCoinProxy.sol | 0x33bb3221e512c812e7036c260a6c240b2c0bc317 | Solidity | UpgradeabilityProxy | contract UpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is
* validated in the constructor.
*/
bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
/**
* @dev Contract constructor.
* @param _implementation Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _implementation, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation"));
_setImplementation(_implementation);
if(_data.length > 0) {
require(_implementation.delegatecall(_data));
}
}
/**
* @dev Returns the current implementation.
* @return Address of the current implementation
*/
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) private {
require(isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
} | /**
* @title UpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/ | NatSpecMultiLine | _setImplementation | function _setImplementation(address newImplementation) private {
require(isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
| /**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://ec9335c22150829534e4959c0cd41265cf570076a191f2aa747348825af814fc | {
"func_code_index": [
2216,
2529
]
} | 2,170 |
|
MedicalCoinProxy | MedicalCoinProxy.sol | 0x33bb3221e512c812e7036c260a6c240b2c0bc317 | Solidity | UpgradeabilityProxy | contract UpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is
* validated in the constructor.
*/
bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
/**
* @dev Contract constructor.
* @param _implementation Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _implementation, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation"));
_setImplementation(_implementation);
if(_data.length > 0) {
require(_implementation.delegatecall(_data));
}
}
/**
* @dev Returns the current implementation.
* @return Address of the current implementation
*/
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) private {
require(isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
} | /**
* @title UpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/ | NatSpecMultiLine | isContract | function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
| /**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://ec9335c22150829534e4959c0cd41265cf570076a191f2aa747348825af814fc | {
"func_code_index": [
2895,
3530
]
} | 2,171 |
|
MedicalCoinProxy | MedicalCoinProxy.sol | 0x33bb3221e512c812e7036c260a6c240b2c0bc317 | Solidity | AdminUpgradeabilityProxy | contract AdminUpgradeabilityProxy is UpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is
* validated in the constructor.
*/
bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* Contract constructor.
* It sets the `msg.sender` as the proxy administrator.
* @param _implementation address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _implementation, bytes _data) UpgradeabilityProxy(_implementation, _data) public payable {
assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin"));
_setAdmin(msg.sender);
}
/**
* @return The address of the proxy admin.
*/
function admin() external view ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external view ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes data) payable external ifAdmin {
_upgradeTo(newImplementation);
require(newImplementation.delegatecall(data));
}
/**
* @return The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
} | /**
* @title AdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/ | NatSpecMultiLine | admin | function admin() external view ifAdmin returns (address) {
return _admin();
}
| /**
* @return The address of the proxy admin.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://ec9335c22150829534e4959c0cd41265cf570076a191f2aa747348825af814fc | {
"func_code_index": [
1879,
1975
]
} | 2,172 |
|
MedicalCoinProxy | MedicalCoinProxy.sol | 0x33bb3221e512c812e7036c260a6c240b2c0bc317 | Solidity | AdminUpgradeabilityProxy | contract AdminUpgradeabilityProxy is UpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is
* validated in the constructor.
*/
bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* Contract constructor.
* It sets the `msg.sender` as the proxy administrator.
* @param _implementation address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _implementation, bytes _data) UpgradeabilityProxy(_implementation, _data) public payable {
assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin"));
_setAdmin(msg.sender);
}
/**
* @return The address of the proxy admin.
*/
function admin() external view ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external view ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes data) payable external ifAdmin {
_upgradeTo(newImplementation);
require(newImplementation.delegatecall(data));
}
/**
* @return The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
} | /**
* @title AdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/ | NatSpecMultiLine | implementation | function implementation() external view ifAdmin returns (address) {
return _implementation();
}
| /**
* @return The address of the implementation.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://ec9335c22150829534e4959c0cd41265cf570076a191f2aa747348825af814fc | {
"func_code_index": [
2047,
2161
]
} | 2,173 |
|
MedicalCoinProxy | MedicalCoinProxy.sol | 0x33bb3221e512c812e7036c260a6c240b2c0bc317 | Solidity | AdminUpgradeabilityProxy | contract AdminUpgradeabilityProxy is UpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is
* validated in the constructor.
*/
bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* Contract constructor.
* It sets the `msg.sender` as the proxy administrator.
* @param _implementation address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _implementation, bytes _data) UpgradeabilityProxy(_implementation, _data) public payable {
assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin"));
_setAdmin(msg.sender);
}
/**
* @return The address of the proxy admin.
*/
function admin() external view ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external view ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes data) payable external ifAdmin {
_upgradeTo(newImplementation);
require(newImplementation.delegatecall(data));
}
/**
* @return The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
} | /**
* @title AdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/ | NatSpecMultiLine | changeAdmin | function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
| /**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://ec9335c22150829534e4959c0cd41265cf570076a191f2aa747348825af814fc | {
"func_code_index": [
2351,
2598
]
} | 2,174 |
|
MedicalCoinProxy | MedicalCoinProxy.sol | 0x33bb3221e512c812e7036c260a6c240b2c0bc317 | Solidity | AdminUpgradeabilityProxy | contract AdminUpgradeabilityProxy is UpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is
* validated in the constructor.
*/
bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* Contract constructor.
* It sets the `msg.sender` as the proxy administrator.
* @param _implementation address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _implementation, bytes _data) UpgradeabilityProxy(_implementation, _data) public payable {
assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin"));
_setAdmin(msg.sender);
}
/**
* @return The address of the proxy admin.
*/
function admin() external view ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external view ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes data) payable external ifAdmin {
_upgradeTo(newImplementation);
require(newImplementation.delegatecall(data));
}
/**
* @return The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
} | /**
* @title AdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/ | NatSpecMultiLine | upgradeTo | function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
| /**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://ec9335c22150829534e4959c0cd41265cf570076a191f2aa747348825af814fc | {
"func_code_index": [
2796,
2912
]
} | 2,175 |
|
MedicalCoinProxy | MedicalCoinProxy.sol | 0x33bb3221e512c812e7036c260a6c240b2c0bc317 | Solidity | AdminUpgradeabilityProxy | contract AdminUpgradeabilityProxy is UpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is
* validated in the constructor.
*/
bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* Contract constructor.
* It sets the `msg.sender` as the proxy administrator.
* @param _implementation address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _implementation, bytes _data) UpgradeabilityProxy(_implementation, _data) public payable {
assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin"));
_setAdmin(msg.sender);
}
/**
* @return The address of the proxy admin.
*/
function admin() external view ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external view ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes data) payable external ifAdmin {
_upgradeTo(newImplementation);
require(newImplementation.delegatecall(data));
}
/**
* @return The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
} | /**
* @title AdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/ | NatSpecMultiLine | upgradeToAndCall | function upgradeToAndCall(address newImplementation, bytes data) payable external ifAdmin {
_upgradeTo(newImplementation);
require(newImplementation.delegatecall(data));
}
| /**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://ec9335c22150829534e4959c0cd41265cf570076a191f2aa747348825af814fc | {
"func_code_index": [
3455,
3654
]
} | 2,176 |
|
MedicalCoinProxy | MedicalCoinProxy.sol | 0x33bb3221e512c812e7036c260a6c240b2c0bc317 | Solidity | AdminUpgradeabilityProxy | contract AdminUpgradeabilityProxy is UpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is
* validated in the constructor.
*/
bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* Contract constructor.
* It sets the `msg.sender` as the proxy administrator.
* @param _implementation address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _implementation, bytes _data) UpgradeabilityProxy(_implementation, _data) public payable {
assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin"));
_setAdmin(msg.sender);
}
/**
* @return The address of the proxy admin.
*/
function admin() external view ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external view ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes data) payable external ifAdmin {
_upgradeTo(newImplementation);
require(newImplementation.delegatecall(data));
}
/**
* @return The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
} | /**
* @title AdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/ | NatSpecMultiLine | _admin | function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
| /**
* @return The admin slot.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://ec9335c22150829534e4959c0cd41265cf570076a191f2aa747348825af814fc | {
"func_code_index": [
3707,
3873
]
} | 2,177 |
|
MedicalCoinProxy | MedicalCoinProxy.sol | 0x33bb3221e512c812e7036c260a6c240b2c0bc317 | Solidity | AdminUpgradeabilityProxy | contract AdminUpgradeabilityProxy is UpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is
* validated in the constructor.
*/
bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* Contract constructor.
* It sets the `msg.sender` as the proxy administrator.
* @param _implementation address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _implementation, bytes _data) UpgradeabilityProxy(_implementation, _data) public payable {
assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin"));
_setAdmin(msg.sender);
}
/**
* @return The address of the proxy admin.
*/
function admin() external view ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external view ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes data) payable external ifAdmin {
_upgradeTo(newImplementation);
require(newImplementation.delegatecall(data));
}
/**
* @return The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
} | /**
* @title AdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/ | NatSpecMultiLine | _setAdmin | function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
| /**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://ec9335c22150829534e4959c0cd41265cf570076a191f2aa747348825af814fc | {
"func_code_index": [
4000,
4164
]
} | 2,178 |
|
MedicalCoinProxy | MedicalCoinProxy.sol | 0x33bb3221e512c812e7036c260a6c240b2c0bc317 | Solidity | AdminUpgradeabilityProxy | contract AdminUpgradeabilityProxy is UpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is
* validated in the constructor.
*/
bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* Contract constructor.
* It sets the `msg.sender` as the proxy administrator.
* @param _implementation address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _implementation, bytes _data) UpgradeabilityProxy(_implementation, _data) public payable {
assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin"));
_setAdmin(msg.sender);
}
/**
* @return The address of the proxy admin.
*/
function admin() external view ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external view ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes data) payable external ifAdmin {
_upgradeTo(newImplementation);
require(newImplementation.delegatecall(data));
}
/**
* @return The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
} | /**
* @title AdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/ | NatSpecMultiLine | _willFallback | function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
| /**
* @dev Only fall back when the sender is not the admin.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://ec9335c22150829534e4959c0cd41265cf570076a191f2aa747348825af814fc | {
"func_code_index": [
4247,
4422
]
} | 2,179 |
|
SlognToken | SlognToken.sol | 0xc0506ceb264b057182a4c3ab8a0b910a545479f0 | Solidity | Token | contract Token {
/* Public variables of the token */
string public standard;
string public name;
string public symbol;
uint8 public decimals;
uint256 public _totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* ERC20 Events */
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function Token(uint256 initialSupply, string _standard, string _name, string _symbol, uint8 _decimals) {
_totalSupply = initialSupply;
balanceOf[this] = initialSupply;
standard = _standard;
name = _name;
symbol = _symbol;
decimals = _decimals;
}
/* Get burnable total supply */
function totalSupply() constant returns(uint256 supply) {
return _totalSupply;
}
/**
* Transfer token logic
* @param _from The address to transfer from.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transferInternal(address _from, address _to, uint256 _value) internal returns (bool success) {
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
return true;
}
/**
* Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFromInternal(address _from, address _to, uint256 _value) internal returns (bool success) {
require(_value >= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
return transferInternal(_from, _to, _value);
}
} | Token | function Token(uint256 initialSupply, string _standard, string _name, string _symbol, uint8 _decimals) {
_totalSupply = initialSupply;
balanceOf[this] = initialSupply;
standard = _standard;
name = _name;
symbol = _symbol;
decimals = _decimals;
}
| /* Initializes contract with initial supply tokens to the creator of the contract */ | Comment | v0.4.11+commit.68ef5810 | bzzr://520b39c434969b3452207146d6707e4c87a166a43c7bf277f368ab5aa6b45faf | {
"func_code_index": [
659,
968
]
} | 2,180 |
|||
SlognToken | SlognToken.sol | 0xc0506ceb264b057182a4c3ab8a0b910a545479f0 | Solidity | Token | contract Token {
/* Public variables of the token */
string public standard;
string public name;
string public symbol;
uint8 public decimals;
uint256 public _totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* ERC20 Events */
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function Token(uint256 initialSupply, string _standard, string _name, string _symbol, uint8 _decimals) {
_totalSupply = initialSupply;
balanceOf[this] = initialSupply;
standard = _standard;
name = _name;
symbol = _symbol;
decimals = _decimals;
}
/* Get burnable total supply */
function totalSupply() constant returns(uint256 supply) {
return _totalSupply;
}
/**
* Transfer token logic
* @param _from The address to transfer from.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transferInternal(address _from, address _to, uint256 _value) internal returns (bool success) {
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
return true;
}
/**
* Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFromInternal(address _from, address _to, uint256 _value) internal returns (bool success) {
require(_value >= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
return transferInternal(_from, _to, _value);
}
} | totalSupply | function totalSupply() constant returns(uint256 supply) {
return _totalSupply;
}
| /* Get burnable total supply */ | Comment | v0.4.11+commit.68ef5810 | bzzr://520b39c434969b3452207146d6707e4c87a166a43c7bf277f368ab5aa6b45faf | {
"func_code_index": [
1008,
1107
]
} | 2,181 |
|||
SlognToken | SlognToken.sol | 0xc0506ceb264b057182a4c3ab8a0b910a545479f0 | Solidity | Token | contract Token {
/* Public variables of the token */
string public standard;
string public name;
string public symbol;
uint8 public decimals;
uint256 public _totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* ERC20 Events */
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function Token(uint256 initialSupply, string _standard, string _name, string _symbol, uint8 _decimals) {
_totalSupply = initialSupply;
balanceOf[this] = initialSupply;
standard = _standard;
name = _name;
symbol = _symbol;
decimals = _decimals;
}
/* Get burnable total supply */
function totalSupply() constant returns(uint256 supply) {
return _totalSupply;
}
/**
* Transfer token logic
* @param _from The address to transfer from.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transferInternal(address _from, address _to, uint256 _value) internal returns (bool success) {
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
return true;
}
/**
* Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFromInternal(address _from, address _to, uint256 _value) internal returns (bool success) {
require(_value >= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
return transferInternal(_from, _to, _value);
}
} | transferInternal | function transferInternal(address _from, address _to, uint256 _value) internal returns (bool success) {
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
return true;
}
| /**
* Transfer token logic
* @param _from The address to transfer from.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/ | NatSpecMultiLine | v0.4.11+commit.68ef5810 | bzzr://520b39c434969b3452207146d6707e4c87a166a43c7bf277f368ab5aa6b45faf | {
"func_code_index": [
1307,
1704
]
} | 2,182 |
|||
SlognToken | SlognToken.sol | 0xc0506ceb264b057182a4c3ab8a0b910a545479f0 | Solidity | Token | contract Token {
/* Public variables of the token */
string public standard;
string public name;
string public symbol;
uint8 public decimals;
uint256 public _totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* ERC20 Events */
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function Token(uint256 initialSupply, string _standard, string _name, string _symbol, uint8 _decimals) {
_totalSupply = initialSupply;
balanceOf[this] = initialSupply;
standard = _standard;
name = _name;
symbol = _symbol;
decimals = _decimals;
}
/* Get burnable total supply */
function totalSupply() constant returns(uint256 supply) {
return _totalSupply;
}
/**
* Transfer token logic
* @param _from The address to transfer from.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transferInternal(address _from, address _to, uint256 _value) internal returns (bool success) {
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
return true;
}
/**
* Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFromInternal(address _from, address _to, uint256 _value) internal returns (bool success) {
require(_value >= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
return transferInternal(_from, _to, _value);
}
} | approve | function approve(address _spender, uint256 _value) returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
| /**
* Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/ | NatSpecMultiLine | v0.4.11+commit.68ef5810 | bzzr://520b39c434969b3452207146d6707e4c87a166a43c7bf277f368ab5aa6b45faf | {
"func_code_index": [
1944,
2106
]
} | 2,183 |
|||
SlognToken | SlognToken.sol | 0xc0506ceb264b057182a4c3ab8a0b910a545479f0 | Solidity | Token | contract Token {
/* Public variables of the token */
string public standard;
string public name;
string public symbol;
uint8 public decimals;
uint256 public _totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* ERC20 Events */
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function Token(uint256 initialSupply, string _standard, string _name, string _symbol, uint8 _decimals) {
_totalSupply = initialSupply;
balanceOf[this] = initialSupply;
standard = _standard;
name = _name;
symbol = _symbol;
decimals = _decimals;
}
/* Get burnable total supply */
function totalSupply() constant returns(uint256 supply) {
return _totalSupply;
}
/**
* Transfer token logic
* @param _from The address to transfer from.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transferInternal(address _from, address _to, uint256 _value) internal returns (bool success) {
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
return true;
}
/**
* Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFromInternal(address _from, address _to, uint256 _value) internal returns (bool success) {
require(_value >= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
return transferInternal(_from, _to, _value);
}
} | transferFromInternal | function transferFromInternal(address _from, address _to, uint256 _value) internal returns (bool success) {
require(_value >= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
return transferInternal(_from, _to, _value);
}
| /**
* Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/ | NatSpecMultiLine | v0.4.11+commit.68ef5810 | bzzr://520b39c434969b3452207146d6707e4c87a166a43c7bf277f368ab5aa6b45faf | {
"func_code_index": [
2391,
2696
]
} | 2,184 |
|||
SlognToken | SlognToken.sol | 0xc0506ceb264b057182a4c3ab8a0b910a545479f0 | Solidity | ICO | contract ICO {
uint256 public PRE_ICO_SINCE = 1500303600; // 07/17/2017 @ 15:00 (UTC)
uint256 public PRE_ICO_TILL = 1500476400; // 07/19/2017 @ 15:00 (UTC)
uint256 public constant PRE_ICO_BONUS_RATE = 70;
uint256 public constant PRE_ICO_SLGN_LESS = 5000 ether; // upper limit for pre ico is 5k ether
uint256 public ICO_SINCE = 1500994800; // 07/25/2017 @ 9:00am (UTC)
uint256 public ICO_TILL = 1502809200; // 08/15/2017 @ 9:00am (UTC)
uint256 public constant ICO_BONUS1_SLGN_LESS = 20000 ether; // bonus 1 will work only if 20000 eth were collected during first phase of ico
uint256 public constant ICO_BONUS1_RATE = 30; // bonus 1 rate
uint256 public constant ICO_BONUS2_SLGN_LESS = 50000 ether; // bonus 1 will work only if 50000 eth were collected during second phase of ico
uint256 public constant ICO_BONUS2_RATE = 15; // bonus 2 rate
uint256 public totalSoldSlogns;
/* This generates a public event on the blockchain that will notify clients */
event BonusEarned(address target, uint256 bonus);
/**
* Calculate amount of premium bonuses
* @param icoStep identifies is it pre-ico (equals 0) or ico (equals 1)
* @param totalSoldSlogns total amount of already sold slogn tokens.
* @param soldSlogns total amount sold slogns in current transaction.
*/
function calculateBonus(uint8 icoStep, uint256 totalSoldSlogns, uint256 soldSlogns) returns (uint256) {
if(icoStep == 1) {
// pre ico
return soldSlogns / 100 * PRE_ICO_BONUS_RATE;
}
else if(icoStep == 2) {
// ico
if(totalSoldSlogns > ICO_BONUS1_SLGN_LESS + ICO_BONUS2_SLGN_LESS) {
return 0;
}
uint256 availableForBonus1 = ICO_BONUS1_SLGN_LESS - totalSoldSlogns;
uint256 tmp = soldSlogns;
uint256 bonus = 0;
uint256 tokensForBonus1 = 0;
if(availableForBonus1 > 0 && availableForBonus1 <= ICO_BONUS1_SLGN_LESS) {
tokensForBonus1 = tmp > availableForBonus1 ? availableForBonus1 : tmp;
bonus += tokensForBonus1 / 100 * ICO_BONUS1_RATE;
tmp -= tokensForBonus1;
}
uint256 availableForBonus2 = (ICO_BONUS2_SLGN_LESS + ICO_BONUS1_SLGN_LESS) - totalSoldSlogns - tokensForBonus1;
uint256 tokensForBonus2 = 0;
if(availableForBonus2 > 0 && availableForBonus2 <= ICO_BONUS2_SLGN_LESS) {
tokensForBonus2 = tmp > availableForBonus2 ? availableForBonus2 : tmp;
bonus += tokensForBonus2 / 100 * ICO_BONUS2_RATE;
tmp -= tokensForBonus2;
}
return bonus;
}
return 0;
}
} | calculateBonus | function calculateBonus(uint8 icoStep, uint256 totalSoldSlogns, uint256 soldSlogns) returns (uint256) {
if(icoStep == 1) {
// pre ico
return soldSlogns / 100 * PRE_ICO_BONUS_RATE;
}
else if(icoStep == 2) {
// ico
if(totalSoldSlogns > ICO_BONUS1_SLGN_LESS + ICO_BONUS2_SLGN_LESS) {
return 0;
}
uint256 availableForBonus1 = ICO_BONUS1_SLGN_LESS - totalSoldSlogns;
uint256 tmp = soldSlogns;
uint256 bonus = 0;
uint256 tokensForBonus1 = 0;
if(availableForBonus1 > 0 && availableForBonus1 <= ICO_BONUS1_SLGN_LESS) {
tokensForBonus1 = tmp > availableForBonus1 ? availableForBonus1 : tmp;
bonus += tokensForBonus1 / 100 * ICO_BONUS1_RATE;
tmp -= tokensForBonus1;
}
uint256 availableForBonus2 = (ICO_BONUS2_SLGN_LESS + ICO_BONUS1_SLGN_LESS) - totalSoldSlogns - tokensForBonus1;
uint256 tokensForBonus2 = 0;
if(availableForBonus2 > 0 && availableForBonus2 <= ICO_BONUS2_SLGN_LESS) {
tokensForBonus2 = tmp > availableForBonus2 ? availableForBonus2 : tmp;
bonus += tokensForBonus2 / 100 * ICO_BONUS2_RATE;
tmp -= tokensForBonus2;
}
return bonus;
}
return 0;
}
| /**
* Calculate amount of premium bonuses
* @param icoStep identifies is it pre-ico (equals 0) or ico (equals 1)
* @param totalSoldSlogns total amount of already sold slogn tokens.
* @param soldSlogns total amount sold slogns in current transaction.
*/ | NatSpecMultiLine | v0.4.11+commit.68ef5810 | bzzr://520b39c434969b3452207146d6707e4c87a166a43c7bf277f368ab5aa6b45faf | {
"func_code_index": [
1525,
2977
]
} | 2,185 |
|||
SlognToken | SlognToken.sol | 0xc0506ceb264b057182a4c3ab8a0b910a545479f0 | Solidity | EscrowICO | contract EscrowICO is Token, ICO {
uint256 public constant MIN_PRE_ICO_SLOGN_COLLECTED = 1000 ether; // PRE ICO is successful only if sold 10.000.000 slogns
uint256 public constant MIN_ICO_SLOGN_COLLECTED = 1000 ether; // ICO is successful only if sold 100.000.000 slogns
bool public isTransactionsAllowed;
uint256 public totalSoldSlogns;
mapping (address => uint256) public preIcoEthers;
mapping (address => uint256) public icoEthers;
event RefundEth(address indexed owner, uint256 value);
event IcoFinished();
function EscrowICO() {
isTransactionsAllowed = false;
}
function getIcoStep(uint256 time) returns (uint8 step) {
if(time >= PRE_ICO_SINCE && time <= PRE_ICO_TILL) {
return 1;
}
else if(time >= ICO_SINCE && time <= ICO_TILL) {
// ico shoud fail if collected less than 1000 slogns during pre ico
if(totalSoldSlogns >= MIN_PRE_ICO_SLOGN_COLLECTED) {
return 2;
}
}
return 0;
}
/**
* officially finish ICO, only allowed after ICO is ended
*/
function icoFinishInternal(uint256 time) internal returns (bool) {
if(time <= ICO_TILL) {
return false;
}
if(totalSoldSlogns >= MIN_ICO_SLOGN_COLLECTED) {
// burn tokens assigned to smart contract
_totalSupply = _totalSupply - balanceOf[this];
balanceOf[this] = 0;
// allow transactions for everyone
isTransactionsAllowed = true;
IcoFinished();
return true;
}
return false;
}
/**
* refund ico method
*/
function refundInternal(uint256 time) internal returns (bool) {
if(time <= PRE_ICO_TILL) {
return false;
}
if(totalSoldSlogns >= MIN_PRE_ICO_SLOGN_COLLECTED) {
return false;
}
uint256 transferedEthers;
transferedEthers = preIcoEthers[msg.sender];
if(transferedEthers > 0) {
preIcoEthers[msg.sender] = 0;
balanceOf[msg.sender] = 0;
msg.sender.transfer(transferedEthers);
RefundEth(msg.sender, transferedEthers);
return true;
}
return false;
}
} | icoFinishInternal | function icoFinishInternal(uint256 time) internal returns (bool) {
if(time <= ICO_TILL) {
return false;
}
if(totalSoldSlogns >= MIN_ICO_SLOGN_COLLECTED) {
// burn tokens assigned to smart contract
_totalSupply = _totalSupply - balanceOf[this];
balanceOf[this] = 0;
// allow transactions for everyone
isTransactionsAllowed = true;
IcoFinished();
return true;
}
return false;
}
| /**
* officially finish ICO, only allowed after ICO is ended
*/ | NatSpecMultiLine | v0.4.11+commit.68ef5810 | bzzr://520b39c434969b3452207146d6707e4c87a166a43c7bf277f368ab5aa6b45faf | {
"func_code_index": [
1182,
1730
]
} | 2,186 |
|||
SlognToken | SlognToken.sol | 0xc0506ceb264b057182a4c3ab8a0b910a545479f0 | Solidity | EscrowICO | contract EscrowICO is Token, ICO {
uint256 public constant MIN_PRE_ICO_SLOGN_COLLECTED = 1000 ether; // PRE ICO is successful only if sold 10.000.000 slogns
uint256 public constant MIN_ICO_SLOGN_COLLECTED = 1000 ether; // ICO is successful only if sold 100.000.000 slogns
bool public isTransactionsAllowed;
uint256 public totalSoldSlogns;
mapping (address => uint256) public preIcoEthers;
mapping (address => uint256) public icoEthers;
event RefundEth(address indexed owner, uint256 value);
event IcoFinished();
function EscrowICO() {
isTransactionsAllowed = false;
}
function getIcoStep(uint256 time) returns (uint8 step) {
if(time >= PRE_ICO_SINCE && time <= PRE_ICO_TILL) {
return 1;
}
else if(time >= ICO_SINCE && time <= ICO_TILL) {
// ico shoud fail if collected less than 1000 slogns during pre ico
if(totalSoldSlogns >= MIN_PRE_ICO_SLOGN_COLLECTED) {
return 2;
}
}
return 0;
}
/**
* officially finish ICO, only allowed after ICO is ended
*/
function icoFinishInternal(uint256 time) internal returns (bool) {
if(time <= ICO_TILL) {
return false;
}
if(totalSoldSlogns >= MIN_ICO_SLOGN_COLLECTED) {
// burn tokens assigned to smart contract
_totalSupply = _totalSupply - balanceOf[this];
balanceOf[this] = 0;
// allow transactions for everyone
isTransactionsAllowed = true;
IcoFinished();
return true;
}
return false;
}
/**
* refund ico method
*/
function refundInternal(uint256 time) internal returns (bool) {
if(time <= PRE_ICO_TILL) {
return false;
}
if(totalSoldSlogns >= MIN_PRE_ICO_SLOGN_COLLECTED) {
return false;
}
uint256 transferedEthers;
transferedEthers = preIcoEthers[msg.sender];
if(transferedEthers > 0) {
preIcoEthers[msg.sender] = 0;
balanceOf[msg.sender] = 0;
msg.sender.transfer(transferedEthers);
RefundEth(msg.sender, transferedEthers);
return true;
}
return false;
}
} | refundInternal | function refundInternal(uint256 time) internal returns (bool) {
if(time <= PRE_ICO_TILL) {
return false;
}
if(totalSoldSlogns >= MIN_PRE_ICO_SLOGN_COLLECTED) {
return false;
}
uint256 transferedEthers;
transferedEthers = preIcoEthers[msg.sender];
if(transferedEthers > 0) {
preIcoEthers[msg.sender] = 0;
balanceOf[msg.sender] = 0;
msg.sender.transfer(transferedEthers);
RefundEth(msg.sender, transferedEthers);
return true;
}
return false;
}
| /**
* refund ico method
*/ | NatSpecMultiLine | v0.4.11+commit.68ef5810 | bzzr://520b39c434969b3452207146d6707e4c87a166a43c7bf277f368ab5aa6b45faf | {
"func_code_index": [
1777,
2418
]
} | 2,187 |
|||
SlognToken | SlognToken.sol | 0xc0506ceb264b057182a4c3ab8a0b910a545479f0 | Solidity | SlognToken | contract SlognToken is Token, EscrowICO {
string public constant STANDARD = 'Slogn v0.1';
string public constant NAME = 'SLOGN';
string public constant SYMBOL = 'SLGN';
uint8 public constant PRECISION = 14;
uint256 public constant TOTAL_SUPPLY = 800000 ether; // initial total supply equals to 8.000.000.000 slogns or 800.000 eths
uint256 public constant CORE_TEAM_TOKENS = TOTAL_SUPPLY / 100 * 15; // 15%
uint256 public constant ADVISORY_BOARD_TOKENS = TOTAL_SUPPLY / 1000 * 15; // 1.5%
uint256 public constant OPENSOURCE_TOKENS = TOTAL_SUPPLY / 1000 * 75; // 7.5%
uint256 public constant RESERVE_TOKENS = TOTAL_SUPPLY / 100 * 5; // 5%
uint256 public constant BOUNTY_TOKENS = TOTAL_SUPPLY / 100; // 1%
address public advisoryBoardFundManager;
address public opensourceFundManager;
address public reserveFundManager;
address public bountyFundManager;
address public ethFundManager;
address public owner;
/* This generates a public event on the blockchain that will notify clients */
event BonusEarned(address target, uint256 bonus);
/* Modifiers */
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
/* Initializes contract with initial supply tokens to the creator of the contract */
function SlognToken(
address [] coreTeam,
address _advisoryBoardFundManager,
address _opensourceFundManager,
address _reserveFundManager,
address _bountyFundManager,
address _ethFundManager
)
Token (TOTAL_SUPPLY, STANDARD, NAME, SYMBOL, PRECISION)
EscrowICO()
{
owner = msg.sender;
advisoryBoardFundManager = _advisoryBoardFundManager;
opensourceFundManager = _opensourceFundManager;
reserveFundManager = _reserveFundManager;
bountyFundManager = _bountyFundManager;
ethFundManager = _ethFundManager;
// transfer tokens to core team
uint256 tokensPerMember = CORE_TEAM_TOKENS / coreTeam.length;
for(uint8 i = 0; i < coreTeam.length; i++) {
transferInternal(this, coreTeam[i], tokensPerMember);
}
// Advisory board fund
transferInternal(this, advisoryBoardFundManager, ADVISORY_BOARD_TOKENS);
// Opensource fund
transferInternal(this, opensourceFundManager, OPENSOURCE_TOKENS);
// Reserve fund
transferInternal(this, reserveFundManager, RESERVE_TOKENS);
// Bounty fund
transferInternal(this, bountyFundManager, BOUNTY_TOKENS);
}
function buyFor(address _user, uint256 ethers, uint time) internal returns (bool success) {
require(ethers > 0);
uint8 icoStep = getIcoStep(time);
require(icoStep == 1 || icoStep == 2);
// maximum collected amount for preico is 5000 ether
if(icoStep == 1 && (totalSoldSlogns + ethers) > 5000 ether) {
throw;
}
uint256 slognAmount = ethers; // calculates the amount
uint256 bonus = calculateBonus(icoStep, totalSoldSlogns, slognAmount);
// check for available slogns
require(balanceOf[this] >= slognAmount + bonus);
if(bonus > 0) {
BonusEarned(_user, bonus);
}
transferInternal(this, _user, slognAmount + bonus);
totalSoldSlogns += slognAmount;
if(icoStep == 1) {
preIcoEthers[_user] += ethers; // fill ethereum used for refund if goal not reached
}
if(icoStep == 2) {
icoEthers[_user] += ethers; // fill ethereum used for refund if goal not reached
}
return true;
}
/**
* Buy Slogn tokens
*/
function buy() payable {
buyFor(msg.sender, msg.value, block.timestamp);
}
/**
* Manage ethereum balance
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transferEther(address to, uint256 value) returns (bool success) {
if(msg.sender != ethFundManager) {
return false;
}
if(totalSoldSlogns < MIN_PRE_ICO_SLOGN_COLLECTED) {
return false;
}
if(this.balance < value) {
return false;
}
to.transfer(value);
return true;
}
/**
* Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool success) {
if(isTransactionsAllowed == false) {
if(msg.sender != bountyFundManager) {
return false;
}
}
return transferInternal(msg.sender, _to, _value);
}
/**
* Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if(isTransactionsAllowed == false) {
if(_from != bountyFundManager) {
return false;
}
}
return transferFromInternal(_from, _to, _value);
}
function refund() returns (bool) {
return refundInternal(block.timestamp);
}
function icoFinish() returns (bool) {
return icoFinishInternal(block.timestamp);
}
function setPreIcoDates(uint256 since, uint256 till) onlyOwner {
PRE_ICO_SINCE = since;
PRE_ICO_TILL = till;
}
function setIcoDates(uint256 since, uint256 till) onlyOwner {
ICO_SINCE = since;
ICO_TILL = till;
}
function setTransactionsAllowed(bool enabled) onlyOwner {
isTransactionsAllowed = enabled;
}
function () payable {
throw;
}
} | SlognToken | function SlognToken(
address [] coreTeam,
address _advisoryBoardFundManager,
address _opensourceFundManager,
address _reserveFundManager,
address _bountyFundManager,
address _ethFundManager
)
Token (TOTAL_SUPPLY, STANDARD, NAME, SYMBOL, PRECISION)
EscrowICO()
{
owner = msg.sender;
advisoryBoardFundManager = _advisoryBoardFundManager;
opensourceFundManager = _opensourceFundManager;
reserveFundManager = _reserveFundManager;
bountyFundManager = _bountyFundManager;
ethFundManager = _ethFundManager;
// transfer tokens to core team
uint256 tokensPerMember = CORE_TEAM_TOKENS / coreTeam.length;
for(uint8 i = 0; i < coreTeam.length; i++) {
transferInternal(this, coreTeam[i], tokensPerMember);
}
// Advisory board fund
transferInternal(this, advisoryBoardFundManager, ADVISORY_BOARD_TOKENS);
// Opensource fund
transferInternal(this, opensourceFundManager, OPENSOURCE_TOKENS);
// Reserve fund
transferInternal(this, reserveFundManager, RESERVE_TOKENS);
// Bounty fund
transferInternal(this, bountyFundManager, BOUNTY_TOKENS);
}
| /* Initializes contract with initial supply tokens to the creator of the contract */ | Comment | v0.4.11+commit.68ef5810 | bzzr://520b39c434969b3452207146d6707e4c87a166a43c7bf277f368ab5aa6b45faf | {
"func_code_index": [
1374,
2649
]
} | 2,188 |
|||
SlognToken | SlognToken.sol | 0xc0506ceb264b057182a4c3ab8a0b910a545479f0 | Solidity | SlognToken | contract SlognToken is Token, EscrowICO {
string public constant STANDARD = 'Slogn v0.1';
string public constant NAME = 'SLOGN';
string public constant SYMBOL = 'SLGN';
uint8 public constant PRECISION = 14;
uint256 public constant TOTAL_SUPPLY = 800000 ether; // initial total supply equals to 8.000.000.000 slogns or 800.000 eths
uint256 public constant CORE_TEAM_TOKENS = TOTAL_SUPPLY / 100 * 15; // 15%
uint256 public constant ADVISORY_BOARD_TOKENS = TOTAL_SUPPLY / 1000 * 15; // 1.5%
uint256 public constant OPENSOURCE_TOKENS = TOTAL_SUPPLY / 1000 * 75; // 7.5%
uint256 public constant RESERVE_TOKENS = TOTAL_SUPPLY / 100 * 5; // 5%
uint256 public constant BOUNTY_TOKENS = TOTAL_SUPPLY / 100; // 1%
address public advisoryBoardFundManager;
address public opensourceFundManager;
address public reserveFundManager;
address public bountyFundManager;
address public ethFundManager;
address public owner;
/* This generates a public event on the blockchain that will notify clients */
event BonusEarned(address target, uint256 bonus);
/* Modifiers */
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
/* Initializes contract with initial supply tokens to the creator of the contract */
function SlognToken(
address [] coreTeam,
address _advisoryBoardFundManager,
address _opensourceFundManager,
address _reserveFundManager,
address _bountyFundManager,
address _ethFundManager
)
Token (TOTAL_SUPPLY, STANDARD, NAME, SYMBOL, PRECISION)
EscrowICO()
{
owner = msg.sender;
advisoryBoardFundManager = _advisoryBoardFundManager;
opensourceFundManager = _opensourceFundManager;
reserveFundManager = _reserveFundManager;
bountyFundManager = _bountyFundManager;
ethFundManager = _ethFundManager;
// transfer tokens to core team
uint256 tokensPerMember = CORE_TEAM_TOKENS / coreTeam.length;
for(uint8 i = 0; i < coreTeam.length; i++) {
transferInternal(this, coreTeam[i], tokensPerMember);
}
// Advisory board fund
transferInternal(this, advisoryBoardFundManager, ADVISORY_BOARD_TOKENS);
// Opensource fund
transferInternal(this, opensourceFundManager, OPENSOURCE_TOKENS);
// Reserve fund
transferInternal(this, reserveFundManager, RESERVE_TOKENS);
// Bounty fund
transferInternal(this, bountyFundManager, BOUNTY_TOKENS);
}
function buyFor(address _user, uint256 ethers, uint time) internal returns (bool success) {
require(ethers > 0);
uint8 icoStep = getIcoStep(time);
require(icoStep == 1 || icoStep == 2);
// maximum collected amount for preico is 5000 ether
if(icoStep == 1 && (totalSoldSlogns + ethers) > 5000 ether) {
throw;
}
uint256 slognAmount = ethers; // calculates the amount
uint256 bonus = calculateBonus(icoStep, totalSoldSlogns, slognAmount);
// check for available slogns
require(balanceOf[this] >= slognAmount + bonus);
if(bonus > 0) {
BonusEarned(_user, bonus);
}
transferInternal(this, _user, slognAmount + bonus);
totalSoldSlogns += slognAmount;
if(icoStep == 1) {
preIcoEthers[_user] += ethers; // fill ethereum used for refund if goal not reached
}
if(icoStep == 2) {
icoEthers[_user] += ethers; // fill ethereum used for refund if goal not reached
}
return true;
}
/**
* Buy Slogn tokens
*/
function buy() payable {
buyFor(msg.sender, msg.value, block.timestamp);
}
/**
* Manage ethereum balance
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transferEther(address to, uint256 value) returns (bool success) {
if(msg.sender != ethFundManager) {
return false;
}
if(totalSoldSlogns < MIN_PRE_ICO_SLOGN_COLLECTED) {
return false;
}
if(this.balance < value) {
return false;
}
to.transfer(value);
return true;
}
/**
* Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool success) {
if(isTransactionsAllowed == false) {
if(msg.sender != bountyFundManager) {
return false;
}
}
return transferInternal(msg.sender, _to, _value);
}
/**
* Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if(isTransactionsAllowed == false) {
if(_from != bountyFundManager) {
return false;
}
}
return transferFromInternal(_from, _to, _value);
}
function refund() returns (bool) {
return refundInternal(block.timestamp);
}
function icoFinish() returns (bool) {
return icoFinishInternal(block.timestamp);
}
function setPreIcoDates(uint256 since, uint256 till) onlyOwner {
PRE_ICO_SINCE = since;
PRE_ICO_TILL = till;
}
function setIcoDates(uint256 since, uint256 till) onlyOwner {
ICO_SINCE = since;
ICO_TILL = till;
}
function setTransactionsAllowed(bool enabled) onlyOwner {
isTransactionsAllowed = enabled;
}
function () payable {
throw;
}
} | buy | function buy() payable {
buyFor(msg.sender, msg.value, block.timestamp);
}
| /**
* Buy Slogn tokens
*/ | NatSpecMultiLine | v0.4.11+commit.68ef5810 | bzzr://520b39c434969b3452207146d6707e4c87a166a43c7bf277f368ab5aa6b45faf | {
"func_code_index": [
3828,
3921
]
} | 2,189 |
|||
SlognToken | SlognToken.sol | 0xc0506ceb264b057182a4c3ab8a0b910a545479f0 | Solidity | SlognToken | contract SlognToken is Token, EscrowICO {
string public constant STANDARD = 'Slogn v0.1';
string public constant NAME = 'SLOGN';
string public constant SYMBOL = 'SLGN';
uint8 public constant PRECISION = 14;
uint256 public constant TOTAL_SUPPLY = 800000 ether; // initial total supply equals to 8.000.000.000 slogns or 800.000 eths
uint256 public constant CORE_TEAM_TOKENS = TOTAL_SUPPLY / 100 * 15; // 15%
uint256 public constant ADVISORY_BOARD_TOKENS = TOTAL_SUPPLY / 1000 * 15; // 1.5%
uint256 public constant OPENSOURCE_TOKENS = TOTAL_SUPPLY / 1000 * 75; // 7.5%
uint256 public constant RESERVE_TOKENS = TOTAL_SUPPLY / 100 * 5; // 5%
uint256 public constant BOUNTY_TOKENS = TOTAL_SUPPLY / 100; // 1%
address public advisoryBoardFundManager;
address public opensourceFundManager;
address public reserveFundManager;
address public bountyFundManager;
address public ethFundManager;
address public owner;
/* This generates a public event on the blockchain that will notify clients */
event BonusEarned(address target, uint256 bonus);
/* Modifiers */
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
/* Initializes contract with initial supply tokens to the creator of the contract */
function SlognToken(
address [] coreTeam,
address _advisoryBoardFundManager,
address _opensourceFundManager,
address _reserveFundManager,
address _bountyFundManager,
address _ethFundManager
)
Token (TOTAL_SUPPLY, STANDARD, NAME, SYMBOL, PRECISION)
EscrowICO()
{
owner = msg.sender;
advisoryBoardFundManager = _advisoryBoardFundManager;
opensourceFundManager = _opensourceFundManager;
reserveFundManager = _reserveFundManager;
bountyFundManager = _bountyFundManager;
ethFundManager = _ethFundManager;
// transfer tokens to core team
uint256 tokensPerMember = CORE_TEAM_TOKENS / coreTeam.length;
for(uint8 i = 0; i < coreTeam.length; i++) {
transferInternal(this, coreTeam[i], tokensPerMember);
}
// Advisory board fund
transferInternal(this, advisoryBoardFundManager, ADVISORY_BOARD_TOKENS);
// Opensource fund
transferInternal(this, opensourceFundManager, OPENSOURCE_TOKENS);
// Reserve fund
transferInternal(this, reserveFundManager, RESERVE_TOKENS);
// Bounty fund
transferInternal(this, bountyFundManager, BOUNTY_TOKENS);
}
function buyFor(address _user, uint256 ethers, uint time) internal returns (bool success) {
require(ethers > 0);
uint8 icoStep = getIcoStep(time);
require(icoStep == 1 || icoStep == 2);
// maximum collected amount for preico is 5000 ether
if(icoStep == 1 && (totalSoldSlogns + ethers) > 5000 ether) {
throw;
}
uint256 slognAmount = ethers; // calculates the amount
uint256 bonus = calculateBonus(icoStep, totalSoldSlogns, slognAmount);
// check for available slogns
require(balanceOf[this] >= slognAmount + bonus);
if(bonus > 0) {
BonusEarned(_user, bonus);
}
transferInternal(this, _user, slognAmount + bonus);
totalSoldSlogns += slognAmount;
if(icoStep == 1) {
preIcoEthers[_user] += ethers; // fill ethereum used for refund if goal not reached
}
if(icoStep == 2) {
icoEthers[_user] += ethers; // fill ethereum used for refund if goal not reached
}
return true;
}
/**
* Buy Slogn tokens
*/
function buy() payable {
buyFor(msg.sender, msg.value, block.timestamp);
}
/**
* Manage ethereum balance
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transferEther(address to, uint256 value) returns (bool success) {
if(msg.sender != ethFundManager) {
return false;
}
if(totalSoldSlogns < MIN_PRE_ICO_SLOGN_COLLECTED) {
return false;
}
if(this.balance < value) {
return false;
}
to.transfer(value);
return true;
}
/**
* Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool success) {
if(isTransactionsAllowed == false) {
if(msg.sender != bountyFundManager) {
return false;
}
}
return transferInternal(msg.sender, _to, _value);
}
/**
* Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if(isTransactionsAllowed == false) {
if(_from != bountyFundManager) {
return false;
}
}
return transferFromInternal(_from, _to, _value);
}
function refund() returns (bool) {
return refundInternal(block.timestamp);
}
function icoFinish() returns (bool) {
return icoFinishInternal(block.timestamp);
}
function setPreIcoDates(uint256 since, uint256 till) onlyOwner {
PRE_ICO_SINCE = since;
PRE_ICO_TILL = till;
}
function setIcoDates(uint256 since, uint256 till) onlyOwner {
ICO_SINCE = since;
ICO_TILL = till;
}
function setTransactionsAllowed(bool enabled) onlyOwner {
isTransactionsAllowed = enabled;
}
function () payable {
throw;
}
} | transferEther | function transferEther(address to, uint256 value) returns (bool success) {
if(msg.sender != ethFundManager) {
return false;
}
if(totalSoldSlogns < MIN_PRE_ICO_SLOGN_COLLECTED) {
return false;
}
if(this.balance < value) {
return false;
}
to.transfer(value);
return true;
}
| /**
* Manage ethereum balance
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/ | NatSpecMultiLine | v0.4.11+commit.68ef5810 | bzzr://520b39c434969b3452207146d6707e4c87a166a43c7bf277f368ab5aa6b45faf | {
"func_code_index": [
4071,
4471
]
} | 2,190 |
|||
SlognToken | SlognToken.sol | 0xc0506ceb264b057182a4c3ab8a0b910a545479f0 | Solidity | SlognToken | contract SlognToken is Token, EscrowICO {
string public constant STANDARD = 'Slogn v0.1';
string public constant NAME = 'SLOGN';
string public constant SYMBOL = 'SLGN';
uint8 public constant PRECISION = 14;
uint256 public constant TOTAL_SUPPLY = 800000 ether; // initial total supply equals to 8.000.000.000 slogns or 800.000 eths
uint256 public constant CORE_TEAM_TOKENS = TOTAL_SUPPLY / 100 * 15; // 15%
uint256 public constant ADVISORY_BOARD_TOKENS = TOTAL_SUPPLY / 1000 * 15; // 1.5%
uint256 public constant OPENSOURCE_TOKENS = TOTAL_SUPPLY / 1000 * 75; // 7.5%
uint256 public constant RESERVE_TOKENS = TOTAL_SUPPLY / 100 * 5; // 5%
uint256 public constant BOUNTY_TOKENS = TOTAL_SUPPLY / 100; // 1%
address public advisoryBoardFundManager;
address public opensourceFundManager;
address public reserveFundManager;
address public bountyFundManager;
address public ethFundManager;
address public owner;
/* This generates a public event on the blockchain that will notify clients */
event BonusEarned(address target, uint256 bonus);
/* Modifiers */
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
/* Initializes contract with initial supply tokens to the creator of the contract */
function SlognToken(
address [] coreTeam,
address _advisoryBoardFundManager,
address _opensourceFundManager,
address _reserveFundManager,
address _bountyFundManager,
address _ethFundManager
)
Token (TOTAL_SUPPLY, STANDARD, NAME, SYMBOL, PRECISION)
EscrowICO()
{
owner = msg.sender;
advisoryBoardFundManager = _advisoryBoardFundManager;
opensourceFundManager = _opensourceFundManager;
reserveFundManager = _reserveFundManager;
bountyFundManager = _bountyFundManager;
ethFundManager = _ethFundManager;
// transfer tokens to core team
uint256 tokensPerMember = CORE_TEAM_TOKENS / coreTeam.length;
for(uint8 i = 0; i < coreTeam.length; i++) {
transferInternal(this, coreTeam[i], tokensPerMember);
}
// Advisory board fund
transferInternal(this, advisoryBoardFundManager, ADVISORY_BOARD_TOKENS);
// Opensource fund
transferInternal(this, opensourceFundManager, OPENSOURCE_TOKENS);
// Reserve fund
transferInternal(this, reserveFundManager, RESERVE_TOKENS);
// Bounty fund
transferInternal(this, bountyFundManager, BOUNTY_TOKENS);
}
function buyFor(address _user, uint256 ethers, uint time) internal returns (bool success) {
require(ethers > 0);
uint8 icoStep = getIcoStep(time);
require(icoStep == 1 || icoStep == 2);
// maximum collected amount for preico is 5000 ether
if(icoStep == 1 && (totalSoldSlogns + ethers) > 5000 ether) {
throw;
}
uint256 slognAmount = ethers; // calculates the amount
uint256 bonus = calculateBonus(icoStep, totalSoldSlogns, slognAmount);
// check for available slogns
require(balanceOf[this] >= slognAmount + bonus);
if(bonus > 0) {
BonusEarned(_user, bonus);
}
transferInternal(this, _user, slognAmount + bonus);
totalSoldSlogns += slognAmount;
if(icoStep == 1) {
preIcoEthers[_user] += ethers; // fill ethereum used for refund if goal not reached
}
if(icoStep == 2) {
icoEthers[_user] += ethers; // fill ethereum used for refund if goal not reached
}
return true;
}
/**
* Buy Slogn tokens
*/
function buy() payable {
buyFor(msg.sender, msg.value, block.timestamp);
}
/**
* Manage ethereum balance
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transferEther(address to, uint256 value) returns (bool success) {
if(msg.sender != ethFundManager) {
return false;
}
if(totalSoldSlogns < MIN_PRE_ICO_SLOGN_COLLECTED) {
return false;
}
if(this.balance < value) {
return false;
}
to.transfer(value);
return true;
}
/**
* Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool success) {
if(isTransactionsAllowed == false) {
if(msg.sender != bountyFundManager) {
return false;
}
}
return transferInternal(msg.sender, _to, _value);
}
/**
* Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if(isTransactionsAllowed == false) {
if(_from != bountyFundManager) {
return false;
}
}
return transferFromInternal(_from, _to, _value);
}
function refund() returns (bool) {
return refundInternal(block.timestamp);
}
function icoFinish() returns (bool) {
return icoFinishInternal(block.timestamp);
}
function setPreIcoDates(uint256 since, uint256 till) onlyOwner {
PRE_ICO_SINCE = since;
PRE_ICO_TILL = till;
}
function setIcoDates(uint256 since, uint256 till) onlyOwner {
ICO_SINCE = since;
ICO_TILL = till;
}
function setTransactionsAllowed(bool enabled) onlyOwner {
isTransactionsAllowed = enabled;
}
function () payable {
throw;
}
} | transfer | function transfer(address _to, uint256 _value) returns (bool success) {
if(isTransactionsAllowed == false) {
if(msg.sender != bountyFundManager) {
return false;
}
}
return transferInternal(msg.sender, _to, _value);
}
| /**
* Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/ | NatSpecMultiLine | v0.4.11+commit.68ef5810 | bzzr://520b39c434969b3452207146d6707e4c87a166a43c7bf277f368ab5aa6b45faf | {
"func_code_index": [
4638,
4936
]
} | 2,191 |
|||
SlognToken | SlognToken.sol | 0xc0506ceb264b057182a4c3ab8a0b910a545479f0 | Solidity | SlognToken | contract SlognToken is Token, EscrowICO {
string public constant STANDARD = 'Slogn v0.1';
string public constant NAME = 'SLOGN';
string public constant SYMBOL = 'SLGN';
uint8 public constant PRECISION = 14;
uint256 public constant TOTAL_SUPPLY = 800000 ether; // initial total supply equals to 8.000.000.000 slogns or 800.000 eths
uint256 public constant CORE_TEAM_TOKENS = TOTAL_SUPPLY / 100 * 15; // 15%
uint256 public constant ADVISORY_BOARD_TOKENS = TOTAL_SUPPLY / 1000 * 15; // 1.5%
uint256 public constant OPENSOURCE_TOKENS = TOTAL_SUPPLY / 1000 * 75; // 7.5%
uint256 public constant RESERVE_TOKENS = TOTAL_SUPPLY / 100 * 5; // 5%
uint256 public constant BOUNTY_TOKENS = TOTAL_SUPPLY / 100; // 1%
address public advisoryBoardFundManager;
address public opensourceFundManager;
address public reserveFundManager;
address public bountyFundManager;
address public ethFundManager;
address public owner;
/* This generates a public event on the blockchain that will notify clients */
event BonusEarned(address target, uint256 bonus);
/* Modifiers */
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
/* Initializes contract with initial supply tokens to the creator of the contract */
function SlognToken(
address [] coreTeam,
address _advisoryBoardFundManager,
address _opensourceFundManager,
address _reserveFundManager,
address _bountyFundManager,
address _ethFundManager
)
Token (TOTAL_SUPPLY, STANDARD, NAME, SYMBOL, PRECISION)
EscrowICO()
{
owner = msg.sender;
advisoryBoardFundManager = _advisoryBoardFundManager;
opensourceFundManager = _opensourceFundManager;
reserveFundManager = _reserveFundManager;
bountyFundManager = _bountyFundManager;
ethFundManager = _ethFundManager;
// transfer tokens to core team
uint256 tokensPerMember = CORE_TEAM_TOKENS / coreTeam.length;
for(uint8 i = 0; i < coreTeam.length; i++) {
transferInternal(this, coreTeam[i], tokensPerMember);
}
// Advisory board fund
transferInternal(this, advisoryBoardFundManager, ADVISORY_BOARD_TOKENS);
// Opensource fund
transferInternal(this, opensourceFundManager, OPENSOURCE_TOKENS);
// Reserve fund
transferInternal(this, reserveFundManager, RESERVE_TOKENS);
// Bounty fund
transferInternal(this, bountyFundManager, BOUNTY_TOKENS);
}
function buyFor(address _user, uint256 ethers, uint time) internal returns (bool success) {
require(ethers > 0);
uint8 icoStep = getIcoStep(time);
require(icoStep == 1 || icoStep == 2);
// maximum collected amount for preico is 5000 ether
if(icoStep == 1 && (totalSoldSlogns + ethers) > 5000 ether) {
throw;
}
uint256 slognAmount = ethers; // calculates the amount
uint256 bonus = calculateBonus(icoStep, totalSoldSlogns, slognAmount);
// check for available slogns
require(balanceOf[this] >= slognAmount + bonus);
if(bonus > 0) {
BonusEarned(_user, bonus);
}
transferInternal(this, _user, slognAmount + bonus);
totalSoldSlogns += slognAmount;
if(icoStep == 1) {
preIcoEthers[_user] += ethers; // fill ethereum used for refund if goal not reached
}
if(icoStep == 2) {
icoEthers[_user] += ethers; // fill ethereum used for refund if goal not reached
}
return true;
}
/**
* Buy Slogn tokens
*/
function buy() payable {
buyFor(msg.sender, msg.value, block.timestamp);
}
/**
* Manage ethereum balance
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transferEther(address to, uint256 value) returns (bool success) {
if(msg.sender != ethFundManager) {
return false;
}
if(totalSoldSlogns < MIN_PRE_ICO_SLOGN_COLLECTED) {
return false;
}
if(this.balance < value) {
return false;
}
to.transfer(value);
return true;
}
/**
* Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool success) {
if(isTransactionsAllowed == false) {
if(msg.sender != bountyFundManager) {
return false;
}
}
return transferInternal(msg.sender, _to, _value);
}
/**
* Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if(isTransactionsAllowed == false) {
if(_from != bountyFundManager) {
return false;
}
}
return transferFromInternal(_from, _to, _value);
}
function refund() returns (bool) {
return refundInternal(block.timestamp);
}
function icoFinish() returns (bool) {
return icoFinishInternal(block.timestamp);
}
function setPreIcoDates(uint256 since, uint256 till) onlyOwner {
PRE_ICO_SINCE = since;
PRE_ICO_TILL = till;
}
function setIcoDates(uint256 since, uint256 till) onlyOwner {
ICO_SINCE = since;
ICO_TILL = till;
}
function setTransactionsAllowed(bool enabled) onlyOwner {
isTransactionsAllowed = enabled;
}
function () payable {
throw;
}
} | transferFrom | function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if(isTransactionsAllowed == false) {
if(_from != bountyFundManager) {
return false;
}
}
return transferFromInternal(_from, _to, _value);
}
| /**
* Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/ | NatSpecMultiLine | v0.4.11+commit.68ef5810 | bzzr://520b39c434969b3452207146d6707e4c87a166a43c7bf277f368ab5aa6b45faf | {
"func_code_index": [
5221,
5532
]
} | 2,192 |
|||
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | addReward | function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
| // Add a new reward token to be distributed to stakers | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
3150,
3622
]
} | 2,193 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | approveRewardDistributor | function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
| // Modify approval for an address to call notifyRewardAmount | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
3687,
3980
]
} | 2,194 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | setBoost | function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
| //set boost parameters | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
4007,
4428
]
} | 2,195 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | setKickIncentive | function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
| //set kick incentive | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
4615,
4895
]
} | 2,196 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | shutdown | function shutdown() external onlyOwner {
isShutdown = true;
}
| //shutdown the contract. | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
4924,
4993
]
} | 2,197 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | setApprovals | function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
| //set approvals for rewards escrow | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
5032,
5212
]
} | 2,198 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | _rewardPerToken | function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
| /* ========== VIEWS ========== */ | Comment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
5251,
5809
]
} | 2,199 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | claimableRewards | function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
| // Address and claimable amount of all reward tokens for the given account | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
6818,
7361
]
} | 2,200 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | rewardWeightOf | function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
| // Total BOOSTED balance of an account, including unlocked but not withdrawn tokens | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
7449,
7570
]
} | 2,201 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | lockedBalanceOf | function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
| // total token balance of an account, including unlocked but not withdrawn tokens | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
7656,
7777
]
} | 2,202 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | balanceOf | function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
| //BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
7893,
8909
]
} | 2,203 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | balanceAtEpochOf | function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
| //BOOSTED balance of an account which only includes properly locked tokens at the given epoch | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
9007,
10147
]
} | 2,204 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | totalSupply | function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
| //supply of all properly locked BOOSTED balances at most recent eligible epoch | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
10230,
10913
]
} | 2,205 |
|
PopLocker | contracts/core/dao/PopLocker.sol | 0x429902c1f43b583e099a0aa5b5c8e0fd40c54435 | Solidity | PopLocker | contract PopLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public stakingToken;
IRewardsEscrow public rewardsEscrow;
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// duration in seconds for rewards to be held in escrow
uint256 public escrowDuration;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 7 days;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 12;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment;
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor(IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow) public Ownable() {
_name = "Vote Locked POP Token";
_symbol = "vlPOP";
_decimals = 18;
stakingToken = _stakingToken;
rewardsEscrow = _rewardsEscrow;
escrowDuration = 365 days;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0, "rewards token does not exist");
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
function setEscrowDuration(uint256 duration) external onlyOwner {
emit EscrowDurationUpdated(escrowDuration, duration);
escrowDuration = duration;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract.
function shutdown() external onlyOwner {
isShutdown = true;
}
//set approvals for rewards escrow
function setApprovals() external {
IERC20(stakingToken).safeApprove(address(rewardsEscrow), 0);
IERC20(stakingToken).safeApprove(address(rewardsEscrow), uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance.mul(_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])).div(1e18).add(
rewards[_user][_rewardsToken]
);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns (uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns (uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) external view returns (uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) external view returns (uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if (uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != currentEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) internal updateReward(_account) {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment == 0 ? 1 : maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime)})
);
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
reward = _getDelayAdjustedReward(_checkDelay, locks[length - 1]);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
reward = reward.add(_getDelayAdjustedReward(_checkDelay, locks[i]));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
stakingToken.safeTransfer(_rewardAddress, reward);
emit KickReward(_rewardAddress, _account, reward);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
emit Relocked(_account, locked);
} else {
stakingToken.safeTransfer(_withdrawTo, locked);
emit Withdrawn(_account, locked);
}
}
function _getDelayAdjustedReward(uint256 _checkDelay, LockedBalance storage lockedBalance)
internal
view
returns (uint256)
{
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(lockedBalance.unlockTime)).div(rewardsDuration);
uint256 rRate = Math.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
return uint256(lockedBalance.amount).mul(rRate).div(denominator);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
// Claim all pending rewards
function getReward(address _account) public nonReentrant updateReward(_account) {
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
uint256 payout = reward.div(uint256(10));
uint256 escrowed = payout.mul(uint256(9));
IERC20(_rewardsToken).safeTransfer(_account, payout);
IRewardsEscrow(rewardsEscrow).lock(_account, escrowed, escrowDuration);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender], "not authorized");
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount);
event Relocked(address indexed _user, uint256 _amount);
event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | // POP locked in this contract will be entitled to voting rights for popcorn.network
// Based on CVX Locking contract for https://www.convexfinance.com/
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards | LineComment | totalSupplyAtEpoch | function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
| //supply of all properly locked BOOSTED balances at the given epoch | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | {
"func_code_index": [
10985,
11732
]
} | 2,206 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.