Unnamed: 0 int64 0 7.36k | comments stringlengths 3 35.2k | code_string stringlengths 1 527k | code stringlengths 1 527k | __index_level_0__ int64 0 88.6k |
|---|---|---|---|---|
4 | // Prevents delegatecall into the modified method | modifier noDelegateCall() {
checkNotDelegateCall();
_;
}
| modifier noDelegateCall() {
checkNotDelegateCall();
_;
}
| 24,961 |
14 | // 마켓이 구동중일때만 | modifier whenMarketRunning() {
require(marketPaused != true);
_;
}
| modifier whenMarketRunning() {
require(marketPaused != true);
_;
}
| 17,265 |
11 | // [NOT MANDATORY FOR ERC1400 STANDARD] 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 oldand the new allowance by unfortunate transaction ordering. One possible solution to mitigate thisrace condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: spender The address which will spend the funds. value The amount of tokens to be spent.return A boolean that indicates if the operation was successful. / | function approve(address spender, uint256 value) external returns (bool) {
require(spender != address(0), "A5"); // Transfer Blocked - Sender not eligible
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
| function approve(address spender, uint256 value) external returns (bool) {
require(spender != address(0), "A5"); // Transfer Blocked - Sender not eligible
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
| 16,701 |
5 | // 요정 소유주만 | modifier onlyMasterOf(uint256 fairyId) {
require(msg.sender == ownerOf(fairyId));
_;
}
| modifier onlyMasterOf(uint256 fairyId) {
require(msg.sender == ownerOf(fairyId));
_;
}
| 43,540 |
13 | // Returns random numbers as two a digits array / | function getDoubleDigits() public view returns(uint[MAX_DIGITS / 2] memory digits){
uint number = randomNumbers[randomNumbers.length - 1];
uint i = 0;
while (number > 0 && i < MAX_DIGITS / 2) {
uint digit = uint(number % 100);
number = number / 100;
digits[i] = digit;
i++;
}
return digits;
}
| function getDoubleDigits() public view returns(uint[MAX_DIGITS / 2] memory digits){
uint number = randomNumbers[randomNumbers.length - 1];
uint i = 0;
while (number > 0 && i < MAX_DIGITS / 2) {
uint digit = uint(number % 100);
number = number / 100;
digits[i] = digit;
i++;
}
return digits;
}
| 22,280 |
8 | // A mapping from owner address to count of tokens that address owns | mapping (address => uint256) ownershipTokenCount;
| mapping (address => uint256) ownershipTokenCount;
| 15,084 |
80 | // Generate the requestId | requestId = generateRequestId();
address mainPayee;
int256 mainExpectedAmount;
| requestId = generateRequestId();
address mainPayee;
int256 mainExpectedAmount;
| 80,505 |
34 | // requirements independent of current auction state: | require(
currentTime <= bidInput.deadline,
"AuctionBase::assertBidInputsOK: payment deadline expired"
);
if (_isSellerRegistrationRequired) {
require(
_isRegisteredSeller[bidInput.seller],
"AuctionBase::assertBidInputsOK: seller not registered"
);
}
| require(
currentTime <= bidInput.deadline,
"AuctionBase::assertBidInputsOK: payment deadline expired"
);
if (_isSellerRegistrationRequired) {
require(
_isRegisteredSeller[bidInput.seller],
"AuctionBase::assertBidInputsOK: seller not registered"
);
}
| 26,401 |
4 | // give approval or grant transaction permission to start | setApprovalForAll(contractAddress, true);
emit TokenCreated(newItemId);
| setApprovalForAll(contractAddress, true);
emit TokenCreated(newItemId);
| 15,203 |
47 | // Require that the owner didn't change after the LSP1 Call (Pending owner didn't automate the acceptOwnership call through LSP1) | require(
currentOwner == owner(),
"LSP14: newOwner MUST accept ownership in a separate transaction"
);
| require(
currentOwner == owner(),
"LSP14: newOwner MUST accept ownership in a separate transaction"
);
| 22,889 |
3 | // calculate the amounts to migrate to v3 | uint256 amount0V2ToMigrate = amount0V2.mul(params.percentageToMigrate) / 100;
uint256 amount1V2ToMigrate = amount1V2.mul(params.percentageToMigrate) / 100;
| uint256 amount0V2ToMigrate = amount0V2.mul(params.percentageToMigrate) / 100;
uint256 amount1V2ToMigrate = amount1V2.mul(params.percentageToMigrate) / 100;
| 15,548 |
68 | // This method can be used by the controller to extract mistakenly/sent tokens to this contract./_token The address of the token contract that you want to recover/set to 0 in case you want to extract ether. | function _claimStdTokens(address _token, address payable to) internal {
if (_token == address(0x0)) {
to.transfer(address(this).balance);
return;
}
uint balance = IERC20(_token).balanceOf(address(this));
(bool status,) = _token.call(abi.encodeWithSignature("transfer(address,uint256)", to, balance));
require(status, "call failed");
emit ClaimedTokens(_token, to, balance);
}
| function _claimStdTokens(address _token, address payable to) internal {
if (_token == address(0x0)) {
to.transfer(address(this).balance);
return;
}
uint balance = IERC20(_token).balanceOf(address(this));
(bool status,) = _token.call(abi.encodeWithSignature("transfer(address,uint256)", to, balance));
require(status, "call failed");
emit ClaimedTokens(_token, to, balance);
}
| 1,178 |
191 | // Distribute funds in escrow from blocked balance to the target address. _projectEscrowContractAddress An `address` of project`s escrow. _distributionTargetAddress Target `address`. _amount An `uint` amount to distribute. _tokenAddress An `address` of a token. / | function distributeFundsInEscrow(
address _projectEscrowContractAddress,
address _distributionTargetAddress,
uint _amount,
address _tokenAddress
)
internal
| function distributeFundsInEscrow(
address _projectEscrowContractAddress,
address _distributionTargetAddress,
uint _amount,
address _tokenAddress
)
internal
| 54,779 |
88 | // Transfer the yield tokens to the recipient. | TokenUtils.safeTransfer(yieldToken, recipient, amountYieldTokens);
return amountYieldTokens;
| TokenUtils.safeTransfer(yieldToken, recipient, amountYieldTokens);
return amountYieldTokens;
| 44,134 |
216 | // ========== RESTRICTED FUNCTIONS ========== / | function collectDaoShare(uint256 amount, address to) external {
require(hasRole(DAO_SHARE_COLLECTOR, msg.sender));
require(amount <= daoShare, "amount<=daoShare");
IDEIStablecoin(dei_contract_address).pool_mint(to, amount);
daoShare -= amount;
emit daoShareCollected(amount, to);
}
| function collectDaoShare(uint256 amount, address to) external {
require(hasRole(DAO_SHARE_COLLECTOR, msg.sender));
require(amount <= daoShare, "amount<=daoShare");
IDEIStablecoin(dei_contract_address).pool_mint(to, amount);
daoShare -= amount;
emit daoShareCollected(amount, to);
}
| 35,487 |
17 | // Contain all polls. Index - poll number. | Poll[] public polls;
| Poll[] public polls;
| 53,915 |
17 | // Token Setup | string public constant name = "CrimsonShares";
string public constant symbol = "RIM";
uint8 public constant decimals = 4;
uint256 private supply;
uint256 public icoPrice = 0.000001 ether;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
| string public constant name = "CrimsonShares";
string public constant symbol = "RIM";
uint8 public constant decimals = 4;
uint256 private supply;
uint256 public icoPrice = 0.000001 ether;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
| 38,036 |
164 | // Permanently disable the "escape hatch" mechanism for this smartwallet. This function call will revert if the smart wallet has alreadycalled `permanentlyDisableEscapeHatch` at any point in the past. No valueis returned from this function - it will either succeed or revert. minimumActionGas uint256 The minimum amount of gas that must beprovided to this call - be aware that additional gas must still be includedto account for the cost of overhead incurred up until the start of thisfunction call. userSignature bytes A signature that resolves to the public keyset for this account in storage slot zero, `_userSigningKey`. If the usersigning key is | function permanentlyDisableEscapeHatch(
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
| function permanentlyDisableEscapeHatch(
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
| 31,339 |
77 | // A proxy for Lido Ethereum 2.0 withdrawals manager contract. Though the Beacon chain already supports setting withdrawal credentials pointing to a smartcontract, the withdrawals specification is not yet final and might change before withdrawalsare enabled in the Merge network. This means that Lido cannot deploy the final implementationof the withdrawals manager contract yet. At the same time, it's desirable to have withdrawalcredentials pointing to a smart contract since this would avoid the need to migrate a lot ofvalidators to new withdrawal credentials once withdrawals are enabled. To solve this, Lido uses an upgradeable proxy controlled by the DAO. Initially, it | contract WithdrawalsManagerProxy is ERC1967Proxy {
/**
* @dev The address of Lido DAO Voting contract.
*/
address internal constant LIDO_VOTING = 0x2e59A20f205bB85a89C53f1936454680651E618e;
/**
* @dev Storage slot with the admin of the contract.
*
* Equals `bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)`.
*/
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Initializes the upgradeable proxy with the initial stub implementation.
*/
constructor() ERC1967Proxy(address(new WithdrawalsManagerStub()), new bytes(0)) {
_setAdmin(LIDO_VOTING);
}
/**
* @return Returns the current implementation address.
*/
function implementation() external view returns (address) {
return _implementation();
}
/**
* @dev Upgrades the proxy to a new implementation, optionally performing an additional
* setup call.
*
* Can only be called by the proxy admin until the proxy is ossified.
* Cannot be called after the proxy is ossified.
*
* Emits an {Upgraded} event.
*
* @param setupCalldata Data for the setup call. The call is skipped if data is empty.
*/
function proxy_upgradeTo(address newImplementation, bytes memory setupCalldata) external {
address admin = _getAdmin();
require(admin != address(0), "proxy: ossified");
require(msg.sender == admin, "proxy: unauthorized");
_upgradeTo(newImplementation);
if (setupCalldata.length > 0) {
Address.functionDelegateCall(newImplementation, setupCalldata, "proxy: setup failed");
}
}
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Returns the current admin of the proxy.
*/
function proxy_getAdmin() external view returns (address) {
return _getAdmin();
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function proxy_changeAdmin(address newAdmin) external {
address admin = _getAdmin();
require(msg.sender == admin, "proxy: unauthorized");
emit AdminChanged(admin, newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Returns whether the implementation is locked forever.
*/
function proxy_getIsOssified() external view returns (bool) {
return _getAdmin() == address(0);
}
} | contract WithdrawalsManagerProxy is ERC1967Proxy {
/**
* @dev The address of Lido DAO Voting contract.
*/
address internal constant LIDO_VOTING = 0x2e59A20f205bB85a89C53f1936454680651E618e;
/**
* @dev Storage slot with the admin of the contract.
*
* Equals `bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)`.
*/
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Initializes the upgradeable proxy with the initial stub implementation.
*/
constructor() ERC1967Proxy(address(new WithdrawalsManagerStub()), new bytes(0)) {
_setAdmin(LIDO_VOTING);
}
/**
* @return Returns the current implementation address.
*/
function implementation() external view returns (address) {
return _implementation();
}
/**
* @dev Upgrades the proxy to a new implementation, optionally performing an additional
* setup call.
*
* Can only be called by the proxy admin until the proxy is ossified.
* Cannot be called after the proxy is ossified.
*
* Emits an {Upgraded} event.
*
* @param setupCalldata Data for the setup call. The call is skipped if data is empty.
*/
function proxy_upgradeTo(address newImplementation, bytes memory setupCalldata) external {
address admin = _getAdmin();
require(admin != address(0), "proxy: ossified");
require(msg.sender == admin, "proxy: unauthorized");
_upgradeTo(newImplementation);
if (setupCalldata.length > 0) {
Address.functionDelegateCall(newImplementation, setupCalldata, "proxy: setup failed");
}
}
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Returns the current admin of the proxy.
*/
function proxy_getAdmin() external view returns (address) {
return _getAdmin();
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function proxy_changeAdmin(address newAdmin) external {
address admin = _getAdmin();
require(msg.sender == admin, "proxy: unauthorized");
emit AdminChanged(admin, newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Returns whether the implementation is locked forever.
*/
function proxy_getIsOssified() external view returns (bool) {
return _getAdmin() == address(0);
}
} | 81,006 |
11 | // two functions - one that returns tokenByIndex andanother one that returns tokenOfOwnerByIndex | function tokenByIndex(uint256 index) public override view returns(uint256) {
// make sure that the index is not out of bounds of the total supply
require(index < totalSupply(), 'global index is out of bounds!');
return _allTokens[index];
}
| function tokenByIndex(uint256 index) public override view returns(uint256) {
// make sure that the index is not out of bounds of the total supply
require(index < totalSupply(), 'global index is out of bounds!');
return _allTokens[index];
}
| 37,535 |
50 | // remove uint32 from whitelist. / | function removeWhiteListUint32(uint32[] storage whiteList,uint32 temp)internal returns (bool) {
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
if (i<len){
if (i!=len-1) {
whiteList[i] = whiteList[len-1];
}
whiteList.length--;
return true;
}
return false;
}
| function removeWhiteListUint32(uint32[] storage whiteList,uint32 temp)internal returns (bool) {
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
if (i<len){
if (i!=len-1) {
whiteList[i] = whiteList[len-1];
}
whiteList.length--;
return true;
}
return false;
}
| 70,605 |
2 | // Integer division of two numbers, truncating the quotient. / | function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
| function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
| 33,028 |
107 | // Check for approval and valid ownership | require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
| require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
| 15,107 |
502 | // To receive MATIC from swapRouter when swapping | receive() external payable {}
/**
* @dev Update the transfer tax rate.
* Can only be called by the current operator.
*/
function updateTransferTaxRate(uint16 _transferTaxRate) public onlyOperator {
require(_transferTaxRate <= MAXIMUM_TRANSFER_TAX_RATE, "::updateTransferTaxRate: Transfer tax rate must not exceed the maximum rate.");
emit TransferTaxRateUpdated(msg.sender, transferTaxRate, _transferTaxRate);
transferTaxRate = _transferTaxRate;
}
| receive() external payable {}
/**
* @dev Update the transfer tax rate.
* Can only be called by the current operator.
*/
function updateTransferTaxRate(uint16 _transferTaxRate) public onlyOperator {
require(_transferTaxRate <= MAXIMUM_TRANSFER_TAX_RATE, "::updateTransferTaxRate: Transfer tax rate must not exceed the maximum rate.");
emit TransferTaxRateUpdated(msg.sender, transferTaxRate, _transferTaxRate);
transferTaxRate = _transferTaxRate;
}
| 698 |
136 | // Verify the liquidity lock of the given address return bool: Is it locked return uint256 : time remaining 0 if unlocked return uint256 : The amount that is locked/ | function checkLiquidityLock(address addy) external view returns (bool, uint256, uint256) {//is Locked, time remaining, how much is locked
uint256 time = liquidityUnlockTime[addy];
time = (block.timestamp < time) ? time - block.timestamp : 0;
bool locked = false;
uint256 amt = 0;
if (time > 0) {
locked = true;
amt = IERC20(addy).balanceOf(address(this));
}
return (locked, time, amt);
}
| function checkLiquidityLock(address addy) external view returns (bool, uint256, uint256) {//is Locked, time remaining, how much is locked
uint256 time = liquidityUnlockTime[addy];
time = (block.timestamp < time) ? time - block.timestamp : 0;
bool locked = false;
uint256 amt = 0;
if (time > 0) {
locked = true;
amt = IERC20(addy).balanceOf(address(this));
}
return (locked, time, amt);
}
| 6,459 |
13 | // Structs// Keeps track of balance amounts in the balances array/ | struct Balance {
address owner;
uint amount;
}
| struct Balance {
address owner;
uint amount;
}
| 21,283 |
41 | // or 0-9 | (_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
| (_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
| 10,304 |
19 | // increments the value of latestTokenId / | function _incrementTokenId() private {
latestTokenId++;
}
| function _incrementTokenId() private {
latestTokenId++;
}
| 13,815 |
96 | // Transfer the ownership of a proxy owned Safe/manager address - Safe Manager/safe uint - Safe Id/usr address - Owner of the safe | function transferSAFEOwnership(
address manager,
uint safe,
address usr
| function transferSAFEOwnership(
address manager,
uint safe,
address usr
| 80,853 |
11 | // Pauses all token transfers. | // * See {ERC20Pausable} and {Pausable-_pause}.
// *
// * Requirements:
// *
// * - the caller must have the `PAUSER_ROLE`.
// */
// function pause() public virtual {
// require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause");
// _pause();
// }
| // * See {ERC20Pausable} and {Pausable-_pause}.
// *
// * Requirements:
// *
// * - the caller must have the `PAUSER_ROLE`.
// */
// function pause() public virtual {
// require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause");
// _pause();
// }
| 45,038 |
14 | // Uh oh: the patient should not be able to deposit the prescription a second time, obtaining more refills than authorized! | int prescriptionID2 = pharmacy2.depositPrescription(prescription);
pharmacy2.fillPrescription(prescriptionID2);
| int prescriptionID2 = pharmacy2.depositPrescription(prescription);
pharmacy2.fillPrescription(prescriptionID2);
| 20,485 |
29 | // check if bid duration is closed | Auction memory auction = auctionRegistry[_auctionId];
| Auction memory auction = auctionRegistry[_auctionId];
| 31,268 |
24 | // Open0x Ownable (by 0xInuarashi) | abstract contract Ownable {
address public owner;
event OwnershipTransferred(address indexed oldOwner_, address indexed newOwner_);
constructor() { owner = msg.sender; }
modifier onlyOwner {
require(owner == msg.sender, "Ownable: caller is not the owner");
_;
}
function _transferOwnership(address newOwner_) internal virtual {
address _oldOwner = owner;
owner = newOwner_;
emit OwnershipTransferred(_oldOwner, newOwner_);
}
function transferOwnership(address newOwner_) public virtual onlyOwner {
require(newOwner_ != address(0x0), "Ownable: new owner is the zero address!");
_transferOwnership(newOwner_);
}
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0x0));
}
}
| abstract contract Ownable {
address public owner;
event OwnershipTransferred(address indexed oldOwner_, address indexed newOwner_);
constructor() { owner = msg.sender; }
modifier onlyOwner {
require(owner == msg.sender, "Ownable: caller is not the owner");
_;
}
function _transferOwnership(address newOwner_) internal virtual {
address _oldOwner = owner;
owner = newOwner_;
emit OwnershipTransferred(_oldOwner, newOwner_);
}
function transferOwnership(address newOwner_) public virtual onlyOwner {
require(newOwner_ != address(0x0), "Ownable: new owner is the zero address!");
_transferOwnership(newOwner_);
}
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0x0));
}
}
| 14,008 |
131 | // Implementation of the basic standard multi-token. _Available since v3.1._ / | contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using SafeMath for uint256;
using Address for address;
// Mapping from token ID to account balances
mapping (uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/*
* bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
* bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
* bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
*
* => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
* 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
*/
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
/*
* bytes4(keccak256('uri(uint256)')) == 0x0e89341c
*/
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
/**
* @dev See {_setURI}.
*/
constructor (string memory uri_) public {
_setURI(uri_);
// register the supported interfaces to conform to ERC1155 via ERC165
_registerInterface(_INTERFACE_ID_ERC1155);
// register the supported interfaces to conform to ERC1155MetadataURI via ERC165
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) external view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
override
{
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
public
virtual
override
{
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][from] = _balances[id][from].sub(
amount,
"ERC1155: insufficient balance for transfer"
);
_balances[id][to] = _balances[id][to].add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] = _balances[id][account].add(amount);
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
_balances[id][account] = _balances[id][account].sub(
amount,
"ERC1155: burn amount exceeds balance"
);
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(
amounts[i],
"ERC1155: burn amount exceeds balance"
);
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
{ }
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
| contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using SafeMath for uint256;
using Address for address;
// Mapping from token ID to account balances
mapping (uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/*
* bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
* bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
* bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
*
* => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
* 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
*/
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
/*
* bytes4(keccak256('uri(uint256)')) == 0x0e89341c
*/
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
/**
* @dev See {_setURI}.
*/
constructor (string memory uri_) public {
_setURI(uri_);
// register the supported interfaces to conform to ERC1155 via ERC165
_registerInterface(_INTERFACE_ID_ERC1155);
// register the supported interfaces to conform to ERC1155MetadataURI via ERC165
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) external view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
override
{
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
public
virtual
override
{
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][from] = _balances[id][from].sub(
amount,
"ERC1155: insufficient balance for transfer"
);
_balances[id][to] = _balances[id][to].add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] = _balances[id][account].add(amount);
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
_balances[id][account] = _balances[id][account].sub(
amount,
"ERC1155: burn amount exceeds balance"
);
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(
amounts[i],
"ERC1155: burn amount exceeds balance"
);
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
{ }
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
| 23,215 |
199 | // IdleToken V5 updates Fee for flash loan | uint256 public flashLoanFee;
| uint256 public flashLoanFee;
| 72,557 |
6 | // Governance info methods | function lockedValue(address user, uint256 poolId) external view returns (uint256);
function totalLockedValue(uint256 poolId) external view returns (uint256);
function normalizedAPY(uint256 poolId) external view returns (uint256);
| function lockedValue(address user, uint256 poolId) external view returns (uint256);
function totalLockedValue(uint256 poolId) external view returns (uint256);
function normalizedAPY(uint256 poolId) external view returns (uint256);
| 43,337 |
124 | // Emitted when a new fee type is registered. | event ProtocolFeeTypeRegistered(uint256 indexed feeType, string name, uint256 maximumPercentage);
| event ProtocolFeeTypeRegistered(uint256 indexed feeType, string name, uint256 maximumPercentage);
| 29,104 |
30 | // ---------------------------------------------------------------------------- Withdraw Confirmation contract ---------------------------------------------------------------------------- | contract WithdrawConfirmation is Owned {
event Confirmation(address indexed sender, uint indexed withdrawId);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event WithdrawCreated(address indexed destination, uint indexed value, uint indexed id);
event Execution(uint indexed withdrawId);
event ExecutionFailure(uint indexed withdrawId);
mapping(address => bool) public isOwner;
mapping(uint => Withdraw) public withdraws;
mapping(uint => mapping(address => bool)) public confirmations;
address[] public owners;
uint public withdrawCount;
struct Withdraw {
address destination;
uint value;
bool executed;
}
modifier hasPermission() {
require(isOwner[msg.sender]);
_;
}
modifier ownerDoesNotExist(address _owner) {
require(!isOwner[_owner]);
_;
}
modifier ownerExists(address _owner) {
require(isOwner[_owner]);
_;
}
modifier notNull(address _address) {
require(_address != 0);
_;
}
modifier notConfirmed(uint withdrawId, address _owner) {
require(!confirmations[withdrawId][_owner]);
_;
}
modifier withdrawExists(uint withdrawId) {
require(withdraws[withdrawId].destination != 0);
_;
}
modifier confirmed(uint withdrawId, address _owner) {
require(confirmations[withdrawId][_owner]);
_;
}
modifier notExecuted(uint withdrawId) {
require(!withdraws[withdrawId].executed);
_;
}
constructor() public {
owners.push(owner);
isOwner[owner] = true;
}
function addOwner(address _owner) public ownerDoesNotExist(_owner) hasPermission {
isOwner[_owner] = true;
owners.push(_owner);
emit OwnerAddition(_owner);
}
function removeOwner(address _owner) public ownerExists(_owner) hasPermission {
require(_owner != owner);
isOwner[_owner] = false;
for(uint i=0; i < owners.length - 1; i++) {
if(owners[i] == _owner) {
owners[i] = owners[owners.length - 1];
break;
}
}
owners.length -= 1;
emit OwnerRemoval(_owner);
}
function createWithdraw(address to, uint value) public ownerExists(msg.sender) notNull(to) {
uint withdrawId = withdrawCount;
withdraws[withdrawId] = Withdraw({
destination: to,
value: value,
executed: false
});
withdrawCount += 1;
confirmations[withdrawId][msg.sender] = true;
emit WithdrawCreated(to, value, withdrawId);
executeWithdraw(withdrawId);
}
function isConfirmed(uint withdrawId) public constant returns(bool) {
for(uint i=0; i < owners.length; i++) {
if(!confirmations[withdrawId][owners[i]])
return false;
}
return true;
}
function confirmWithdraw(uint withdrawId) public ownerExists(msg.sender) withdrawExists(withdrawId) notConfirmed(withdrawId, msg.sender) {
confirmations[withdrawId][msg.sender] = true;
emit Confirmation(msg.sender, withdrawId);
executeWithdraw(withdrawId);
}
function executeWithdraw(uint withdrawId) public ownerExists(msg.sender) confirmed(withdrawId, msg.sender) notExecuted(withdrawId) {
if(isConfirmed(withdrawId)) {
Withdraw storage with = withdraws[withdrawId];
with.executed = true;
if(with.destination.send(with.value))
emit Execution(withdrawId);
else {
emit ExecutionFailure(withdrawId);
with.executed = false;
}
}
}
}
| contract WithdrawConfirmation is Owned {
event Confirmation(address indexed sender, uint indexed withdrawId);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event WithdrawCreated(address indexed destination, uint indexed value, uint indexed id);
event Execution(uint indexed withdrawId);
event ExecutionFailure(uint indexed withdrawId);
mapping(address => bool) public isOwner;
mapping(uint => Withdraw) public withdraws;
mapping(uint => mapping(address => bool)) public confirmations;
address[] public owners;
uint public withdrawCount;
struct Withdraw {
address destination;
uint value;
bool executed;
}
modifier hasPermission() {
require(isOwner[msg.sender]);
_;
}
modifier ownerDoesNotExist(address _owner) {
require(!isOwner[_owner]);
_;
}
modifier ownerExists(address _owner) {
require(isOwner[_owner]);
_;
}
modifier notNull(address _address) {
require(_address != 0);
_;
}
modifier notConfirmed(uint withdrawId, address _owner) {
require(!confirmations[withdrawId][_owner]);
_;
}
modifier withdrawExists(uint withdrawId) {
require(withdraws[withdrawId].destination != 0);
_;
}
modifier confirmed(uint withdrawId, address _owner) {
require(confirmations[withdrawId][_owner]);
_;
}
modifier notExecuted(uint withdrawId) {
require(!withdraws[withdrawId].executed);
_;
}
constructor() public {
owners.push(owner);
isOwner[owner] = true;
}
function addOwner(address _owner) public ownerDoesNotExist(_owner) hasPermission {
isOwner[_owner] = true;
owners.push(_owner);
emit OwnerAddition(_owner);
}
function removeOwner(address _owner) public ownerExists(_owner) hasPermission {
require(_owner != owner);
isOwner[_owner] = false;
for(uint i=0; i < owners.length - 1; i++) {
if(owners[i] == _owner) {
owners[i] = owners[owners.length - 1];
break;
}
}
owners.length -= 1;
emit OwnerRemoval(_owner);
}
function createWithdraw(address to, uint value) public ownerExists(msg.sender) notNull(to) {
uint withdrawId = withdrawCount;
withdraws[withdrawId] = Withdraw({
destination: to,
value: value,
executed: false
});
withdrawCount += 1;
confirmations[withdrawId][msg.sender] = true;
emit WithdrawCreated(to, value, withdrawId);
executeWithdraw(withdrawId);
}
function isConfirmed(uint withdrawId) public constant returns(bool) {
for(uint i=0; i < owners.length; i++) {
if(!confirmations[withdrawId][owners[i]])
return false;
}
return true;
}
function confirmWithdraw(uint withdrawId) public ownerExists(msg.sender) withdrawExists(withdrawId) notConfirmed(withdrawId, msg.sender) {
confirmations[withdrawId][msg.sender] = true;
emit Confirmation(msg.sender, withdrawId);
executeWithdraw(withdrawId);
}
function executeWithdraw(uint withdrawId) public ownerExists(msg.sender) confirmed(withdrawId, msg.sender) notExecuted(withdrawId) {
if(isConfirmed(withdrawId)) {
Withdraw storage with = withdraws[withdrawId];
with.executed = true;
if(with.destination.send(with.value))
emit Execution(withdrawId);
else {
emit ExecutionFailure(withdrawId);
with.executed = false;
}
}
}
}
| 19,559 |
23 | // Allows the nft owner to redeem or burn the piNFT. _tokenId The Id of the token. _nftReceiver The receiver of the nft after the function call. _erc20Receiver The receiver of the validator funds after the function call. _erc20Contract The address of the deposited validator funds. burnNFT Boolean to determine redeeming or burning. / | function redeemOrBurnPiNFT(
uint256 _tokenId,
address _nftReceiver,
address _erc20Receiver,
address _erc20Contract,
bool burnNFT
| function redeemOrBurnPiNFT(
uint256 _tokenId,
address _nftReceiver,
address _erc20Receiver,
address _erc20Contract,
bool burnNFT
| 6,290 |
5 | // Calculate protocol fee based on mint ratio | function protocolFee() public view override returns (uint) {
return mintRatio() * factory.maxProtocolFee() / factory.PRECISION();
}
| function protocolFee() public view override returns (uint) {
return mintRatio() * factory.maxProtocolFee() / factory.PRECISION();
}
| 31,660 |
1 | // Deposit HEX and bridged HEX on whichever network you are on to mint CHEX. 1 CHEX = 1 eHEX + 1 pHEX. You must grant this contract the appropriate approvals. Transaction must include the flat rate arbitrage throttle, paid in ETH or PLS. | function mint(uint256 amount) external payable nonReentrant{
require(msg.value == arbitrage_throttle, "Transaction must include the arbitrage throttle.");
IERC20(HEX_ADDRESS).transferFrom(msg.sender, address(this), amount);
IERC20(getAddress()).transferFrom(msg.sender, address(this), amount);
_mint(msg.sender, amount);
emit Minted(msg.sender, amount);
}
| function mint(uint256 amount) external payable nonReentrant{
require(msg.value == arbitrage_throttle, "Transaction must include the arbitrage throttle.");
IERC20(HEX_ADDRESS).transferFrom(msg.sender, address(this), amount);
IERC20(getAddress()).transferFrom(msg.sender, address(this), amount);
_mint(msg.sender, amount);
emit Minted(msg.sender, amount);
}
| 36,303 |
15 | // NFTSalesBNB - NFT sale in BNB | contract NFTSalesBNB is ERC1155Holder, Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct Token {
bool resolved;
uint256 price;
IUniV2PriceOracle priceOracle;
}
struct Collectible {
uint256 price; // in usd
}
IERC1155Collectible public immutable collection;
address public immutable vesting;
address public immutable refRegistry;
address public baseStablecoin;
bool public salesEnabled;
uint256 public minBuy = 1e18;
// @dev collections - list of resolved for sell stablecoins
mapping(address => Token) public tokenInfo;
// token id -> data
mapping(uint256 => Collectible) public collectibleInfo;
event Bought(address token, address from, uint256 tokenId, uint256 amount);
event Deposited(address token, address from, uint256 amount);
// `_collectionToken` - erc1155 token
constructor(
IERC1155Collectible _collectionToken,
address _vesting,
address _refRegistry,
IUniV2PriceOracle _priceOracle
) {
require(
address(_collectionToken) != address(0) &&
address(_vesting) != address(0) &&
address(_refRegistry) != address(0) &&
address(_priceOracle) != address(0),
"Token sell: wrong constructor arguments"
);
collection = _collectionToken;
vesting = _vesting;
refRegistry = _refRegistry;
Token storage token = tokenInfo[address(0)];
token.resolved = true;
token.price = 1e18;
token.priceOracle = _priceOracle;
collectibleInfo[1].price = 1e18;
collectibleInfo[2].price = 769e14;
collectibleInfo[3].price = 336e13;
collectibleInfo[4].price = 541e12;
collectibleInfo[5].price = 2086e10;
}
function buy(
uint256 _amount,
uint256 _tokenId,
uint256 _items,
address _to,
address _sponsor
) external payable isSellApproved {
require(_to != address(0), "Token sell: buy for vitalik?");
require(_items > 0, "Token sell: zero items, really?");
require(
tokenInfo[address(0)].resolved,
"Token sell: token is not accepted"
);
if (!IPartner(refRegistry).isUser(msg.sender)) {
IPartner(refRegistry).register(msg.sender, _sponsor);
}
_buy(address(0), _amount, _tokenId, _items, _to);
}
function sellSwitcher(bool _status) external onlyOwner {
salesEnabled = _status;
}
function setMinBuy(uint256 _minBuy) external onlyOwner {
minBuy = _minBuy;
}
function setBaseStablecoin(address _stablecoin) external onlyOwner {
baseStablecoin = _stablecoin;
}
function setPriceOracle(IUniV2PriceOracle _priceOracle) external onlyOwner {
tokenInfo[address(0)].priceOracle = _priceOracle;
}
function countBuyAmount(
address _token,
uint256 _tokenId,
uint256 _items
) public view returns (uint256 amountOut) {
IUniV2PriceOracle priceOracle = tokenInfo[_token].priceOracle;
address token0 = priceOracle.token0();
address token1 = priceOracle.token1();
uint256 amountIn = _items.mul(collectibleInfo[_tokenId].price);
if (token0 == baseStablecoin) {
amountOut = priceOracle.consult(token0, amountIn);
} else {
amountOut = priceOracle.consult(token1, amountIn);
}
}
function _buy(
address _token,
uint256 _amount,
uint256 _tokenId,
uint256 _items,
address _to
) internal {
uint256 minAmount = countBuyAmount(_token, _tokenId, _items);
IUniV2PriceOracle priceOracle = IUniV2PriceOracle(
tokenInfo[_token].priceOracle
);
// update price
if (
priceOracle.blockTimestampLast() + priceOracle.PERIOD() >=
block.timestamp
) {
priceOracle.update();
}
require(minAmount != 0, "Token sell: zero min amount");
require(
_amount >= minAmount,
"Token sell: not enough to buy, low amount"
);
require(msg.value == _amount, "Token sell: not enough ether for buy");
Address.sendValue(payable(vesting), _amount);
collection.mint(_to, _tokenId, _items, "");
emit Deposited(_token, msg.sender, _amount);
emit Bought(_token, _to, _tokenId, _items);
}
modifier isSellApproved() {
require(salesEnabled, "Sales disabled");
_;
}
}
| contract NFTSalesBNB is ERC1155Holder, Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct Token {
bool resolved;
uint256 price;
IUniV2PriceOracle priceOracle;
}
struct Collectible {
uint256 price; // in usd
}
IERC1155Collectible public immutable collection;
address public immutable vesting;
address public immutable refRegistry;
address public baseStablecoin;
bool public salesEnabled;
uint256 public minBuy = 1e18;
// @dev collections - list of resolved for sell stablecoins
mapping(address => Token) public tokenInfo;
// token id -> data
mapping(uint256 => Collectible) public collectibleInfo;
event Bought(address token, address from, uint256 tokenId, uint256 amount);
event Deposited(address token, address from, uint256 amount);
// `_collectionToken` - erc1155 token
constructor(
IERC1155Collectible _collectionToken,
address _vesting,
address _refRegistry,
IUniV2PriceOracle _priceOracle
) {
require(
address(_collectionToken) != address(0) &&
address(_vesting) != address(0) &&
address(_refRegistry) != address(0) &&
address(_priceOracle) != address(0),
"Token sell: wrong constructor arguments"
);
collection = _collectionToken;
vesting = _vesting;
refRegistry = _refRegistry;
Token storage token = tokenInfo[address(0)];
token.resolved = true;
token.price = 1e18;
token.priceOracle = _priceOracle;
collectibleInfo[1].price = 1e18;
collectibleInfo[2].price = 769e14;
collectibleInfo[3].price = 336e13;
collectibleInfo[4].price = 541e12;
collectibleInfo[5].price = 2086e10;
}
function buy(
uint256 _amount,
uint256 _tokenId,
uint256 _items,
address _to,
address _sponsor
) external payable isSellApproved {
require(_to != address(0), "Token sell: buy for vitalik?");
require(_items > 0, "Token sell: zero items, really?");
require(
tokenInfo[address(0)].resolved,
"Token sell: token is not accepted"
);
if (!IPartner(refRegistry).isUser(msg.sender)) {
IPartner(refRegistry).register(msg.sender, _sponsor);
}
_buy(address(0), _amount, _tokenId, _items, _to);
}
function sellSwitcher(bool _status) external onlyOwner {
salesEnabled = _status;
}
function setMinBuy(uint256 _minBuy) external onlyOwner {
minBuy = _minBuy;
}
function setBaseStablecoin(address _stablecoin) external onlyOwner {
baseStablecoin = _stablecoin;
}
function setPriceOracle(IUniV2PriceOracle _priceOracle) external onlyOwner {
tokenInfo[address(0)].priceOracle = _priceOracle;
}
function countBuyAmount(
address _token,
uint256 _tokenId,
uint256 _items
) public view returns (uint256 amountOut) {
IUniV2PriceOracle priceOracle = tokenInfo[_token].priceOracle;
address token0 = priceOracle.token0();
address token1 = priceOracle.token1();
uint256 amountIn = _items.mul(collectibleInfo[_tokenId].price);
if (token0 == baseStablecoin) {
amountOut = priceOracle.consult(token0, amountIn);
} else {
amountOut = priceOracle.consult(token1, amountIn);
}
}
function _buy(
address _token,
uint256 _amount,
uint256 _tokenId,
uint256 _items,
address _to
) internal {
uint256 minAmount = countBuyAmount(_token, _tokenId, _items);
IUniV2PriceOracle priceOracle = IUniV2PriceOracle(
tokenInfo[_token].priceOracle
);
// update price
if (
priceOracle.blockTimestampLast() + priceOracle.PERIOD() >=
block.timestamp
) {
priceOracle.update();
}
require(minAmount != 0, "Token sell: zero min amount");
require(
_amount >= minAmount,
"Token sell: not enough to buy, low amount"
);
require(msg.value == _amount, "Token sell: not enough ether for buy");
Address.sendValue(payable(vesting), _amount);
collection.mint(_to, _tokenId, _items, "");
emit Deposited(_token, msg.sender, _amount);
emit Bought(_token, _to, _tokenId, _items);
}
modifier isSellApproved() {
require(salesEnabled, "Sales disabled");
_;
}
}
| 43,029 |
125 | // Hook that is called after a set of serially-ordered token ids have been transferred. This includesminting.And also called after one token has been burned. startTokenId - the first token id to be transferredquantity - the amount to be transferred Calling conditions: - When `from` and `to` are both non-zero, `from`'s `tokenId` has beentransferred to `to`.- When `from` is zero, `tokenId` has been minted for `to`.- When `to` is zero, `tokenId` has been burned by `from`.- `from` and `to` are never both zero. / | function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
| function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
| 3,008 |
13 | // Check the last exchange rate without any state changes | function peek(bytes calldata) public view override returns (bool, uint256) {
return (success, rate);
}
| function peek(bytes calldata) public view override returns (bool, uint256) {
return (success, rate);
}
| 43,045 |
36 | // This function can release ERC20-tokens `_tokensToWithdraw`, which/ got stuck in this smart contract (were transferred here by the mistake)/Allowed only for SuperAdmin./Transfers all balance of stuck `_tokensToWithdraw` from | /// this contract to {_corporateTreasury} wallet
/// @param _tokensToWithdraw address of ERC20-token to withdraw
function withdrawStuckTokens(
address _tokensToWithdraw
) external onlySuperAdmin {
address from = address(this);
uint256 amount = IERC20(_tokensToWithdraw).balanceOf(from);
IERC20(_tokensToWithdraw).transfer(_corporateTreasury, amount);
}
| /// this contract to {_corporateTreasury} wallet
/// @param _tokensToWithdraw address of ERC20-token to withdraw
function withdrawStuckTokens(
address _tokensToWithdraw
) external onlySuperAdmin {
address from = address(this);
uint256 amount = IERC20(_tokensToWithdraw).balanceOf(from);
IERC20(_tokensToWithdraw).transfer(_corporateTreasury, amount);
}
| 24,134 |
354 | // Address of the media contract that can call this market | address public mediaContract;
| address public mediaContract;
| 75,780 |
3 | // initialize variables | taskOwner = tOwner;
TaskId = TID;
TaskOpen = true;
numLabelers = nLabelers;
totalAmount = amount;
rewardPerLabeler = totalAmount / numLabelers;
numLabelersPaid = 0;
| taskOwner = tOwner;
TaskId = TID;
TaskOpen = true;
numLabelers = nLabelers;
totalAmount = amount;
rewardPerLabeler = totalAmount / numLabelers;
numLabelersPaid = 0;
| 14,170 |
4 | // need to approve this contract first | function claim() public {
uint256 approved = token.allowance(msg.sender, this);
uint256 amount = token.balanceOf(msg.sender);
if (approved > amount) {
approved = amount;
}
uint256 availableBalance = this.balance;
uint256 weiBack = convertBalance(approved);
if (availableBalance < weiBack) {
approved = availableBalance.mul(rate);
weiBack = availableBalance;
}
token.transferFrom(msg.sender, this, approved);
token.burn(approved);
msg.sender.transfer(weiBack);
}
| function claim() public {
uint256 approved = token.allowance(msg.sender, this);
uint256 amount = token.balanceOf(msg.sender);
if (approved > amount) {
approved = amount;
}
uint256 availableBalance = this.balance;
uint256 weiBack = convertBalance(approved);
if (availableBalance < weiBack) {
approved = availableBalance.mul(rate);
weiBack = availableBalance;
}
token.transferFrom(msg.sender, this, approved);
token.burn(approved);
msg.sender.transfer(weiBack);
}
| 41,400 |
52 | // only enable if no plan to airdrop |
function enableTrading() external onlyOwner {
require(!tradingActive, "Cannot reEnable trading");
tradingActive = true;
swapEnabled = true;
tradingActiveBlock = block.number;
emit EnabledTrading();
}
|
function enableTrading() external onlyOwner {
require(!tradingActive, "Cannot reEnable trading");
tradingActive = true;
swapEnabled = true;
tradingActiveBlock = block.number;
emit EnabledTrading();
}
| 4,783 |
10 | // Emitted when MOMA is claimed by user | event MomaClaimed(address claimer, address recipient, AccountType accountType, uint claimed, uint left);
| event MomaClaimed(address claimer, address recipient, AccountType accountType, uint claimed, uint left);
| 48,548 |
11 | // emergency case | function rescueFund(IERC20 token) public onlyOwner {
if (address(token) == address(0)) {
(bool success, ) = msg.sender.call{value: address(this).balance}('');
require(success, 'TOKordinator: fail to rescue Ether');
} else {
token.safeTransfer(msg.sender, token.balanceOf(address(this)));
}
}
| function rescueFund(IERC20 token) public onlyOwner {
if (address(token) == address(0)) {
(bool success, ) = msg.sender.call{value: address(this).balance}('');
require(success, 'TOKordinator: fail to rescue Ether');
} else {
token.safeTransfer(msg.sender, token.balanceOf(address(this)));
}
}
| 14,230 |
232 | // Market dynamic variables. | struct MarketStatus {
uint128 commitmentsTotal;
bool finalized;
bool usePointList;
}
| struct MarketStatus {
uint128 commitmentsTotal;
bool finalized;
bool usePointList;
}
| 56,259 |
380 | // calc debt | (uint256 oldUserDebtBalance, uint256 totalAssetSupplyInUsd) = debtSystem.GetUserDebtBalanceInUsd(user);
uint256 newTotalAssetSupply = totalAssetSupplyInUsd.add(amount);
| (uint256 oldUserDebtBalance, uint256 totalAssetSupplyInUsd) = debtSystem.GetUserDebtBalanceInUsd(user);
uint256 newTotalAssetSupply = totalAssetSupplyInUsd.add(amount);
| 9,846 |
31 | // Used to update the name and symbol of a local token _canonical - The canonical id and domain to remove _name - The new name _symbol - The new symbol / | function updateDetails(
TokenId calldata _canonical,
string memory _name,
string memory _symbol
| function updateDetails(
TokenId calldata _canonical,
string memory _name,
string memory _symbol
| 19,217 |
169 | // Round up after scaling. | redeemable = stakeScaled
.mul(address(this).balance)
.sub(1)
.div(SCALING_FACTOR)
.add(1);
| redeemable = stakeScaled
.mul(address(this).balance)
.sub(1)
.div(SCALING_FACTOR)
.add(1);
| 42,064 |
428 | // activates a reserve_reserve the address of the reserve/ | function activateReserve(address _reserve) external onlyLendingPoolConfigurator {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
require(
reserve.lastLiquidityCumulativeIndex > 0 &&
reserve.lastVariableBorrowCumulativeIndex > 0,
"Reserve has not been initialized yet"
);
reserve.isActive = true;
}
| function activateReserve(address _reserve) external onlyLendingPoolConfigurator {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
require(
reserve.lastLiquidityCumulativeIndex > 0 &&
reserve.lastVariableBorrowCumulativeIndex > 0,
"Reserve has not been initialized yet"
);
reserve.isActive = true;
}
| 9,242 |
59 | // confirm claim | _confirmClaim(processId, CLAIM_ID, payoutAmount);
emit LogDepegClaimConfirmed(processId, CLAIM_ID, claim.claimAmount, depegBalance, payoutAmount);
| _confirmClaim(processId, CLAIM_ID, payoutAmount);
emit LogDepegClaimConfirmed(processId, CLAIM_ID, claim.claimAmount, depegBalance, payoutAmount);
| 40,739 |
125 | // payable(gov).transfer(cost); | (bool success,) = payable(gov).call{value:cost}("");
| (bool success,) = payable(gov).call{value:cost}("");
| 25,304 |
7 | // action performed on the module during a transfer action this function is used to update variables of the module upon transfer if it is required if the module does not require state updates in case of transfer, this function remains empty This function can be called ONLY by the compliance contract itself (_compliance) This function can be called only on a compliance contract that is bound to the module_from address of the transfer sender_to address of the transfer receiver_value amount of tokens sent / | function moduleTransferAction(address _from, address _to, uint256 _value) external;
| function moduleTransferAction(address _from, address _to, uint256 _value) external;
| 223 |
0 | // Immutable state/Functions that return immutable state of the router | interface IPeripheryImmutableState {
/// @return Returns the address of the Mauve factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
| interface IPeripheryImmutableState {
/// @return Returns the address of the Mauve factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
| 31,449 |
69 | // MUST fully redeem a past stake, CD gets destroyed | newStakingShareSecondsToBurn = lastStake.stakingShares.mul(stakeTimeSecCalculated);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
if(lastStake.stakingShares > sharesLeftToBurn){
sharesLeftToBurn = 0;
} else {
| newStakingShareSecondsToBurn = lastStake.stakingShares.mul(stakeTimeSecCalculated);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
if(lastStake.stakingShares > sharesLeftToBurn){
sharesLeftToBurn = 0;
} else {
| 24,081 |
59 | // Helper method for the frontend, returns all the subscribed CDPs paginated/_page What page of subscribers you want/_perPage Number of entries per page/ return List of all subscribers for that page | function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) {
CompoundHolder[] memory holders = new CompoundHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
| function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) {
CompoundHolder[] memory holders = new CompoundHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
| 5,997 |
110 | // Function for the frontend to dynamically retrieve the price scaling of buy orders. / | function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
| function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
| 26,535 |
12 | // The Ballot will authorize the amount in the user's wallet at time of registration. Ensure all funds to be used for voting are present in wallet before registering | function registerToVote() public {
require(registered[msg.sender] == false, "Already registered");
registered[msg.sender] = true;
Voter storage sender = voters[msg.sender];
sender.registrationDate = block.timestamp;
//TODO: set total votes to current balance or approval value, whichever is lower
}
| function registerToVote() public {
require(registered[msg.sender] == false, "Already registered");
registered[msg.sender] = true;
Voter storage sender = voters[msg.sender];
sender.registrationDate = block.timestamp;
//TODO: set total votes to current balance or approval value, whichever is lower
}
| 27,606 |
11 | // Mapping of wrapped assets data(wrappedAddress => WrappedAsset) | mapping(address => WrappedAsset) public wrappedAssetData;
| mapping(address => WrappedAsset) public wrappedAssetData;
| 21,867 |
19 | // Transfer token for a specified address to The address to transfer to. value The amount to be transferred. comment The transfer comment.return True if the transaction succeeds. / | function transferWithComment(
address to,
uint256 value,
string calldata comment
| function transferWithComment(
address to,
uint256 value,
string calldata comment
| 23,016 |
301 | // update reallocation batch | reallocationBatch.depositedReallocation = depositOptimizedAmount;
reallocationBatch.depositedReallocationSharesReceived = newShares;
strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying;
| reallocationBatch.depositedReallocation = depositOptimizedAmount;
reallocationBatch.depositedReallocationSharesReceived = newShares;
strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying;
| 65,227 |
14 | // Check cliffing duration | if (currentTime() < tokenGrant.vestingStartTime) {
return (0, 0);
}
| if (currentTime() < tokenGrant.vestingStartTime) {
return (0, 0);
}
| 49,923 |
29 | // An event emitted when a proposal has been canceled | event ProposalCanceled(uint256 id);
event NewAdmin(address indexed newAdmin);
| event ProposalCanceled(uint256 id);
event NewAdmin(address indexed newAdmin);
| 14,078 |
26 | // check message is from the correct source chain position | require(key.this_chain_id == _slot0.bridgedChainPosition, "Lane: InvalidSourceChainId");
| require(key.this_chain_id == _slot0.bridgedChainPosition, "Lane: InvalidSourceChainId");
| 11,688 |
50 | // 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;
}
| function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| 244 |
7 | // takeSnapshot will update latestSnapshotInfo | (uint256 bk2, string memory cid2) = snapper.latestSnapshotInfo();
assertEq(bk2, snapshotBlock);
assertEq(cid2, CID1);
| (uint256 bk2, string memory cid2) = snapper.latestSnapshotInfo();
assertEq(bk2, snapshotBlock);
assertEq(cid2, CID1);
| 32,858 |
8 | // Emitted when customer enrolls for loyalty program | event ItemAdded(uint itemId, string itemName, uint price, uint points, address sellerAddress);
| event ItemAdded(uint itemId, string itemName, uint price, uint points, address sellerAddress);
| 24,626 |
389 | // Calling this function governor commits proposed whitelist if timelock interval of proposal was passed | function commitWhitelist() public onlyGovernor {
// Check if proposal was made
require(proposalTime != 0, "Didn't proposed yet");
// Check if timelock interval was passed
require((proposalTime + timeLockInterval) < now, "Can't commit yet");
// Set new whitelist and emit event
whitelist = proposedWhitelist;
emit Committed(whitelist);
// Reset proposal time lock
proposalTime = 0;
}
| function commitWhitelist() public onlyGovernor {
// Check if proposal was made
require(proposalTime != 0, "Didn't proposed yet");
// Check if timelock interval was passed
require((proposalTime + timeLockInterval) < now, "Can't commit yet");
// Set new whitelist and emit event
whitelist = proposedWhitelist;
emit Committed(whitelist);
// Reset proposal time lock
proposalTime = 0;
}
| 47,118 |
287 | // Accumulator for sequencer inbox messages; tail represents hash of the current state; each element represents the inclusion of a new message. | function sequencerInboxAccs(uint256) external view returns (bytes32);
| function sequencerInboxAccs(uint256) external view returns (bytes32);
| 11,400 |
291 | // Valid TokenMessengers on remote domains | mapping(uint32 => bytes32) public remoteTokenMessengers;
| mapping(uint32 => bytes32) public remoteTokenMessengers;
| 17,085 |
3 | // Only smart contracts will be affected by this modifier | modifier defense() {
require(
(msg.sender == tx.origin), // If it is a normal user and not smart contract
"This smart contract has been grey listed" // make sure that it is not on our greyList.
);
_;
}
| modifier defense() {
require(
(msg.sender == tx.origin), // If it is a normal user and not smart contract
"This smart contract has been grey listed" // make sure that it is not on our greyList.
);
_;
}
| 20,029 |
28 | // This call allows anyone owed money by the contract to collect it by initiating a transfer to their account. / | function WithdrawFromPool() external payable hasMoneyInWithdrawPool {
address payable callerAddress = payable(msg.sender);
uint256 amt = withDrawPool[msg.sender];
withDrawPool[msg.sender] = 0;
Erc20Utils.moveTokensFromContract(tokenAddress, callerAddress, amt);
}
| function WithdrawFromPool() external payable hasMoneyInWithdrawPool {
address payable callerAddress = payable(msg.sender);
uint256 amt = withDrawPool[msg.sender];
withDrawPool[msg.sender] = 0;
Erc20Utils.moveTokensFromContract(tokenAddress, callerAddress, amt);
}
| 15,805 |
16 | // Check if request still be able to take (not bigger than insuredSumRemaining) | require(
_provideCover.fundingSum <=
(request.insuredSum -
ld.requestIdToInsuredSumTaken(_provideCover.requestId)),
"Cover Gateway: Remaining insured sum is insufficient"
);
| require(
_provideCover.fundingSum <=
(request.insuredSum -
ld.requestIdToInsuredSumTaken(_provideCover.requestId)),
"Cover Gateway: Remaining insured sum is insufficient"
);
| 19,237 |
33 | // 1st year effective annual interest rate is 100% | interest = (1000 * maxMintProofOfStake).div(100);
| interest = (1000 * maxMintProofOfStake).div(100);
| 4,921 |
399 | // Creates `amount` new tokens for `to`. | * See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mintTo(address to, uint256 amount) public {
require(canMint(amount), "Cannot mint: it would create an asset/liability mismatch");
// This will lock the function down to only the minter
super.mint(to, amount);
}
| * See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mintTo(address to, uint256 amount) public {
require(canMint(amount), "Cannot mint: it would create an asset/liability mismatch");
// This will lock the function down to only the minter
super.mint(to, amount);
}
| 1,251 |
10 | // 1 | uint256 LIQUIDITY_FEE_DENOMINATOR;
| uint256 LIQUIDITY_FEE_DENOMINATOR;
| 20,830 |
68 | // The block number when Ramp mining starts. | uint256 public START_BLOCK;
| uint256 public START_BLOCK;
| 43,308 |
269 | // CVX Locking contract for https:www.convexfinance.com/ CVX locked in this contract will be entitled to voting rights for the Convex Finance platform Based on EPS Staking contract for http:ellipsis.finance/ Based on SNX MultiRewards by iamdefinitelyahuman - https:github.com/iamdefinitelyahuman/multi-rewards | contract CvxLocker 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 constant stakingToken = IERC20(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); //cvx
address public constant cvxCrv = address(0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7);
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 86400 * 7;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 17;
// 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 = address(0x1389388d01708118b497f59521f6943Be2541bb7);
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//staking
uint256 public minimumStake = 10000;
uint256 public maximumStake = 10000;
address public stakingProxy;
address public constant cvxcrvStaking = address(0x3Fe65692bfCD0e6CF84cB1E7d24108E434A7587e);
uint256 public constant stakeOffsetOnLock = 500; //allow broader range for staking when depositing
//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() public Ownable() {
_name = "Vote Locked Convex Token";
_symbol = "vlCVX";
_decimals = 18;
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);
require(_rewardsToken != address(stakingToken));
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);
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//Set the staking contract for the underlying cvx. immutable to avoid foul play
function setStakingContract(address _staking) external onlyOwner {
require(stakingProxy == address(0), "staking contract immutable");
stakingProxy = _staking;
}
//set staking limits. will stake the mean of the two once either ratio is crossed
function setStakeLimits(uint256 _minimum, uint256 _maximum) external onlyOwner {
require(_minimum <= denominator, "min range");
require(_maximum <= denominator, "max range");
minimumStake = _minimum;
maximumStake = _maximum;
updateStakeRatio(0);
}
//set boost parameters
function setBoost(uint256 _max, uint256 _rate, address _receivingAddress) external onlyOwner {
require(maximumBoostPayment < 1500, "over max payment"); //max 15%
require(boostRate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
//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. unstake all tokens. release all locks
function shutdown() external onlyOwner {
if (stakingProxy != address(0)) {
uint256 stakeBalance = IStakingProxy(stakingProxy).getBalance();
IStakingProxy(stakingProxy).withdraw(stakeBalance);
}
isShutdown = true;
}
//set approvals for staking cvx and cvxcrv
function setApprovals() external {
IERC20(cvxCrv).safeApprove(cvxcrvStaking, 0);
IERC20(cvxCrv).safeApprove(cvxcrvStaking, uint256(-1));
IERC20(stakingToken).safeApprove(stakingProxy, 0);
IERC20(stakingToken).safeApprove(stakingProxy, 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) view external returns(uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) view external 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) view external 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 (uint 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) view external 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 (uint 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() view external 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 (uint 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) view external 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 (uint 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) view external 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
) view external 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 (uint 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 updateReward(_account) {
//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 {
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);
}
//update staking, allow a bit of leeway for smaller deposits to reduce gas
updateStakeRatio(stakeOffsetOnLock);
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) {
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(locks[length - 1].unlockTime)).div(rewardsDuration);
uint256 rRate = MathUtil.min(kickRewardPerEpoch.mul(epochsover+1), denominator);
reward = uint256(locks[length - 1].amount).mul(rRate).div(denominator);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint 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) {
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(locks[i].unlockTime)).div(rewardsDuration);
uint256 rRate = MathUtil.min(kickRewardPerEpoch.mul(epochsover+1), denominator);
reward = reward.add( uint256(locks[i].amount).mul(rRate).div(denominator));
}
//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);
emit Withdrawn(_account, locked, _relock);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//preallocate enough cvx from stake contract to pay for both reward and withdraw
allocateCVXForTransfer(uint256(locked));
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
transferCVX(_rewardAddress, reward, false);
emit KickReward(_rewardAddress, _account, reward);
}else if(_spendRatio > 0){
//preallocate enough cvx to transfer the boost cost
allocateCVXForTransfer( uint256(locked).mul(_spendRatio).div(denominator) );
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
} else {
transferCVX(_withdrawTo, locked, true);
}
}
// 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));
}
//pull required amount of cvx from staking for an upcoming transfer
function allocateCVXForTransfer(uint256 _amount) internal{
uint256 balance = stakingToken.balanceOf(address(this));
if (_amount > balance) {
IStakingProxy(stakingProxy).withdraw(_amount.sub(balance));
}
}
//transfer helper: pull enough from staking, transfer, updating staking ratio
function transferCVX(address _account, uint256 _amount, bool _updateStake) internal {
//allocate enough cvx from staking for the transfer
allocateCVXForTransfer(_amount);
//transfer
stakingToken.safeTransfer(_account, _amount);
//update staking
if(_updateStake){
updateStakeRatio(0);
}
}
//calculate how much cvx should be staked. update if needed
function updateStakeRatio(uint256 _offset) internal {
if (isShutdown) return;
//get balances
uint256 local = stakingToken.balanceOf(address(this));
uint256 staked = IStakingProxy(stakingProxy).getBalance();
uint256 total = local.add(staked);
if(total == 0) return;
//current staked ratio
uint256 ratio = staked.mul(denominator).div(total);
//mean will be where we reset to if unbalanced
uint256 mean = maximumStake.add(minimumStake).div(2);
uint256 max = maximumStake.add(_offset);
uint256 min = Math.min(minimumStake, minimumStake - _offset);
if (ratio > max) {
//remove
uint256 remove = staked.sub(total.mul(mean).div(denominator));
IStakingProxy(stakingProxy).withdraw(remove);
} else if (ratio < min) {
//add
uint256 increase = total.mul(mean).div(denominator).sub(staked);
stakingToken.safeTransfer(stakingProxy, increase);
IStakingProxy(stakingProxy).stake();
}
}
// Claim all pending rewards
function getReward(address _account, bool _stake) public nonReentrant updateReward(_account) {
for (uint i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
if (_rewardsToken == cvxCrv && _stake) {
IRewardStaking(cvxcrvStaking).stakeFor(_account, reward);
} else {
IERC20(_rewardsToken).safeTransfer(_account, reward);
}
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
// claim all pending rewards
function getReward(address _account) external{
getReward(_account,false);
}
/* ========== 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]);
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);
if(_rewardsToken == cvxCrv){
//update staking ratio if main reward
updateStakeRatio(0);
}
}
// 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 (uint 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, bool _relocked);
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);
} | contract CvxLocker 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 constant stakingToken = IERC20(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); //cvx
address public constant cvxCrv = address(0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7);
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 86400 * 7;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 17;
// 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 = address(0x1389388d01708118b497f59521f6943Be2541bb7);
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//staking
uint256 public minimumStake = 10000;
uint256 public maximumStake = 10000;
address public stakingProxy;
address public constant cvxcrvStaking = address(0x3Fe65692bfCD0e6CF84cB1E7d24108E434A7587e);
uint256 public constant stakeOffsetOnLock = 500; //allow broader range for staking when depositing
//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() public Ownable() {
_name = "Vote Locked Convex Token";
_symbol = "vlCVX";
_decimals = 18;
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);
require(_rewardsToken != address(stakingToken));
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);
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//Set the staking contract for the underlying cvx. immutable to avoid foul play
function setStakingContract(address _staking) external onlyOwner {
require(stakingProxy == address(0), "staking contract immutable");
stakingProxy = _staking;
}
//set staking limits. will stake the mean of the two once either ratio is crossed
function setStakeLimits(uint256 _minimum, uint256 _maximum) external onlyOwner {
require(_minimum <= denominator, "min range");
require(_maximum <= denominator, "max range");
minimumStake = _minimum;
maximumStake = _maximum;
updateStakeRatio(0);
}
//set boost parameters
function setBoost(uint256 _max, uint256 _rate, address _receivingAddress) external onlyOwner {
require(maximumBoostPayment < 1500, "over max payment"); //max 15%
require(boostRate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
//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. unstake all tokens. release all locks
function shutdown() external onlyOwner {
if (stakingProxy != address(0)) {
uint256 stakeBalance = IStakingProxy(stakingProxy).getBalance();
IStakingProxy(stakingProxy).withdraw(stakeBalance);
}
isShutdown = true;
}
//set approvals for staking cvx and cvxcrv
function setApprovals() external {
IERC20(cvxCrv).safeApprove(cvxcrvStaking, 0);
IERC20(cvxCrv).safeApprove(cvxcrvStaking, uint256(-1));
IERC20(stakingToken).safeApprove(stakingProxy, 0);
IERC20(stakingToken).safeApprove(stakingProxy, 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) view external returns(uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) view external 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) view external 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 (uint 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) view external 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 (uint 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() view external 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 (uint 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) view external 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 (uint 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) view external 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
) view external 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 (uint 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 updateReward(_account) {
//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 {
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);
}
//update staking, allow a bit of leeway for smaller deposits to reduce gas
updateStakeRatio(stakeOffsetOnLock);
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) {
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(locks[length - 1].unlockTime)).div(rewardsDuration);
uint256 rRate = MathUtil.min(kickRewardPerEpoch.mul(epochsover+1), denominator);
reward = uint256(locks[length - 1].amount).mul(rRate).div(denominator);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint 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) {
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(locks[i].unlockTime)).div(rewardsDuration);
uint256 rRate = MathUtil.min(kickRewardPerEpoch.mul(epochsover+1), denominator);
reward = reward.add( uint256(locks[i].amount).mul(rRate).div(denominator));
}
//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);
emit Withdrawn(_account, locked, _relock);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//preallocate enough cvx from stake contract to pay for both reward and withdraw
allocateCVXForTransfer(uint256(locked));
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
transferCVX(_rewardAddress, reward, false);
emit KickReward(_rewardAddress, _account, reward);
}else if(_spendRatio > 0){
//preallocate enough cvx to transfer the boost cost
allocateCVXForTransfer( uint256(locked).mul(_spendRatio).div(denominator) );
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
} else {
transferCVX(_withdrawTo, locked, true);
}
}
// 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));
}
//pull required amount of cvx from staking for an upcoming transfer
function allocateCVXForTransfer(uint256 _amount) internal{
uint256 balance = stakingToken.balanceOf(address(this));
if (_amount > balance) {
IStakingProxy(stakingProxy).withdraw(_amount.sub(balance));
}
}
//transfer helper: pull enough from staking, transfer, updating staking ratio
function transferCVX(address _account, uint256 _amount, bool _updateStake) internal {
//allocate enough cvx from staking for the transfer
allocateCVXForTransfer(_amount);
//transfer
stakingToken.safeTransfer(_account, _amount);
//update staking
if(_updateStake){
updateStakeRatio(0);
}
}
//calculate how much cvx should be staked. update if needed
function updateStakeRatio(uint256 _offset) internal {
if (isShutdown) return;
//get balances
uint256 local = stakingToken.balanceOf(address(this));
uint256 staked = IStakingProxy(stakingProxy).getBalance();
uint256 total = local.add(staked);
if(total == 0) return;
//current staked ratio
uint256 ratio = staked.mul(denominator).div(total);
//mean will be where we reset to if unbalanced
uint256 mean = maximumStake.add(minimumStake).div(2);
uint256 max = maximumStake.add(_offset);
uint256 min = Math.min(minimumStake, minimumStake - _offset);
if (ratio > max) {
//remove
uint256 remove = staked.sub(total.mul(mean).div(denominator));
IStakingProxy(stakingProxy).withdraw(remove);
} else if (ratio < min) {
//add
uint256 increase = total.mul(mean).div(denominator).sub(staked);
stakingToken.safeTransfer(stakingProxy, increase);
IStakingProxy(stakingProxy).stake();
}
}
// Claim all pending rewards
function getReward(address _account, bool _stake) public nonReentrant updateReward(_account) {
for (uint i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
if (_rewardsToken == cvxCrv && _stake) {
IRewardStaking(cvxcrvStaking).stakeFor(_account, reward);
} else {
IERC20(_rewardsToken).safeTransfer(_account, reward);
}
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
// claim all pending rewards
function getReward(address _account) external{
getReward(_account,false);
}
/* ========== 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]);
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);
if(_rewardsToken == cvxCrv){
//update staking ratio if main reward
updateStakeRatio(0);
}
}
// 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 (uint 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, bool _relocked);
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);
} | 25,362 |
10 | // Put sibling edge if needed | if (parentNode.children[1 - bit].isEmpty()) {
parentNode.children[1 - bit].header = siblings[siblings.length - i - 1];
}
| if (parentNode.children[1 - bit].isEmpty()) {
parentNode.children[1 - bit].header = siblings[siblings.length - i - 1];
}
| 2,464 |
265 | // Create price sheet | function _createPriceSheet(
PriceSheet[] storage sheets,
uint accountIndex,
uint32 ethNum,
uint nestNum1k,
uint level_shares,
uint tokenAmountPerEth
| function _createPriceSheet(
PriceSheet[] storage sheets,
uint accountIndex,
uint32 ethNum,
uint nestNum1k,
uint level_shares,
uint tokenAmountPerEth
| 37,346 |
13 | // NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. / | function upgradeTo(address newImplementation) external virtual ifAdmin {
_upgradeTo(newImplementation);
}
| function upgradeTo(address newImplementation) external virtual ifAdmin {
_upgradeTo(newImplementation);
}
| 2,952 |
70 | // Defines the initial contract | constructor () public ERC20Detailed("MarbleCoin", "MBC", 18) {
// Generate 100 million tokens in the contract owner's account
mint(msg.sender, 100000000 * MBC);
}
| constructor () public ERC20Detailed("MarbleCoin", "MBC", 18) {
// Generate 100 million tokens in the contract owner's account
mint(msg.sender, 100000000 * MBC);
}
| 28,117 |
67 | // withdraw your reward | function withdrawRewards() public {
( uint256 amount, uint256 tax ) = calculateReward(msg.sender);
require(amount > 0, "No rewards for this address");
uint256 WithdrawingStartTime = government.getWithdrawingStartTime();
require(now > WithdrawingStartTime, "Can withdraw after staking time");
//update total reward collected
userRewardInfo[msg.sender].totalWithdrawn = getTotalRewardCollectedByUser(msg.sender).add(amount);
userRewardInfo[msg.sender].lastWithdrawTime = now;
//transfer amount to user
ris3.transfer(msg.sender, amount);
//transfer tax to tax taxPool
ris3.transfer(taxPoolAddress, tax);
emit Withdrawn(msg.sender, amount);
}
| function withdrawRewards() public {
( uint256 amount, uint256 tax ) = calculateReward(msg.sender);
require(amount > 0, "No rewards for this address");
uint256 WithdrawingStartTime = government.getWithdrawingStartTime();
require(now > WithdrawingStartTime, "Can withdraw after staking time");
//update total reward collected
userRewardInfo[msg.sender].totalWithdrawn = getTotalRewardCollectedByUser(msg.sender).add(amount);
userRewardInfo[msg.sender].lastWithdrawTime = now;
//transfer amount to user
ris3.transfer(msg.sender, amount);
//transfer tax to tax taxPool
ris3.transfer(taxPoolAddress, tax);
emit Withdrawn(msg.sender, amount);
}
| 1,470 |
309 | // Executes a swap on 0x/swapData encoded swap data | function executeZeroExSwap(ExternalSwapData calldata swapData)
external
payable
nonReentrant
whenNotPaused
isValidReferee(swapData.referee)
| function executeZeroExSwap(ExternalSwapData calldata swapData)
external
payable
nonReentrant
whenNotPaused
isValidReferee(swapData.referee)
| 30,483 |
16 | // getTokenURI() postfixed with the token ID baseTokenURI(){tokenID}/tokenId Token ID/ return uri where token data can be retrieved | function getTokenURI(uint tokenId)
public virtual override view
returns (string memory)
{
return string(abi.encodePacked(getBaseTokenURI(), tokenId));
}
| function getTokenURI(uint tokenId)
public virtual override view
returns (string memory)
{
return string(abi.encodePacked(getBaseTokenURI(), tokenId));
}
| 27,166 |
24 | // Fetches the revenue of central bank commission by transaction type _txType transaction typereturn revenue / | function getCBRevnuePerTransactionType(TxType _txType) override public view returns(uint256 revenue) {
revenue = CB_Fees[_txType].revenue;
return revenue;
}
| function getCBRevnuePerTransactionType(TxType _txType) override public view returns(uint256 revenue) {
revenue = CB_Fees[_txType].revenue;
return revenue;
}
| 6,337 |
210 | // Claim rewards from multiple pools. Callable by anyone. _pids An array of pool identifiers. _beneficiary The address to claim for. / | function claimMultiple(
uint256[] calldata _pids,
address _beneficiary
| function claimMultiple(
uint256[] calldata _pids,
address _beneficiary
| 33,238 |
144 | // handle the transfer of reward tokens via `transferFrom` to reduce the number of transactions required and ensure correctness of the reward amount | ERC20Upgradeable(_rewardsToken).safeTransferFrom(msg.sender, address(this), reward);
if (block.timestamp >= rewardData[_rewardsToken].periodFinish) {
rewardData[_rewardsToken].rewardRate = reward / rewardData[_rewardsToken].rewardsDuration;
} else {
| ERC20Upgradeable(_rewardsToken).safeTransferFrom(msg.sender, address(this), reward);
if (block.timestamp >= rewardData[_rewardsToken].periodFinish) {
rewardData[_rewardsToken].rewardRate = reward / rewardData[_rewardsToken].rewardsDuration;
} else {
| 42,570 |
0 | // La dirección del contrato de adopción que se probará | Adoption adoption = Adoption(DeployedAddresses.Adoption());
| Adoption adoption = Adoption(DeployedAddresses.Adoption());
| 11,352 |
134 | // no escrow actions - escrow remains on L2 | emit WithdrawalCompleted(account, amount);
| emit WithdrawalCompleted(account, amount);
| 42,171 |
269 | // tokenid => creator address | mapping(uint256 => address) public creator;
function setBaseURI(string memory baseURI_) external onlyOwner {
super._setBaseURI(baseURI_);
}
| mapping(uint256 => address) public creator;
function setBaseURI(string memory baseURI_) external onlyOwner {
super._setBaseURI(baseURI_);
}
| 43,707 |
12 | // Sage path | function isSagePathUser(address user) public view returns (bool isIndeed) {
return _meetsSagePathThreshold(user);
}
| function isSagePathUser(address user) public view returns (bool isIndeed) {
return _meetsSagePathThreshold(user);
}
| 22,514 |
38 | // This method can be used by the controller to extract mistakenly/sent tokens to this contract./_token The address of the token contract that you want to recover/set to 0 in case you want to extract ether. | function claimTokens(address _token) onlyController {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
ERC20Token token = ERC20Token(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
| function claimTokens(address _token) onlyController {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
ERC20Token token = ERC20Token(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
| 19,580 |
26 | // Checks the mint eligibility based on the current phase.return mintEligibility True if the user is eligible to mint, false otherwise. / | function _getWLMintEligibilityAtCurrentPhase(
address _user,
bytes32[] memory _proof
| function _getWLMintEligibilityAtCurrentPhase(
address _user,
bytes32[] memory _proof
| 10,436 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.